Skip to content

[Performance] Fix array merge in loop #30153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ public function __construct(
protected function initTypeModels()
{
$productTypes = $this->_exportConfig->getEntityTypes(CatalogProduct::ENTITY);
$disabledAttrs = [];
$indexValueAttributes = [];
foreach ($productTypes as $productTypeName => $productTypeConfig) {
if (!($model = $this->_typeFactory->create($productTypeConfig['model']))) {
throw new \Magento\Framework\Exception\LocalizedException(
Expand All @@ -174,21 +176,19 @@ protected function initTypeModels()
}
if ($model->isSuitable()) {
$this->_productTypeModels[$productTypeName] = $model;
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$this->_disabledAttrs = array_merge($this->_disabledAttrs, $model->getDisabledAttrs());
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$this->_indexValueAttributes = array_merge(
$this->_indexValueAttributes,
$model->getIndexValueAttributes()
);
$disabledAttrs[] = $model->getDisabledAttrs();
$indexValueAttributes[] = $model->getIndexValueAttributes();
}
}
if (!$this->_productTypeModels) {
throw new \Magento\Framework\Exception\LocalizedException(
__('There are no product types available for export')
);
}
$this->_disabledAttrs = array_unique($this->_disabledAttrs);
$this->_disabledAttrs = array_unique(array_merge([], $this->_disabledAttrs, ...$disabledAttrs));
$this->_indexValueAttributes = array_unique(
array_merge([], $this->_indexValueAttributes, ...$indexValueAttributes)
);
return $this;
}

Expand Down Expand Up @@ -518,6 +518,8 @@ protected function getTierPrices(array $listSku, $table)
if (isset($this->_parameters[\Magento\ImportExport\Model\Export::FILTER_ELEMENT_GROUP])) {
$exportFilter = $this->_parameters[\Magento\ImportExport\Model\Export::FILTER_ELEMENT_GROUP];
}
$selectFields = [];
$exportData = false;
if ($table == ImportAdvancedPricing::TABLE_TIER_PRICE) {
$selectFields = [
ImportAdvancedPricing::COL_SKU => 'cpe.sku',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ public function process(string $encodedMessage)
$status = OperationInterface::STATUS_TYPE_COMPLETE;
$errorCode = null;
$messages = [];
$entityParams = [];
$topicName = $operation->getTopicName();
$handlers = $this->configuration->getHandlers($topicName);
try {
Expand All @@ -127,7 +128,7 @@ public function process(string $encodedMessage)
$this->logger->error($e->getMessage());
$status = OperationInterface::STATUS_TYPE_NOT_RETRIABLY_FAILED;
$errorCode = $e->getCode();
$messages[] = $e->getMessage();
$messages[] = [$e->getMessage()];
}

$outputData = null;
Expand All @@ -136,9 +137,7 @@ public function process(string $encodedMessage)
$result = $this->executeHandler($callback, $entityParams);
$status = $result['status'];
$errorCode = $result['error_code'];
// phpcs:disable Magento2.Performance.ForeachArrayMerge
$messages = array_merge($messages, $result['messages']);
// phpcs:enable Magento2.Performance.ForeachArrayMerge
$messages[] = $result['messages'];
$outputData = $result['output_data'];
}
}
Expand All @@ -157,7 +156,7 @@ public function process(string $encodedMessage)
);
$outputData = $this->jsonHelper->serialize($outputData);
} catch (\Exception $e) {
$messages[] = $e->getMessage();
$messages[] = [$e->getMessage()];
}
}

Expand All @@ -167,7 +166,7 @@ public function process(string $encodedMessage)
$operation->getId(),
$status,
$errorCode,
implode('; ', $messages),
implode('; ', array_merge([], ...$messages)),
$serializedData,
$outputData
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,10 @@ public function testGetterAmount($amountForBundle, $optionList, $expectedResult)

