11
11
use Magento \Catalog \Model \Category ;
12
12
use Magento \Catalog \Model \ResourceModel \Category as ResourceCategory ;
13
13
use Magento \Catalog \Model \ResourceModel \Category \CollectionFactory ;
14
+ use Magento \Framework \Exception \LocalizedException ;
15
+ use Magento \Framework \Phrase ;
14
16
use Magento \Framework \Setup \Patch \DataPatchInterface ;
15
17
16
18
use function str_replace ;
@@ -39,21 +41,7 @@ public function getAliases(): array
39
41
public function apply (): self
40
42
{
41
43
$ 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 ();
57
45
58
46
$ idsToName = [];
59
47
/** @var Category $category */
@@ -64,18 +52,20 @@ public function apply(): self
64
52
/** @var Category $category */
65
53
foreach ($ categories as $ category ) {
66
54
if (!$ category ->getData ('category_code ' )) {
67
- $ code = '' ;
55
+ $ code = [] ;
68
56
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
+ );
75
64
}
65
+ $ code [] = $ idsToName [$ pathId ];
76
66
}
77
67
78
- $ category ->setCustomAttribute ('category_code ' , strtolower (str_replace (' ' , '_ ' , $ code )));
68
+ $ category ->setCustomAttribute ('category_code ' , strtolower (str_replace (' ' , '_ ' , implode ( ' _ ' , $ code) )));
79
69
$ this ->resourceCategory ->saveAttribute ($ category , 'category_code ' );
80
70
}
81
71
}
0 commit comments