ColourDefinitionSniff.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 ColourDefinitionSniff
  11. *
  12. * Ensure that hexadecimal values are used for variables not for properties
  13. *
  14. * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#hexadecimal-notation
  15. */
  16. class ColourDefinitionSniff implements Sniff
  17. {
  18. /**
  19. * A list of tokenizers this sniff supports.
  20. *
  21. * @var array
  22. */
  23. public $supportedTokenizers = [TokenizerSymbolsInterface::TOKENIZER_CSS];
  24. /**
  25. * @inheritdoc
  26. */
  27. public function register()
  28. {
  29. return [T_COLOUR];
  30. }
  31. /**
  32. * @inheritdoc
  33. */
  34. public function process(File $phpcsFile, $stackPtr)
  35. {
  36. $tokens = $phpcsFile->getTokens();
  37. $colour = $tokens[$stackPtr]['content'];
  38. $variablePtr = $phpcsFile->findPrevious(T_ASPERAND, $stackPtr);
  39. if ((false === $variablePtr) || ($tokens[$stackPtr]['line'] !== $tokens[$variablePtr]['line'])) {
  40. $phpcsFile->addError('Hexadecimal value should be used for variable', $stackPtr, 'NotInVariable');
  41. }
  42. $expected = strtolower($colour);
  43. if ($colour !== $expected) {
  44. $error = 'CSS colours must be defined in lowercase; expected %s but found %s';
  45. $phpcsFile->addError($error, $stackPtr, 'NotLower', [$expected, $colour]);
  46. }
  47. // Now check if shorthand can be used.
  48. if (strlen($colour) !== 7) {
  49. return;
  50. }
  51. if ($colour[1] === $colour[2] && $colour[3] === $colour[4] && $colour[5] === $colour[6]) {
  52. $expected = '#' . $colour[1] . $colour[3] . $colour[5];
  53. $error = 'CSS colours must use shorthand if available; expected %s but found %s';
  54. $phpcsFile->addError($error, $stackPtr, 'Shorthand', [$expected, $colour]);
  55. }
  56. }
  57. }