$optionSelections = [];
foreach ($options as $option) {
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$optionSelections = array_merge($optionSelections, $option->getSelections());
$optionSelections[] = $option->getSelections();
}
$optionSelections = array_merge([], ...$optionSelections);

$this->selectionPriceListProvider->expects($this->any())->method('getPriceList')->willReturn($optionSelections);

$price = $this->createMock(BundleOptionPrice::class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -603,19 +603,15 @@ protected function populateInsertOptionValues(array $optionIds): array
if ($assoc['position'] == $this->_cachedOptions[$entityId][$key]['index']
&& $assoc['parent_id'] == $entityId) {
$option['parent_id'] = $entityId;
//phpcs:ignore Magento2.Performance.ForeachArrayMerge
$optionValues = array_merge(
$optionValues,
$this->populateOptionValueTemplate($option, $optionId)
);
$optionValues[] = $this->populateOptionValueTemplate($option, $optionId);
$this->_cachedOptions[$entityId][$key]['option_id'] = $optionId;
break;
}
}
}
}

return $optionValues;
return array_merge([], ...$optionValues);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,13 @@ public function build($storeId, $changedIds, $valueFieldSuffix)
//Create list of temporary tables based on available attributes attributes
$valueTables = [];
foreach ($temporaryEavAttributes as $tableName => $columns) {
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$valueTables = array_merge(
$valueTables,
$this->_createTemporaryTable($this->_getTemporaryTableName($tableName), $columns, $valueFieldSuffix)
$valueTables[] = $this->_createTemporaryTable(
$this->_getTemporaryTableName($tableName),
$columns,
$valueFieldSuffix
);
}
$valueTables = array_merge([], ...$valueTables);

//Fill "base" table which contains all available products
$this->_fillTemporaryEntityTable($entityTableName, $entityTableColumns, $changedIds);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,11 @@ public function testSaveCategoryLinks($newCategoryLinks, $dbCategoryLinks, $affe
$expectedResult = [];

foreach ($affectedIds as $type => $ids) {
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$expectedResult = array_merge($expectedResult, $ids);
$expectedResult[] = $ids;
// Verify if the correct insert, update and/or delete actions are performed:
$this->setupExpectationsForConnection($type, $ids);
}
$expectedResult = array_merge([], ...$expectedResult);

$actualResult = $this->model->saveCategoryLinks($product, $newCategoryLinks);

Expand Down
19 changes: 9 additions & 10 deletions app/code/Magento/CatalogImportExport/Model/Export/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,8 @@ protected function initCategories()
protected function initTypeModels()
{
$productTypes = $this->_exportConfig->getEntityTypes($this->getEntityTypeCode());
$disabledAttrs = [];
$indexValueAttributes = [];
foreach ($productTypes as $productTypeName => $productTypeConfig) {
if (!($model = $this->_typeFactory->create($productTypeConfig['model']))) {
throw new \Magento\Framework\Exception\LocalizedException(
Expand All @@ -494,21 +496,19 @@ protected function initTypeModels()
}
if ($model->isSuitable()) {
$this->_productTypeModels[$productTypeName] = $model;
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$this->_disabledAttrs = array_merge($this->_disabledAttrs, $model->getDisabledAttrs());
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$this->_indexValueAttributes = array_merge(
$this->_indexValueAttributes,
$model->getIndexValueAttributes()
);
$disabledAttrs[] = $model->getDisabledAttrs();
$indexValueAttributes[] = $model->getIndexValueAttributes();
}
}
if (!$this->_productTypeModels) {
throw new \Magento\Framework\Exception\LocalizedException(
__('There are no product types available for export.')
);
}
$this->_disabledAttrs = array_unique($this->_disabledAttrs);
$this->_disabledAttrs = array_unique(array_merge([], $this->_disabledAttrs, ...$disabledAttrs));
$this->_indexValueAttributes = array_unique(
array_merge([], $this->_indexValueAttributes, ...$indexValueAttributes)
);

return $this;
}
Expand Down Expand Up @@ -1128,7 +1128,7 @@ private function wrapValue($value)
protected function collectMultirawData()
{
$data = [];
$productIds = [];
$productLinkIds = [];
$rowWebsites = [];
$rowCategories = [];

Expand All @@ -1138,7 +1138,6 @@ protected function collectMultirawData()
/** @var \Magento\Catalog\Model\Product $item */
foreach ($collection as $item) {
$productLinkIds[] = $item->getData($this->getProductEntityLinkField());
$productIds[] = $item->getId();
$rowWebsites[$item->getId()] = array_intersect(
array_keys($this->_websiteIdToCode),
$item->getWebsites()
Expand Down
11 changes: 6 additions & 5 deletions app/code/Magento/CatalogImportExport/Model/Import/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,8 @@ private function initImagesArrayKeys()
protected function _initTypeModels()
{
$productTypes = $this->_importConfig->getEntityTypes($this->getEntityTypeCode());
$fieldsMap = [];
$specialAttributes = [];
foreach ($productTypes as $productTypeName => $productTypeConfig) {
$params = [$this, $productTypeName];
if (!($model = $this->_productTypeFactory->create($productTypeConfig['model'], ['params' => $params]))
Expand All @@ -1231,14 +1233,13 @@ protected function _initTypeModels()
if ($model->isSuitable()) {
$this->_productTypeModels[$productTypeName] = $model;
}
// phpcs:disable Magento2.Performance.ForeachArrayMerge.ForeachArrayMerge
$this->_fieldsMap = array_merge($this->_fieldsMap, $model->getCustomFieldsMapping());
$this->_specialAttributes = array_merge($this->_specialAttributes, $model->getParticularAttributes());
// phpcs:enable
$fieldsMap[] = $model->getCustomFieldsMapping();
$specialAttributes[] = $model->getParticularAttributes();
}
$this->_fieldsMap = array_merge([], $this->_fieldsMap, ...$fieldsMap);
$this->_initErrorTemplates();
// remove doubles
$this->_specialAttributes = array_unique($this->_specialAttributes);
$this->_specialAttributes = array_unique(array_merge([], $this->_specialAttributes, ...$specialAttributes));

return $this;
}
Expand Down
12 changes: 5 additions & 7 deletions app/code/Magento/Config/Model/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,9 @@ public function save()
$deleteTransaction
);

$groupChangedPaths = $this->getChangedPaths($sectionId, $groupId, $groupData, $oldConfig, $extraOldGroups);
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$changedPaths = \array_merge($changedPaths, $groupChangedPaths);
$changedPaths[] = $this->getChangedPaths($sectionId, $groupId, $groupData, $oldConfig, $extraOldGroups);
}
$changedPaths = array_merge([], ...$changedPaths);

try {
$deleteTransaction->delete();
Expand Down Expand Up @@ -356,7 +355,7 @@ private function getChangedPaths(
$field = $this->getField($sectionId, $groupId, $fieldId);
$path = $this->getFieldPath($field, $fieldId, $oldConfig, $extraOldGroups);
if ($this->isValueChanged($oldConfig, $path, $fieldData)) {
$changedPaths[] = $path;
$changedPaths[] = [$path];
}
}
}
Expand All @@ -371,12 +370,11 @@ private function getChangedPaths(
$oldConfig,
$extraOldGroups
);
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$changedPaths = \array_merge($changedPaths, $subGroupChangedPaths);
$changedPaths[] = $subGroupChangedPaths;
}
}

return $changedPaths;
return \array_merge([], ...$changedPaths);
}

/**
Expand Down
16 changes: 6 additions & 10 deletions app/code/Magento/Config/Model/Config/Structure.php
Original file line number Diff line number Diff line change
Expand Up @@ -292,20 +292,16 @@ public function getFieldPathsByAttribute($attributeName, $attributeValue)
foreach ($section['children'] as $group) {
if (isset($group['children'])) {
$path = $section['id'] . '/' . $group['id'];
// phpcs:ignore Magento2.Performance.ForeachArrayMerge.ForeachArrayMerge
$result = array_merge(
$result,
$this->_getGroupFieldPathsByAttribute(
$group['children'],
$path,
$attributeName,
$attributeValue
)
$result[] = $this->_getGroupFieldPathsByAttribute(
$group['children'],
$path,
$attributeName,
$attributeValue
);
}
}
}
return $result;
return array_merge([], ...$result);
}

/**
Expand Down
20 changes: 11 additions & 9 deletions app/code/Magento/Deploy/Package/Processor/PreProcessor/Css.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
use Magento\Deploy\Package\Package;
use Magento\Deploy\Package\PackageFile;
use Magento\Deploy\Package\Processor\ProcessorInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Css\PreProcessor\Instruction\Import;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\ReadInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\View\Url\CssResolver;
use Magento\Framework\View\Asset\Minification;
use Magento\Framework\View\Url\CssResolver;

/**
* Pre-processor for speeding up deployment of CSS files
Expand Down Expand Up @@ -137,7 +137,7 @@ private function buildMap($packagePath, $filePath, $fullPath)

$content = $this->staticDir->readFile($this->minification->addMinifiedSign($fullPath));

$callback = function ($matchContent) use ($packagePath, $filePath, & $imports) {
$callback = function ($matchContent) use ($packagePath, $filePath, &$imports) {
$importRelPath = $this->normalize(pathinfo($filePath, PATHINFO_DIRNAME) . '/' . $matchContent['path']);
$imports[$importRelPath] = $this->normalize(
$packagePath . '/' . pathinfo($filePath, PATHINFO_DIRNAME) . '/' . $matchContent['path']
Expand Down Expand Up @@ -175,15 +175,17 @@ private function buildMap($packagePath, $filePath, $fullPath)
*
* @param string $fileName
* @return array
* phpcs:disable Magento2.Performance.ForeachArrayMerge
*/
private function collectFileMap($fileName)
private function collectFileMap(string $fileName): array
{
$result = isset($this->map[$fileName]) ? $this->map[$fileName] : [];
foreach ($result as $path) {
$result = array_merge($result, $this->collectFileMap($path));
$valueFromMap = $this->map[$fileName] ?? [];
$result = [$valueFromMap];

foreach ($valueFromMap as $path) {
$result[] = $this->collectFileMap($path);
}
return array_unique($result);

return array_unique(array_merge([], ...$result));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,8 @@ public function execute(string $field, string $value): array
$ids = [];
/** @var GetAssetIdsByContentFieldInterface $fieldHandler */
foreach ($this->fieldHandlers[$field] as $fieldHandler) {
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$ids = array_merge($ids, $fieldHandler->execute($value));
$ids[] = $fieldHandler->execute($value);
}
return array_unique($ids);
return array_unique(array_merge([], ...$ids));
}
}
6 changes: 4 additions & 2 deletions app/code/Magento/Sales/Model/AdminOrder/Create.php
Original file line number Diff line number Diff line change
Expand Up @@ -1999,15 +1999,17 @@ protected function _validate()
$this->_errors[] = __('Please specify order items.');
}

$errors = [];
foreach ($items as $item) {
/** @var \Magento\Quote\Model\Quote\Item $item */
$messages = $item->getMessage(false);
if ($item->getHasError() && is_array($messages) && !empty($messages)) {
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
$this->_errors = array_merge($this->_errors, $messages);
$errors[] = $messages;
}
}

$this->_errors = array_merge([], $this->_errors, ...$errors);

if (!$this->getQuote()->isVirtual()) {
if (!$this->getQuote()->getShippingAddress()->getShippingMethod()) {
$this->_errors[] = __('The shipping method is missing. Select the shipping method and try again.');
Expand Down
Loading