forked from elgentos/magento2-regenerate-catalog-urls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegenerateCategoryUrlCommand.php
209 lines (178 loc) · 7.47 KB
/
RegenerateCategoryUrlCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
declare(strict_types=1);
namespace Elgentos\RegenerateCatalogUrls\Console\Command;
use Elgentos\RegenerateCatalogUrls\Service\RegenerateProductUrl;
use Exception;
use Magento\Framework\App\Area;
use Magento\Framework\Console\Cli;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\App\Emulation;
use Magento\Store\Model\StoreManagerInterface;
use Magento\UrlRewrite\Model\UrlPersistInterface;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Magento\Framework\App\State;
class RegenerateCategoryUrlCommand extends AbstractRegenerateCommand
{
private CategoryUrlRewriteGenerator $categoryUrlRewriteGenerator;
private UrlPersistInterface $urlPersist;
private CategoryCollectionFactory $categoryCollectionFactory;
private Emulation $emulation;
public function __construct(
StoreManagerInterface $storeManager,
State $state,
RegenerateProductUrl $regenerateProductUrl,
QuestionHelper $questionHelper,
CategoryUrlRewriteGenerator $categoryUrlRewriteGenerator,
UrlPersistInterface $urlPersist,
CategoryCollectionFactory $categoryCollectionFactory,
Emulation\Proxy $emulation
) {
parent::__construct($storeManager, $state, $regenerateProductUrl, $questionHelper);
$this->categoryUrlRewriteGenerator = $categoryUrlRewriteGenerator;
$this->urlPersist = $urlPersist;
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->emulation = $emulation;
}
/**
* @return void
*/
protected function configure(): void
{
$this->setName('regenerate:category:url')
->setDescription('Regenerate url for given categories')
->addArgument(
'cids',
InputArgument::IS_ARRAY,
'Categories to regenerate'
)->addOption(
'root',
'r',
InputOption::VALUE_OPTIONAL,
'Regenerate for root category and its children only',
false
);
parent::configure();
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return int
* @throws LocalizedException
*/
public function execute(InputInterface $input, OutputInterface $output): int
{
$this->input = $input;
$this->output = $output;
try {
$this->state->getAreaCode();
} catch (LocalizedException $e) {
$this->state->setAreaCode('adminhtml');
}
$counter = 0;
$stores = $this->getChosenStores();
$rootIdOption = intval($input->getOption('root')) ?: false;
foreach ($stores as $storeId) {
$currentRootId = intval($this->storeManager->getGroup($this->storeManager->getStore($storeId)->getStoreGroupId())->getRootCategoryId());
if($rootIdOption !== false) {
$fromRootId = $rootIdOption;
if($rootIdOption !== $currentRootId) {
$output->writeln(
sprintf('Skipping store %s because its root category id %s, differs from the passed root category %s', $storeId, $currentRootId, $fromRootId)
);
continue;
}
} else {
$fromRootId = $currentRootId;
}
$output->writeln(
sprintf('Processing store %s...', $storeId)
);
$rootCategory = $this->categoryCollectionFactory->create()->addAttributeToFilter('entity_id', $fromRootId)->addAttributeToSelect("name")->getFirstItem();
if(!$rootCategory->getId()) {
throw new \Exception(sprintf("Root category with ID %d, was not found.", $fromRootId));
}
$this->emulation->startEnvironmentEmulation($storeId, Area::AREA_FRONTEND, true);
$categories = $this->categoryCollectionFactory->create()
->setStore($storeId)
->addAttributeToSelect(['name', 'url_path', 'url_key', 'path'])
->addAttributeToFilter('level', ['gt' => 1]);
$categoryIds = $input->getArgument('cids');
if ($fromRootId) {
//path LIKE '1/rootcategory/%' OR path = '1/rootcategory'
$categories->addAttributeToFilter('path', [
'like' => '1/' . $fromRootId . '/%',
'=' => '1/' . $fromRootId
]);
} elseif (!empty($categoryIds)) {
$categories->addAttributeToFilter('entity_id', ['in' => $categoryIds]);
}
foreach ($categories as $category) {
$output->writeln(
sprintf('Regenerating urls for %s (%s)',
implode('/', [
$rootCategory->getName(),
...array_map(fn($category) => $category->getName(), $category->getParentCategories())
]),
$category->getId())
);
$this->urlPersist->deleteByData(
[
UrlRewrite::ENTITY_ID => $category->getId(),
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::REDIRECT_TYPE => 0,
UrlRewrite::STORE_ID => $storeId
]
);
$newUrls = $this->categoryUrlRewriteGenerator->generate($category);
try {
$newUrls = $this->filterEmptyRequestPaths($newUrls);
$this->urlPersist->replace($newUrls);
$counter += count($newUrls);
} catch (Exception $e) {
$output->writeln(
sprintf(
'<error>Duplicated url for store ID %d, category %d (%s) - %s Generated URLs:' .
PHP_EOL . '%s</error>' . PHP_EOL,
$storeId,
$category->getId(),
$category->getName(),
$e->getMessage(),
implode(PHP_EOL, array_keys($newUrls))
)
);
}
}
$this->emulation->stopEnvironmentEmulation();
}
$output->writeln(
sprintf('Done regenerating. Regenerated %d urls', $counter)
);
return Cli::RETURN_SUCCESS;
}
/**
* Remove entries with request_path='' to prevent error 404 for "http://site.com/" address.
*
* @param UrlRewrite[] $newUrls
*
* @return UrlRewrite[]
*/
private function filterEmptyRequestPaths(array $newUrls): array
{
$result = [];
foreach ($newUrls as $key => $url) {
$requestPath = $url->getRequestPath();
if (!empty($requestPath)) {
$result[$key] = $url;
}
}
return $result;
}
}