Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. RequireNullCoalesceOperatorSniff.php

function RequireNullCoalesceOperatorSniff::checkIsset

1 call to RequireNullCoalesceOperatorSniff::checkIsset()
RequireNullCoalesceOperatorSniff::process in vendor/slevomat/coding-standard/SlevomatCodingStandard/Sniffs/ControlStructures/RequireNullCoalesceOperatorSniff.php
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint *

File

vendor/slevomat/coding-standard/SlevomatCodingStandard/Sniffs/ControlStructures/RequireNullCoalesceOperatorSniff.php, line 56

Class

RequireNullCoalesceOperatorSniff

Namespace

SlevomatCodingStandard\Sniffs\ControlStructures

Code

public function checkIsset(File $phpcsFile, int $issetPointer) : void {
    $tokens = $phpcsFile->getTokens();
    $previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $issetPointer - 1);
    if ($tokens[$previousPointer]['code'] === T_BOOLEAN_NOT) {
        return;
    }
    if (in_array($tokens[$previousPointer]['code'], Tokens::$booleanOperators, true)) {
        return;
    }
    $openParenthesisPointer = TokenHelper::findNextEffective($phpcsFile, $issetPointer + 1);
    $closeParenthesisPointer = $tokens[$openParenthesisPointer]['parenthesis_closer'];
    
    /** @var int $inlineThenPointer */
    $inlineThenPointer = TokenHelper::findNextEffective($phpcsFile, $closeParenthesisPointer + 1);
    if ($tokens[$inlineThenPointer]['code'] !== T_INLINE_THEN) {
        return;
    }
    $commaPointer = TokenHelper::findNext($phpcsFile, T_COMMA, $openParenthesisPointer + 1, $closeParenthesisPointer);
    if ($commaPointer !== null) {
        return;
    }
    $inlineElsePointer = TernaryOperatorHelper::getElsePointer($phpcsFile, $inlineThenPointer);
    $variableContent = IdentificatorHelper::getContent($phpcsFile, $openParenthesisPointer + 1, $closeParenthesisPointer - 1);
    $thenContent = IdentificatorHelper::getContent($phpcsFile, $inlineThenPointer + 1, $inlineElsePointer - 1);
    if ($variableContent !== $thenContent) {
        return;
    }
    $fix = $phpcsFile->addFixableError('Use null coalesce operator instead of ternary operator.', $inlineThenPointer, self::CODE_NULL_COALESCE_OPERATOR_NOT_USED);
    if (!$fix) {
        return;
    }
    $startPointer = $issetPointer;
    if (in_array($tokens[$previousPointer]['code'], Tokens::$castTokens, true)) {
        $startPointer = $previousPointer;
    }
    $phpcsFile->fixer
        ->beginChangeset();
    FixerHelper::change($phpcsFile, $startPointer, $inlineElsePointer, sprintf('%s ??', $variableContent));
    $phpcsFile->fixer
        ->endChangeset();
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal