Skip to content

Commit e386ceb

Browse files
authored
Fix patch + add check for invalid data
1 parent 39b0606 commit e386ceb

File tree

1 file changed

+13
-23
lines changed

1 file changed

+13
-23
lines changed

Setup/Patch/Data/PopulateCategoryCodeV1.php

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
use Magento\Catalog\Model\Category;
1212
use Magento\Catalog\Model\ResourceModel\Category as ResourceCategory;
1313
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
14+
use Magento\Framework\Exception\LocalizedException;
15+
use Magento\Framework\Phrase;
1416
use Magento\Framework\Setup\Patch\DataPatchInterface;
1517

1618
use function str_replace;
@@ -39,21 +41,7 @@ public function getAliases(): array
3941
public function apply(): self
4042
{
4143
$collection = $this->collecionFactory->create();
42-
$categories = $collection->addAttributeToSelect([
43-
'entity_id',
44-
'description',
45-
'name',
46-
'url',
47-
'category_code',
48-
'path',
49-
'path_ids',
50-
'url_key',
51-
'is_active',
52-
'include_in_menu',
53-
'meta_title',
54-
'store_id',
55-
'parent_id'
56-
])->getItems();
44+
$categories = $collection->addAttributeToSelect(['entity_id', 'name', 'category_code', 'path'])->getItems();
5745

5846
$idsToName = [];
5947
/** @var Category $category */
@@ -64,18 +52,20 @@ public function apply(): self
6452
/** @var Category $category */
6553
foreach ($categories as $category) {
6654
if (!$category->getData('category_code')) {
67-
$code = '';
55+
$code = [];
6856
foreach ($category->getPathIds() as $pathId) {
69-
if ($pathId !== '1') {
70-
if ($code === '') {
71-
$code = $idsToName[$pathId];
72-
} else {
73-
$code .= '_' . $idsToName[$pathId];
74-
}
57+
if ($pathId === '') {
58+
throw new LocalizedException(
59+
new Phrase(
60+
'Category "%1" has an invalid path: %2.',
61+
[$category->getName(), $category->getPath()]
62+
)
63+
);
7564
}
65+
$code[] = $idsToName[$pathId];
7666
}
7767

78-
$category->setCustomAttribute('category_code', strtolower(str_replace(' ', '_', $code)));
68+
$category->setCustomAttribute('category_code', strtolower(str_replace(' ', '_', implode('_', $code))));
7969
$this->resourceCategory->saveAttribute($category, 'category_code');
8070
}
8171
}

0 commit comments

Comments
 (0)