AvoidIdSniff.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 AvoidIdSniff
  11. *
  12. * Ensure that id selector is not used
  13. *
  14. * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#types
  15. */
  16. class AvoidIdSniff 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. * Tokens that can appear in a selector
  26. *
  27. * @var array
  28. */
  29. private $selectorTokens = [
  30. T_HASH,
  31. T_WHITESPACE,
  32. T_STRING_CONCAT,
  33. T_OPEN_PARENTHESIS,
  34. T_CLOSE_PARENTHESIS,
  35. T_OPEN_SQUARE_BRACKET,
  36. T_CLOSE_SQUARE_BRACKET,
  37. T_DOUBLE_QUOTED_STRING,
  38. T_CONSTANT_ENCAPSED_STRING,
  39. T_DOUBLE_COLON,
  40. T_COLON,
  41. T_EQUAL,
  42. T_MUL_EQUAL,
  43. T_OR_EQUAL,
  44. T_STRING,
  45. T_NONE,
  46. T_DOLLAR,
  47. T_GREATER_THAN,
  48. T_PLUS,
  49. T_NS_SEPARATOR,
  50. T_LNUMBER,
  51. ];
  52. /**
  53. * @inheritdoc
  54. */
  55. public function register()
  56. {
  57. return [T_HASH];
  58. }
  59. /**
  60. * @inheritdoc
  61. *
  62. * Will flag any selector that looks like the following:
  63. * #foo[bar],
  64. * #foo[bar=bash],
  65. * #foo[bar~=bash],
  66. * #foo[bar$=bash],
  67. * #foo[bar*=bash],
  68. * #foo[bar|=bash],
  69. * #foo[bar='bash'],
  70. * #foo:hover,
  71. * #foo:nth-last-of-type(n),
  72. * #foo::before,
  73. * #foo + div,
  74. * #foo > div,
  75. * #foo ~ div,
  76. * #foo\3Abar ~ div,
  77. * #foo\:bar ~ div,
  78. * #foo.bar .baz,
  79. * div#foo {
  80. * blah: 'abc';
  81. * }
  82. */
  83. public function process(File $phpcsFile, $stackPtr)
  84. {
  85. $tokens = $phpcsFile->getTokens();
  86. // Find the next non-selector token
  87. $nextToken = $phpcsFile->findNext($this->selectorTokens, $stackPtr + 1, null, true);
  88. // Anything except a { or a , means this is not a selector
  89. if ($nextToken !== false && in_array($tokens[$nextToken]['code'], [T_OPEN_CURLY_BRACKET, T_COMMA])) {
  90. $phpcsFile->addError('Id selector is used', $stackPtr, 'IdSelectorUsage');
  91. }
  92. }
  93. }