VariablesSniff.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sniffs\Less;
  7. use PHP_CodeSniffer\Sniffs\Sniff;
  8. use PHP_CodeSniffer\Files\File;
  9. /**
  10. * Class VariablesSniff
  11. *
  12. * Ensure that the variables are responds to the following requirements:
  13. * - If variables are local and used only in a module scope,
  14. * they should be located in the module file, in the beginning of the general comment.
  15. * - All variable names must be lowercase
  16. *
  17. * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#local-variables
  18. * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#naming
  19. */
  20. class VariablesSniff implements Sniff
  21. {
  22. /**
  23. * A list of tokenizers this sniff supports.
  24. *
  25. * @var array
  26. */
  27. public $supportedTokenizers = [TokenizerSymbolsInterface::TOKENIZER_CSS];
  28. /**
  29. * @inheritdoc
  30. */
  31. public function register()
  32. {
  33. return [T_ASPERAND];
  34. }
  35. /**
  36. * @inheritdoc
  37. */
  38. public function process(File $phpcsFile, $stackPtr)
  39. {
  40. $tokens = $phpcsFile->getTokens();
  41. $currentToken = $tokens[$stackPtr];
  42. $nextColon = $phpcsFile->findNext(T_COLON, $stackPtr);
  43. $nextSemicolon = $phpcsFile->findNext(T_SEMICOLON, $stackPtr);
  44. if ((false === $nextColon) || (false === $nextSemicolon)) {
  45. return;
  46. }
  47. $isVariableDeclaration = ($currentToken['line'] === $tokens[$nextColon]['line'])
  48. && ($currentToken['line'] === $tokens[$nextSemicolon]['line'])
  49. && (T_STRING === $tokens[$stackPtr + 1]['code'])
  50. && (T_COLON === $tokens[$stackPtr + 2]['code']);
  51. if (!$isVariableDeclaration) {
  52. return;
  53. }
  54. $classBefore = $phpcsFile->findPrevious(T_STYLE, $stackPtr);
  55. if (false !== $classBefore) {
  56. $phpcsFile->addError(
  57. 'Variable declaration located not in the beginning of general comments',
  58. $stackPtr,
  59. 'VariableLocation'
  60. );
  61. }
  62. $variableName = $tokens[$stackPtr + 1]['content'];
  63. if (preg_match('/[A-Z]/', $variableName)) {
  64. $phpcsFile->addError(
  65. 'Variable declaration contains uppercase symbols',
  66. $stackPtr,
  67. 'VariableUppercase'
  68. );
  69. }
  70. }
  71. }