SelectorDelimiterSniff.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 SelectorDelimiterSniff
  11. *
  12. * Ensure that a line break exists after each selector delimiter.
  13. * No spaces should be before or after delimiters.
  14. *
  15. * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#selector-delimiters
  16. */
  17. class SelectorDelimiterSniff implements Sniff
  18. {
  19. /**
  20. * A list of tokenizers this sniff supports.
  21. *
  22. * @var array
  23. */
  24. public $supportedTokenizers = [TokenizerSymbolsInterface::TOKENIZER_CSS];
  25. /**
  26. * @inheritdoc
  27. */
  28. public function register()
  29. {
  30. return [T_COMMA];
  31. }
  32. /**
  33. * @inheritdoc
  34. */
  35. public function process(File $phpcsFile, $stackPtr)
  36. {
  37. $tokens = $phpcsFile->getTokens();
  38. // Check that there's no spaces before delimiter
  39. if ($tokens[$stackPtr - 1]['code'] === T_WHITESPACE) {
  40. $phpcsFile->addError('Spaces should not be before delimiter', $stackPtr - 1, 'SpacesBeforeDelimiter');
  41. }
  42. $this->validateParenthesis($phpcsFile, $stackPtr, $tokens);
  43. }
  44. /**
  45. * Parenthesis validation.
  46. *
  47. * @param File $phpcsFile
  48. * @param int $stackPtr
  49. * @param array $tokens
  50. * @return void
  51. */
  52. private function validateParenthesis(File $phpcsFile, $stackPtr, array $tokens)
  53. {
  54. $nextPtr = $stackPtr + 1;
  55. $nextClassPtr = $phpcsFile->findNext(T_STRING_CONCAT, $nextPtr);
  56. $nextOpenBrace = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, $nextPtr);
  57. if ($nextClassPtr === false || $nextOpenBrace === false) {
  58. return;
  59. }
  60. $stackLine = $tokens[$stackPtr]['line'];
  61. $nextClassLine = $tokens[$nextPtr]['line'];
  62. $nextOpenBraceLine = $tokens[$nextOpenBrace]['line'];
  63. // Check that each class declaration goes from new line
  64. if (($stackLine === $nextClassLine) && ($stackLine === $nextOpenBraceLine)) {
  65. $prevParenthesis = $phpcsFile->findPrevious(T_OPEN_PARENTHESIS, $stackPtr);
  66. $nextParenthesis = $phpcsFile->findNext(T_OPEN_PARENTHESIS, $stackPtr);
  67. if ((false !== $prevParenthesis) && (false !== $nextParenthesis)
  68. && ($tokens[$prevParenthesis]['line'] === $tokens[$stackPtr]['line'])
  69. && ($tokens[$nextParenthesis]['line'] === $tokens[$stackPtr]['line'])
  70. ) {
  71. return;
  72. }
  73. $error = 'Add a line break after each selector delimiter';
  74. $phpcsFile->addError($error, $nextOpenBrace, 'LineBreakAfterDelimiter');
  75. }
  76. }
  77. }