|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento2\Sniffs\PHP; |
| 9 | + |
| 10 | +use PHP_CodeSniffer\Files\File; |
| 11 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 12 | + |
| 13 | +/** |
| 14 | + * Sniff to validate array autovivification. |
| 15 | + */ |
| 16 | +class ArrayAutovivificationSniff implements Sniff |
| 17 | +{ |
| 18 | + /** |
| 19 | + * String representation of error. |
| 20 | + * |
| 21 | + * @var string |
| 22 | + */ |
| 23 | + private $warningMessage = 'Deprecated: Automatic conversion of false to array is deprecated.'; |
| 24 | + |
| 25 | + /** |
| 26 | + * Warning violation code. |
| 27 | + * |
| 28 | + * @var string |
| 29 | + */ |
| 30 | + private $warningCode = 'Autovivification'; |
| 31 | + |
| 32 | + /** |
| 33 | + * @inheritdoc |
| 34 | + */ |
| 35 | + public function register(): array |
| 36 | + { |
| 37 | + return [ |
| 38 | + T_VARIABLE |
| 39 | + ]; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @inheritdoc |
| 44 | + */ |
| 45 | + public function process(File $phpcsFile, $stackPtr): void |
| 46 | + { |
| 47 | + $positionSquareBracket = $phpcsFile->findNext(T_OPEN_SQUARE_BRACKET, $stackPtr, $stackPtr + 2); |
| 48 | + |
| 49 | + if ($positionSquareBracket) { |
| 50 | + $tokens = $phpcsFile->getTokens(); |
| 51 | + $positionFunction = $phpcsFile->findPrevious(T_FUNCTION, $positionSquareBracket) ?: 0; |
| 52 | + $sliceLength = $stackPtr - $positionFunction; |
| 53 | + $sliceToken = array_slice(array_column($tokens, 'content'), $positionFunction, $sliceLength, true); |
| 54 | + $propertyTokenKey = array_keys($sliceToken, $tokens[$stackPtr]['content']); |
| 55 | + |
| 56 | + arsort($propertyTokenKey); |
| 57 | + |
| 58 | + foreach ($propertyTokenKey as $tokenKey) { |
| 59 | + if ($tokens[$tokenKey + 2]['content'] === '=') { |
| 60 | + if ($tokens[$tokenKey + 4]['content'] != 'false') { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + $phpcsFile->addWarning($this->warningMessage, $positionSquareBracket, $this->warningCode); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments