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
Push — master ( d3ddc5...97aa73 )
by Daniel
01:53
created

Products::callbackGenerateProductUrl()   B

Complexity

Conditions 3
Paths 6

Size

Total Lines 24
Code Lines 16

Duplication

Lines 24
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 24
loc 24
rs 8.9713
cc 3
eloc 16
nc 6
nop 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
     * @var \Magento\Catalog\Model\ResourceModel\Product\Collection
44
     */
45
    protected $collection = null;
46
47
    /**
48
     * Generate product url by product
49
     * @param $args
50
     */
51 View Code Duplication
    public function callbackGenerateProductUrl($args)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
52
    {
53
        try {
54
            if (!isset($args['row']['entity_id'])) {
55
                $this->output->writeln('Id not found');
56
                return;
57
            }
58
            $productId = $args['row']['entity_id'];
59
            $this->progressBar->setMessage($productId);
60
            $this->progressBar->advance();
61
62
63
            $product = clone $args['product'];
64
            $product->load($productId);
65
            $product->setStoreId(null);
66
            $this->removeProductUrls($productId);
67
            $this->replaceUrls(
68
                $this->prepareUrls($product)
69
            );
70
        } catch (\Exception $e) {
71
            $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...
72
            return;
73
        }
74
    }
75
76
    /**
77
     *  Remove Product urls
78
     *
79
     * @param $productId
80
     * @param null $storeId
81
     * @return bool
82
     */
83 View Code Duplication
    protected function removeProductUrls($productId, $storeId = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
    {
85
        if (!is_numeric($productId)) {
86
            return false;
87
        }
88
        $data = [
89
            UrlRewrite::ENTITY_ID => $productId,
90
            UrlRewrite::ENTITY_TYPE => \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::ENTITY_TYPE,
91
            UrlRewrite::REDIRECT_TYPE => 0,
92
        ];
93
94
        if (!is_null($storeId)) {
95
            $data[] = [UrlRewrite::STORE_ID => $storeId];
96
        }
97
        try {
98
            $this->getUrlPersist()->deleteByData($data);
99
        } catch (\Exception $e) {
100
            $this->output->writeln($e->getMessage());
101
            return false;
102
        }
103
        return true;
104
    }
105
106
    /**
107
     *  Generate list of product urls
108
     *
109
     * @param $product
110
     * @return array
111
     */
112
    private function prepareUrls($product)
113
    {
114
        return $this->getProductUrlRewriteGenerator()->generate($product);
115
    }
116
117
    /**
118
     *  Get Product Url Generator
119
     *
120
     * @return \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator
121
     */
122
    protected function getProductUrlRewriteGenerator()
123
    {
124
        return $this->getObjectManager()->create('\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator');
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130
    protected function configure()
131
    {
132
        $options = [
133
            new InputOption(
134
                self::INPUT_PRODUCT,
135
                'p',
136
                InputOption::VALUE_OPTIONAL,
137
                'Reindex a specific product'
138
            )
139
        ];
140
        $this->setName('urlrewrite:rebuild:products');
141
        $this->setDescription('Rebuild Product URL Rewrites');
142
        $this->setDefinition($options);
143
        parent::configure();
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149
    protected function execute(InputInterface $input, OutputInterface $output)
150
    {
151
        parent::execute($input, $output);
152
153
        try {
154
155
            $productIds = $input->getOption(self::INPUT_PRODUCT);
156
            $this->getProductCollection();
157
            $this->addFilterProductIds($productIds);
158
            $size = $this->collection->getSize();
159
            if (!$size) {
160
                $this->output->write('', true);
161
                $this->output->write('Nothing to process', true);
162
                return \Magento\Framework\Console\Cli::RETURN_SUCCESS;
163
            }
164
165
            $this->progressBar->start($size);
166
167
            $this->getIterator()->walk(
168
                $this->collection->getSelect(),
169
                [[$this, 'callbackGenerateProductUrl']],
170
                [
171
                    'product' => $this->getProductFactory()
172
                ]
173
            );
174
            $this->progressBar->finish();
175
            $this->output->write('', true);
176
        } catch (\Exception $e) {
177
            $this->output->writeln($e->getMessage());
178
            return \Magento\Framework\Console\Cli::RETURN_FAILURE;
179
        }
180
        return \Magento\Framework\Console\Cli::RETURN_SUCCESS;
181
    }
182
183
    /**
184
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
185
     */
186
    protected function getProductCollection()
187
    {
188
        if (is_null($this->collection)) {
189
            /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
190
            $this->collection = $this->getObjectManager()->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
191
        }
192
        return $this->collection;
193
    }
194
195
    private function addFilterProductIds($productIds = null)
196
    {
197
        if (is_null($productIds) || is_null($this->collection)) {
198
            return;
199
        }
200
        $this->collection->addIdFilter(explode(',', $productIds));
201
    }
202
203
    /**
204
     * Create product factory
205
     *
206
     * @return \Magento\Catalog\Model\ProductFactory
207
     */
208
    protected function getProductFactory()
209
    {
210
        return $this->getObjectManager()->create('\Magento\Catalog\Model\ProductFactory')->create();
211
    }
212
}