AbstractPrestashopProductsImportCommand::handle()   B
last analyzed

Complexity

Conditions 9
Paths 92

Size

Total Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 7.5135
c 0
b 0
f 0
cc 9
nc 92
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace DansMaCulotte\PrestashopWebService\Commands;
4
5
use DansMaCulotte\PrestashopWebService\Exceptions\PrestashopWebServiceException;
6
use DansMaCulotte\PrestashopWebService\PrestashopWebService;
7
use Illuminate\Console\Command;
8
use Illuminate\Support\Collection;
9
10
abstract class AbstractPrestashopProductsImportCommand extends Command
11
{
12
    const PRESTASHOP_RESOURCE_NAME = 'products';
13
14
    /**
15
     * The name and signature of the console command.
16
     *
17
     * @var string
18
     */
19
    protected $signature = 'prestashop:import-products {--id=* : The Prestashop ID of the product}';
20
21
    /**
22
     * The console command description.
23
     *
24
     * @var string
25
     */
26
    protected $description = 'Import or sync products with Prestashop products database';
27
28
    /**
29
     * The prestashop singleton from the service provider
30
     * @var PrestashopWebService
31
     */
32
    protected $prestashop;
33
34
    /**
35
     * Create a new command instance.
36
     *
37
     * @param PrestashopWebService $prestashop
38
     */
39
    public function __construct(PrestashopWebService $prestashop)
40
    {
41
        parent::__construct();
42
43
        $this->prestashop = $prestashop;
44
    }
45
46
    /**
47
     * Execute the console command.
48
     *
49
     * @return mixed
50
     */
51
    public function handle()
52
    {
53
        $ids = $this->option('id');
54
        $debug = $this->getOutput()->isDebug();
55
56
        $this->info('Importing products');
57
58
        $products = count($ids) ? $ids : $this->getProducts();
59
        $bar = $this->output->createProgressBar(count($products));
60
61
        $skippedProducts = new Collection();
62
63
        foreach ($products as $productId) {
0 ignored issues
show
Bug introduced by
The expression $products of type array|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
64
            try {
65
                $rawProduct = $this->getProduct($productId);
66
                $product = $this->importProduct($rawProduct);
67
68
                if (!$product) {
69
                    $skippedProducts->add(new Collection([
70
                        'id' => (string) $rawProduct->id,
71
                        'reference' => (string) $rawProduct->reference,
72
                    ]));
73
74
                    if ($debug) {
75
                        $this->info("\nPrestashop: Skipped product [{$rawProduct->id}] $rawProduct->reference");
76
                    }
77
                } else {
78
                    if ($debug) {
79
                        $this->info("\nPrestashop: Imported product [{$rawProduct->id}] {$rawProduct->reference}");
80
                    }
81
                }
82
83
                $bar->advance();
84
            } catch (\Exception $e) {
85
                if ($debug) {
86
                    $this->info($e->getMessage());
87
                }
88
                $this->error("\nPrestashop: Failed to request product " . (string) $productId);
89
            }
90
        }
91
92
        $bar->finish();
93
94
        $skippedProductsCount = count($skippedProducts);
95
        if ($skippedProductsCount) {
96
            $this->info("\nPrestashop: Skipped {$skippedProductsCount} products");
97
            $this->table(['id', 'reference'], $skippedProducts->toArray());
98
        }
99
100
        return true;
101
    }
102
103
    /**
104
     * @return array
105
     */
106 View Code Duplication
    public function getProducts()
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...
107
    {
108
        try {
109
            $xml = $this->prestashop->get([
110
                'resource' => self::PRESTASHOP_RESOURCE_NAME,
111
            ]);
112
        } catch (PrestashopWebServiceException $e) {
113
            $this->error('Prestashop: Failed to request products');
114
            return [];
115
        }
116
117
        $ids = [];
118
119
        foreach ($xml->products->children() as $product) {
120
            foreach ($product->attributes() as $key => $value) {
121
                if ($key === 'id') {
122
                    array_push($ids, (string)$value);
123
                }
124
            }
125
        }
126
127
        return $ids;
128
    }
129
130
    /**
131
     * @param string $id
132
     * @return \SimpleXMLElement
133
     * @throws \DansMaCulotte\PrestashopWebService\Exceptions\PrestashopWebServiceException
134
     */
135
    public function getProduct(string $id)
136
    {
137
        $xml = $this->prestashop->get([
138
            'resource' => self::PRESTASHOP_RESOURCE_NAME,
139
            'id' => $id,
140
        ]);
141
142
        return $xml->product;
143
    }
144
145
    /**
146
     * @param \SimpleXMLElement $product
147
     */
148
    abstract public function importProduct(\SimpleXMLElement $product);
149
}
150