Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
All Data Structures Namespaces Files Functions Variables Pages
PropertiesSortingSniff.php
Go to the documentation of this file.
1 <?php
6 namespace Magento\Sniffs\Less;
7 
8 use PHP_CodeSniffer\Sniffs\Sniff;
9 use PHP_CodeSniffer\Files\File;
10 
19 class PropertiesSortingSniff implements Sniff
20 {
27 
33  private $properties = [];
34 
40  private $styleSymbolsToSkip = [
43  ];
44 
48  public function register()
49  {
50  return [
51  T_OPEN_CURLY_BRACKET,
52  T_CLOSE_CURLY_BRACKET,
53  T_OPEN_PARENTHESIS,
54  T_CLOSE_PARENTHESIS,
55  T_STYLE
56  ];
57  }
58 
62  public function process(File $phpcsFile, $stackPtr)
63  {
64  $tokens = $phpcsFile->getTokens();
65  $currentToken = $tokens[$stackPtr];
66 
67  // if variables, mixins, extends area used - skip
68  if ((T_ASPERAND === $tokens[$stackPtr - 1]['code'])
69  || in_array($tokens[$stackPtr]['content'], $this->styleSymbolsToSkip)
70  ) {
71  return;
72  }
73 
74  $nextCurlyBracket = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, $stackPtr + 1);
75  if (in_array($currentToken['code'], [T_OPEN_CURLY_BRACKET, T_CLOSE_CURLY_BRACKET])
76  || ((false !== $nextCurlyBracket) && ($tokens[$nextCurlyBracket]['line'] === $tokens[$stackPtr]['line']))
77  ) {
78  if ($this->properties) {
79  // validate collected properties before erase them
80  $this->validatePropertiesSorting($phpcsFile, $stackPtr, $this->properties);
81  }
82 
83  $this->properties = [];
84  return;
85  }
86 
87  if (T_STYLE === $currentToken['code']) {
88  $this->properties[] = $currentToken['content'];
89  }
90  }
91 
101  private function validatePropertiesSorting(File $phpcsFile, $stackPtr, array $properties)
102  {
103  // Fix needed for cases when incorrect properties passed for validation due to bug in PHP tokens.
104  $symbolsForSkip = ['(', 'block', 'field'];
105  $properties = array_filter(
106  $properties,
107  function ($var) use ($symbolsForSkip) {
108  return !in_array($var, $symbolsForSkip);
109  }
110  );
111 
112  $originalProperties = $properties;
113  sort($properties);
114 
115  if ($originalProperties !== $properties) {
116  $delimiter = $phpcsFile->findPrevious(T_SEMICOLON, $stackPtr);
117  $phpcsFile->addError('Properties sorted not alphabetically', $delimiter, 'PropertySorting');
118  }
119  }
120 }
$properties
Definition: categories.php:26
$tokens
Definition: cards_list.phtml:9