Skip to content

Commit f75830d

Browse files
committed
Add Sniff for check autovivification on array
1 parent 8f6ddba commit f75830d

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
$propertyTokenKey = array_keys(array_column($tokens, 'content'), $tokens[$stackPtr]['content']);
52+
53+
arsort($propertyTokenKey);
54+
55+
foreach ($propertyTokenKey as $tokenKey) {
56+
if ($tokenKey < $stackPtr && $tokens[$tokenKey + 2]['content'] === '=') {
57+
if ($tokens[$tokenKey + 4]['content'] != 'false') {
58+
return;
59+
}
60+
61+
$phpcsFile->addWarning($this->warningMessage, $positionSquareBracket, $this->warningCode);
62+
}
63+
}
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)