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.
Completed
Branch master (d24cbd)
by Daniel
09:54 queued 03:30
created

Products::prepareCollections()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 21
rs 9.0534
c 1
b 0
f 1
cc 4
eloc 14
nc 6
nop 2
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
    /**
59
     * {@inheritdoc}
60
     */
61
    protected function configure()
62
    {
63
        $options = [
64
            new InputOption(
65
                self::INPUT_PRODUCT,
66
                'p',
67
                InputOption::VALUE_OPTIONAL,
68
                'Reindex a specific product'
69
            ),
70
            new InputOption(
71
                self::INPUT_STORE,
72
                's',
73
                InputOption::VALUE_OPTIONAL,
74
                'Reindex a specific store',
75
                \Magento\Store\Model\Store::DEFAULT_STORE_ID
76
            )
77
        ];
78
        $this->setName('urlrewrite:rebuild:products');
79
        $this->setDescription('Rebuild Product URL Rewrites');
80
        $this->setDefinition($options);
81
        parent::configure();
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    protected function execute(InputInterface $input, OutputInterface $output)
88
    {
89
        parent::execute($input, $output);
90
91
        try {
92
93
            $productIds = $input->getOption(self::INPUT_PRODUCT);
94
            $storeId = $input->getOption(self::INPUT_STORE);
95
            $this->prepareCollections($storeId, $productIds);
96
97
            if ($size = $this->getSizeToProcess()) {
98
                $this->progressBar->start($size);
99
                $this->rebuildUrls();
100
            }
101
102
            $this->progressBar->finish();
103
            $this->output->write('', true);
104
        } catch (\Exception $e) {
105
            $this->output->writeln($e->getMessage());
106
            return \Magento\Framework\Console\Cli::RETURN_FAILURE;
107
        }
108
        return \Magento\Framework\Console\Cli::RETURN_SUCCESS;
109
    }
110
111
    /**
112
     * Generate product url by product
113
     * @param $args
114
     */
115
    public function callbackGenerateProductUrl($args)
116
    {
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
            $this->output->writeln($e->getMessage() . '- Product ID -' . $productId);
0 ignored issues
show
Bug introduced by
The variable $productId does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
141
            return;
142
        }
143
    }
144
145
    /**
146
     *  Remove Product urls
147
     *
148
     * @param $productId
149
     * @param null $storeId
150
     * @return bool
151
     */
152
    protected function removeProductUrls($productId, $storeId = null)
153
    {
154
        if (!is_numeric($productId)) {
155
            return false;
156
        }
157
        $data = [
158
            UrlRewrite::ENTITY_ID => $productId,
159
            UrlRewrite::ENTITY_TYPE => \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::ENTITY_TYPE,
160
            UrlRewrite::IS_AUTOGENERATED => 1,
161
            UrlRewrite::REDIRECT_TYPE => 0,
162
            UrlRewrite::STORE_ID => $storeId
163
        ];
164
165
        try {
166
            $this->getUrlPersist()->deleteByData($data);
167
        } catch (\Exception $e) {
168
            $this->output->writeln($e->getMessage());
169
            return false;
170
        }
171
        return true;
172
    }
173
174
    /**
175
     *  Generate list of product urls
176
     *
177
     * @param $product
178
     * @return array
179
     */
180
    private function prepareUrls($product)
181
    {
182
        return $this->getProductUrlRewriteGenerator()->generate($product);
183
    }
184
185
    /**
186
     *  Get Product Url Generator
187
     *
188
     * @return \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator
189
     */
190
    protected function getProductUrlRewriteGenerator()
191
    {
192
        return $this->getObjectManager()->create('\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator');
193
    }
194
195
196
197
    /**
198
     * Prepare Collections to process
199
     *
200
     * @param $storeId
201
     * @param $productIds
202
     * @throws \Exception
203
     */
204
    protected function prepareCollections($storeId, $productIds)
205
    {
206
        if (\Magento\Store\Model\Store::DEFAULT_STORE_ID == $storeId) {
207
            $stores = $this->getStoreManager()->getStores();
208
        } else {
209
            $stores = [$this->getStoreManager()->getStore($storeId)];
210
        }
211
        if (empty($stores)) {
212
            throw new \Exception('Invalid store');
213
        }
214
215
        foreach ($stores as $store) {
216
            $this->_collection = null;
217
            $storeId = $store->getId();
218
            $this->getProductCollection();
219
            $this->addFilterProductIds($productIds);
220
            $this->addStoreFilter($storeId);
221
222
            $this->addCollections($this->_collection, $storeId);
223
        }
224
    }
225
226
    /**
227
     * Get product collection
228
     *
229
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
230
     */
231
    protected function getProductCollection()
232
    {
233
        if (is_null($this->_collection)) {
234
            /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
235
            $this->_collection = $this->getObjectManager()->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
236
        }
237
        return $this->_collection;
238
    }
239
240
    /**
241
     * Filter collection by product ID
242
     *
243
     * @param null $productIds
244
     */
245
    private function addFilterProductIds($productIds = null)
246
    {
247
        if (is_null($productIds) || is_null($this->_collection)) {
248
            return;
249
        }
250
        $this->_collection->addIdFilter(explode(',', $productIds));
251
    }
252
253
    /**
254
     * Filter Collection by Store
255
     *
256
     * @param null $storeId
257
     */
258
    private function addStoreFilter($storeId = null)
259
    {
260
        if (is_null($storeId) || is_null($this->_collection)) {
261
            return;
262
        }
263
        $this->_collection
264
            ->addStoreFilter($storeId)
265
            ->setStoreId($storeId);;
266
    }
267
268
    /**
269
     * Add collection to process
270
     *
271
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
272
     * @param $storeId
273
     */
274
    protected function addCollections(\Magento\Catalog\Model\ResourceModel\Product\Collection $collection, $storeId)
275
    {
276
        $this->_collections[$storeId] = $collection;
277
    }
278
279
    /**
280
     * Number of Items to process
281
     *
282
     * @return int
283
     */
284
    protected function getSizeToProcess()
285
    {
286
        $size = 0;
287
        foreach ($this->_collections as $collection) {
288
            $size += $collection->getSize();
289
        }
290
        return $size;
291
    }
292
293
    /**
294
     * Rebuild Urls
295
     */
296
    protected function rebuildUrls()
297
    {
298
        foreach ($this->_collections as $storeId => $collection) {
299
            $this->getIterator()->walk(
300
                $collection->getSelect(),
301
                [[$this, 'callbackGenerateProductUrl']],
302
                [
303
                    'product' => $this->getProductFactory(),
304
                    'storeId' => $storeId
305
                ]
306
            );
307
        }
308
309
    }
310
311
    /**
312
     * Create product factory
313
     *
314
     * @return \Magento\Catalog\Model\ProductFactory
315
     */
316
    protected function getProductFactory()
317
    {
318
        return $this->getObjectManager()->create('\Magento\Catalog\Model\ProductFactory')->create();
319
    }
320
}