diff --git a/Magento2/Sniffs/Performance/ForeachArrayMergeSniff.php b/Magento2/Sniffs/Performance/ForeachArrayMergeSniff.php new file mode 100644 index 00000000..eae75006 --- /dev/null +++ b/Magento2/Sniffs/Performance/ForeachArrayMergeSniff.php @@ -0,0 +1,71 @@ +getTokens(); + + $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); + } + } +} diff --git a/Magento2/Tests/Performance/ForeachArrayMergeUnitTest.inc b/Magento2/Tests/Performance/ForeachArrayMergeUnitTest.inc new file mode 100644 index 00000000..02aa5093 --- /dev/null +++ b/Magento2/Tests/Performance/ForeachArrayMergeUnitTest.inc @@ -0,0 +1,43 @@ + 'value', + 1 => 'value2', +]; + +$options = []; + +foreach ([] as $collection) { + foreach ($configurationSources as $source) { + $options = array_merge($options, $source); + } +} + +$options = []; +$itemCount = count($configurationSources); +for ($i = 0; $i <= $itemCount; $i++) { + $source = $options[$itemCount]; + $options = array_merge($options, $source); +} + +class SelectBuilder +{ + private $columns = []; + + public function getColumns() + { + return $this->columns; + } + + public function setColumns(array $columns) + { + $this->columns = $columns; + } +} + +$selectBuilder = new SelectBuilder(); + +foreach ([] as $collection) { + foreach ($configurationSources as $source) { + $selectBuilder->setColumns(array_merge($selectBuilder->getColumns(), $source)); + } +} diff --git a/Magento2/Tests/Performance/ForeachArrayMergeUnitTest.php b/Magento2/Tests/Performance/ForeachArrayMergeUnitTest.php new file mode 100644 index 00000000..16273883 --- /dev/null +++ b/Magento2/Tests/Performance/ForeachArrayMergeUnitTest.php @@ -0,0 +1,35 @@ + 1, + 19 => 1, + 41 => 1 + ]; + } +} diff --git a/Magento2/ruleset.xml b/Magento2/ruleset.xml index 2f9e5f4b..ec705c70 100644 --- a/Magento2/ruleset.xml +++ b/Magento2/ruleset.xml @@ -235,6 +235,10 @@ 7 warning + + 7 + warning + 7 warning