VariablesSniff.php 2.37 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Sniffs\Less;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;

/**
 * Class VariablesSniff
 *
 * Ensure that the variables are responds to the following requirements:
 * - If variables are local and used only in a module scope,
 *   they should be located in the module file, in the beginning of the general comment.
 * - All variable names must be lowercase
 *
 * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#local-variables
 * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#naming
 */
class VariablesSniff implements Sniff
{
    /**
     * A list of tokenizers this sniff supports.
     *
     * @var array
     */
    public $supportedTokenizers = [TokenizerSymbolsInterface::TOKENIZER_CSS];

    /**
     * @inheritdoc
     */
    public function register()
    {
        return [T_ASPERAND];
    }

    /**
     * @inheritdoc
     */
    public function process(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $currentToken = $tokens[$stackPtr];

        $nextColon = $phpcsFile->findNext(T_COLON, $stackPtr);
        $nextSemicolon = $phpcsFile->findNext(T_SEMICOLON, $stackPtr);
        if ((false === $nextColon) || (false === $nextSemicolon)) {
            return;
        }

        $isVariableDeclaration = ($currentToken['line'] === $tokens[$nextColon]['line'])
            && ($currentToken['line'] === $tokens[$nextSemicolon]['line'])
            && (T_STRING === $tokens[$stackPtr + 1]['code'])
            && (T_COLON === $tokens[$stackPtr + 2]['code']);

        if (!$isVariableDeclaration) {
            return;
        }

        $classBefore = $phpcsFile->findPrevious(T_STYLE, $stackPtr);
        if (false !== $classBefore) {
            $phpcsFile->addError(
                'Variable declaration located not in the beginning of general comments',
                $stackPtr,
                'VariableLocation'
            );
        }

        $variableName = $tokens[$stackPtr + 1]['content'];
        if (preg_match('/[A-Z]/', $variableName)) {
            $phpcsFile->addError(
                'Variable declaration contains uppercase symbols',
                $stackPtr,
                'VariableUppercase'
            );
        }
    }
}