forked from magento/magento-coding-standard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForeachArrayMergeSniff.php
75 lines (65 loc) · 1.83 KB
/
ForeachArrayMergeSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* Copyright © Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Sniffs\Performance;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
/**
* Detects array_merge(...) is used in a loop and is a resources greedy construction.
*/
class ForeachArrayMergeSniff implements Sniff
{
/**
* String representation of warning.
*
* @var string
*/
protected $warningMessage = 'array_merge(...) is used in a loop and is a resources greedy construction.';
/**
* Warning violation code.
*
* @var string
*/
protected $warningCode = 'ForeachArrayMerge';
/**
* @var array
*/
protected $foreachCache = [];
/**
* @inheritdoc
*/
public function register()
{
return [T_FOREACH, T_FOR];
}
/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// If it's inline control structure we do nothing. PSR2 issue will be raised.
if (!array_key_exists('scope_opener', $tokens[$stackPtr])) {
return;
}
$scopeOpener = $tokens[$stackPtr]['scope_opener'];
$scopeCloser = $tokens[$stackPtr]['scope_closer'];
for ($i = $scopeOpener; $i < $scopeCloser; $i++) {
$tag = $tokens[$i];
if ($tag['code'] !== T_STRING) {
continue;
}
if ($tag['content'] !== 'array_merge') {
continue;
}
$cacheKey = $phpcsFile->getFilename() . $i;
if (isset($this->foreachCache[$cacheKey])) {
continue;
}
$this->foreachCache[$cacheKey] = '';
$phpcsFile->addWarning($this->warningMessage, $i, $this->warningCode);
}
}
}