GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Products   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 293
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 6
Bugs 1 Features 5
Metric Value
wmc 32
lcom 1
cbo 1
dl 0
loc 293
rs 9.6
c 6
b 1
f 5

14 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 22 1
A execute() 0 23 3
B callbackGenerateProductUrl() 0 33 5
A removeProductUrls() 0 21 3
A prepareUrls() 0 4 1
A getProductUrlRewriteGenerator() 0 4 1
A prepareCollections() 0 21 4
A getProductCollection() 0 8 2
A addFilterProductIds() 0 7 3
A addStoreFilter() 0 9 3
A addCollections() 0 4 1
A getSizeToProcess() 0 8 2
A rebuildUrls() 0 14 2
A getProductFactory() 0 4 1
1
<?php
2
/**
3
 * Rebuild Url Rewrite for magento 2
4
 * Copyright (C) 2017
5
 *
6
 * This file is part of DanielSousa/UrlRewrite.
7
 *
8
 * DanielSousa/UrlRewrite is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20
 */
21
22
namespace DanielSousa\UrlRewrite\Console\Command;
23
24
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
25
use Symfony\Component\Console\Input\InputInterface;
26
use Symfony\Component\Console\Input\InputOption;
27
use Symfony\Component\Console\Output\OutputInterface;
28
29
class Products extends AbstractUrlRewriteCommand
30
{
31
32
    /**
33
     * Name of product input option
34
     */
35
    const INPUT_PRODUCT = 'product';
36
37
    /**
38
     * Force of force input option
39
     */
40
    const INPUT_FORCE = 'force';
41
42
    /**
43
     * Name of product input option
44
     */
45
    const INPUT_STORE = 'store';
46
47
    /**
48
     * @var \Magento\Catalog\Model\ResourceModel\Product\Collection
49
     */
50
    protected $_collection = null;
51
52
    /**
53
     * Collections to process
54
     */
55
    protected $_collections = [];
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    protected function configure()
61
    {
62
        $options = [
63
            new InputOption(
64
                self::INPUT_PRODUCT,
65
                'p',
66
                InputOption::VALUE_OPTIONAL,
67
                'Reindex a specific product'
68
            ),
69
            new InputOption(
70
                self::INPUT_STORE,
71
                's',
72
                InputOption::VALUE_OPTIONAL,
73
                'Reindex a specific store',
74
                \Magento\Store\Model\Store::DEFAULT_STORE_ID
75
            )
76
        ];
77
        $this->setName('urlrewrite:rebuild:products');
78
        $this->setDescription('Rebuild Product URL Rewrites');
79
        $this->setDefinition($options);
80
        parent::configure();
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    protected function execute(InputInterface $input, OutputInterface $output)
87
    {
88
        parent::execute($input, $output);
89
90
        try {
91
92
            $productIds = $input->getOption(self::INPUT_PRODUCT);
93
            $storeId = $input->getOption(self::INPUT_STORE);
94
            $this->prepareCollections($storeId, $productIds);
95
96
            if ($size = $this->getSizeToProcess()) {
97
                $this->progressBar->start($size);
98
                $this->rebuildUrls();
99
            }
100
101
            $this->progressBar->finish();
102
            $this->output->write('', true);
103
        } catch (\Exception $e) {
104
            $this->output->writeln($e->getMessage());
105
            return \Magento\Framework\Console\Cli::RETURN_FAILURE;
106
        }
107
        return \Magento\Framework\Console\Cli::RETURN_SUCCESS;
108
    }
109
110
    /**
111
     * Generate product url by product
112
     * @param $args
113
     */
114
    public function callbackGenerateProductUrl($args)
115
    {
116
        $productId = null;
117
        try {
118
            if (!isset($args['row']['entity_id'])) {
119
                $this->output->writeln('Id not found');
120
                return;
121
            }
122
            $productId = $args['row']['entity_id'];
123
            $this->progressBar->setMessage($productId);
124
            $this->progressBar->advance();
125
126
127
            $product = clone $args['product'];
128
            $product->load($productId);
129
130
            $storeId = $args['storeId'];
131
            if (is_null($storeId)) {
132
                $storeId = \Magento\Store\Model\Store::DEFAULT_STORE_ID;
133
            }
134
            $product->setStoreId($storeId);
135
            $this->removeProductUrls($productId, $storeId);
136
            $this->replaceUrls(
137
                $this->prepareUrls($product)
138
            );
139
        } catch (\Exception $e) {
140
            if (!is_null($productId)) {
141
                $this->output->writeln('ERROR ON PRODUCT ID -' . $productId);
142
            }
143
            $this->output->writeln($e->getMessage());
144
            return;
145
        }
146
    }
147
148
    /**
149
     *  Remove Product urls
150
     *
151
     * @param $productId
152
     * @param null $storeId
153
     * @return bool
154
     */
155
    protected function removeProductUrls($productId, $storeId = null)
156
    {
157
        if (!is_numeric($productId)) {
158
            return false;
159
        }
160
        $data = [
161
            UrlRewrite::ENTITY_ID => $productId,
162
            UrlRewrite::ENTITY_TYPE => \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::ENTITY_TYPE,
163
            UrlRewrite::IS_AUTOGENERATED => 1,
164
            UrlRewrite::REDIRECT_TYPE => 0,
165
            UrlRewrite::STORE_ID => $storeId
166
        ];
167
168
        try {
169
            $this->getUrlPersist()->deleteByData($data);
170
        } catch (\Exception $e) {
171
            $this->output->writeln($e->getMessage());
172
            return false;
173
        }
174
        return true;
175
    }
176
177
    /**
178
     *  Generate list of product urls
179
     *
180
     * @param $product
181
     * @return array
182
     */
183
    private function prepareUrls($product)
184
    {
185
        return $this->getProductUrlRewriteGenerator()->generate($product);
186
    }
187
188
    /**
189
     *  Get Product Url Generator
190
     *
191
     * @return \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator
192
     */
193
    protected function getProductUrlRewriteGenerator()
194
    {
195
        return $this->getObjectManager()->create('\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator');
196
    }
197
198
    /**
199
     * Prepare Collections to process
200
     *
201
     * @param $storeId
202
     * @param $productIds
203
     * @throws \Exception
204
     */
205
    protected function prepareCollections($storeId, $productIds)
206
    {
207
        if (\Magento\Store\Model\Store::DEFAULT_STORE_ID == $storeId) {
208
            $stores = $this->getStoreManager()->getStores();
209
        } else {
210
            $stores = [$this->getStoreManager()->getStore($storeId)];
211
        }
212
        if (empty($stores)) {
213
            throw new \Exception('Invalid store');
214
        }
215
216
        foreach ($stores as $store) {
217
            $this->_collection = null;
218
            $storeId = $store->getId();
219
            $this->getProductCollection();
220
            $this->addFilterProductIds($productIds);
221
            $this->addStoreFilter($storeId);
222
223
            $this->addCollections($this->_collection, $storeId);
224
        }
225
    }
226
227
    /**
228
     * Get product collection
229
     *
230
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
231
     */
232
    protected function getProductCollection()
233
    {
234
        if (is_null($this->_collection)) {
235
            /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
236
            $this->_collection = $this->getObjectManager()->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
237
        }
238
        return $this->_collection;
239
    }
240
241
    /**
242
     * Filter collection by product ID
243
     *
244
     * @param null $productIds
245
     */
246
    private function addFilterProductIds($productIds = null)
247
    {
248
        if (is_null($productIds) || is_null($this->_collection)) {
249
            return;
250
        }
251
        $this->_collection->addIdFilter(explode(',', $productIds));
252
    }
253
254
    /**
255
     * Filter Collection by Store
256
     *
257
     * @param null $storeId
258
     */
259
    private function addStoreFilter($storeId = null)
260
    {
261
        if (is_null($storeId) || is_null($this->_collection)) {
262
            return;
263
        }
264
        $this->_collection
265
            ->addStoreFilter($storeId)
266
            ->setStoreId($storeId); ;
267
    }
268
269
    /**
270
     * Add collection to process
271
     *
272
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
273
     * @param $storeId
274
     */
275
    protected function addCollections(\Magento\Catalog\Model\ResourceModel\Product\Collection $collection, $storeId)
276
    {
277
        $this->_collections[$storeId] = $collection;
278
    }
279
280
    /**
281
     * Number of Items to process
282
     *
283
     * @return int
284
     */
285
    protected function getSizeToProcess()
286
    {
287
        $size = 0;
288
        foreach ($this->_collections as $collection) {
289
            $size += $collection->getSize();
290
        }
291
        return $size;
292
    }
293
294
    /**
295
     * Rebuild Urls
296
     */
297
    protected function rebuildUrls()
298
    {
299
        foreach ($this->_collections as $storeId => $collection) {
300
            $this->getIterator()->walk(
301
                $collection->getSelect(),
302
                [[$this, 'callbackGenerateProductUrl']],
303
                [
304
                    'product' => $this->getProductFactory(),
305
                    'storeId' => $storeId
306
                ]
307
            );
308
        }
309
310
    }
311
312
    /**
313
     * Create product factory
314
     *
315
     * @return \Magento\Catalog\Model\ProductFactory
316
     */
317
    protected function getProductFactory()
318
    {
319
        return $this->getObjectManager()->create('\Magento\Catalog\Model\ProductFactory')->create();
320
    }
321
}