Skip to content

Commit eecaa67

Browse files
author
Lars Roettig
committed
#20: add parrent
1 parent 9d1205c commit eecaa67

File tree

3 files changed

+34
-8
lines changed

3 files changed

+34
-8
lines changed

Magento2/Sniffs/Performance/ForeachArrayMergeSniff.php

+13-4
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class ForeachArrayMergeSniff implements Sniff
1616
*
1717
* @var string
1818
*/
19-
protected $warningMessage = 'Array merge is slow in each functions. ';
19+
protected $warningMessage = 'array_merge(...) is used in a loop and is a resources greedy construction.';
2020

2121
/**
2222
* Warning violation code.
@@ -25,6 +25,11 @@ class ForeachArrayMergeSniff implements Sniff
2525
*/
2626
protected $warningCode = 'ForeachArrayMerge';
2727

28+
/**
29+
* @var array
30+
*/
31+
protected $foreachCache = [];
32+
2833
/**
2934
* @inheritdoc
3035
*/
@@ -41,10 +46,9 @@ public function process(File $phpcsFile, $stackPtr)
4146
$tokens = $phpcsFile->getTokens();
4247

4348
$scopeOpener = $tokens[$stackPtr]['scope_opener'];
44-
$scopeCloser = $tokens[$stackPtr]['scope_closer'] ;
49+
$scopeCloser = $tokens[$stackPtr]['scope_closer'];
4550

46-
for ($i = $scopeOpener; $i < $scopeCloser; $i++)
47-
{
51+
for ($i = $scopeOpener; $i < $scopeCloser; $i++) {
4852
$tag = $tokens[$i];
4953
if ($tag['code'] !== T_STRING) {
5054
continue;
@@ -53,6 +57,11 @@ public function process(File $phpcsFile, $stackPtr)
5357
continue;
5458
}
5559

60+
$cacheKey = $phpcsFile->getFilename() . $i;
61+
if (isset($this->foreachCache[$cacheKey])) {
62+
continue;
63+
}
64+
5665
$phpcsFile->addWarning($this->warningMessage, $i, $this->warningCode);
5766
}
5867
}

Magento2/Tests/Performance/ForeachArrayMergeUnitTest.inc

+19-2
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ $configurationSources = [
55
];
66

77
$options = [];
8-
foreach ($configurationSources as $source) {
9-
$options = array_merge($options, $source);
8+
9+
foreach ([] as $collection) {
10+
foreach ($configurationSources as $source) {
11+
$options = array_merge($options, $source);
12+
}
1013
}
1114

1215
$options = [];
@@ -15,3 +18,17 @@ for ($i = 0; $i <= $itemCount; $i++) {
1518
$source = $options[$itemCount];
1619
$options = array_merge($options, $source));
1720
}
21+
22+
class CSV
23+
{
24+
public static function getColumns()
25+
{
26+
return [];
27+
}
28+
}
29+
30+
foreach ([] as $collection) {
31+
foreach ($configurationSources as $source) {
32+
$options = array_merge(CSV::getColumns(), $source);
33+
}
34+
}

Magento2/Tests/Performance/ForeachArrayMergeUnitTest.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ public function getErrorList()
2626
public function getWarningList()
2727
{
2828
return [
29-
9 => 1,
30-
16 => 1,
29+
11 => 1,
30+
19 => 1,
3131
];
3232
}
3333
}

0 commit comments

Comments
 (0)