Completed
Push — master ( cebedb...b44bca )
by Gilmar
22:17
created

ProductCommand::translateUpdate()   B

Complexity

Conditions 3
Paths 1

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 27
rs 8.8571
cc 3
eloc 19
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of gpupo/netshoes-sdk
5
 * Created by Gilmar Pupo <[email protected]>
6
 * For the information of copyright and license you should read the file
7
 * LICENSE which is distributed with this source code.
8
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
9
 * LICENSE que é distribuído com este código-fonte.
10
 * Para obtener la información de los derechos de autor y la licencia debe leer
11
 * el archivo LICENSE que se distribuye con el código fuente.
12
 * For more information, see <http://www.g1mr.com/>.
13
 */
14
15
namespace Gpupo\NetshoesSdk\Console\Command;
16
17
use Gpupo\CommonSchema\TranslatorDataCollection;
18
use Symfony\Component\Console\Input\ArrayInput;
19
use Symfony\Component\Console\Input\InputArgument;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Output\OutputInterface;
22
23
/**
24
 * @codeCoverageIgnore
25
 */
26
class ProductCommand extends AbstractCommand
27
{
28
    protected $list = ['view', 'insert', 'update', 'list', 'translateTo', 'translateUpdate'];
29
30 View Code Duplication
    public function list($app)
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...
31
    {
32
        $this->getApp()->appendCommand('product:list', 'List')
33
            ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
34
                $list = $app->processInputParameters([], $input, $output);
35
                $collection = $app->factorySdk($list)->factoryManager('product')->fetch(0, 50);
36
                foreach ($collection as $p) {
37
                    $app->displayProduct($p, $output);
38
                    $output->writeln("\n\n--------------------------------------\n\n");
39
                }
40
            });
41
    }
42
43
    public function insert($app)
44
    {
45
        $opts = [
46
            ['key' => 'file'],
47
        ];
48
49
        $this->getApp()->appendCommand('product:insert', 'Insere um produto a partir do Json de um arquivo', $opts)
50
            ->setCode(function (InputInterface $input, OutputInterface $output) use ($app, $opts) {
51
                $list = $app->processInputParameters($opts, $input, $output);
52
53
                $data = json_decode(file_get_contents($list['file']), true);
54
                $sdk = $app->factorySdk($list);
55
                $product = $sdk->createProduct($data);
56
57
                try {
58
                    $operation = $sdk->factoryManager('product')->save($product);
59
60
                    if (202 === $operation->getHttpStatusCode()) {
61
                        $output->writeln('<info>Successo!</info>');
62
                    }
63
                } catch (\Exception $e) {
64
                    $app->showException($e, $output);
65
                }
66
            });
67
    }
68
69
    public function translateTo($app)
70
    {
71
        $this->getApp()->appendCommand('product:translate:to', 'Exporta o produto no padrão comum')
72
            ->addArgument('productId', InputArgument::REQUIRED, 'Product ID')
73
            ->addArgument('filenameOutput', InputArgument::REQUIRED, 'Caminho do arquivo que será gerado')
74
            ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
75
                $list = $app->processInputParameters([], $input, $output);
76
                $id = $input->getArgument('productId');
77
                $filenameOutput = $input->getArgument('filenameOutput');
78
                $p = $app->factorySdk($list)->factoryManager('product')->translatorFindById($id);
79
80
                if (empty($p)) {
81
                    return $output->writeln('<error>Produto não encontrado!</error>');
82
                }
83
                $json = json_encode($p->toArray(), JSON_PRETTY_PRINT);
84
                file_put_contents($filenameOutput, $json);
85
86
                return $output->writeln('Arquivo <info>'.$filenameOutput.'</info> gerado.');
87
            });
88
    }
89
90
    public function translateUpdate($app)
91
    {
92
        $this->getApp()->appendCommand('product:translate:update', 'Atualiza o produto (schema)')
93
            ->addArgument('filenameInput', InputArgument::REQUIRED, 'Arquivo json com dados do produto')
94
            ->addArgument('filenamePrevious', InputArgument::OPTIONAL, 'Previous file')
95
            ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
96
                $list = $app->processInputParameters([], $input, $output);
97
                $filenameInput = $input->getArgument('filenameInput');
98
                $current = new TranslatorDataCollection(json_decode(file_get_contents($filenameInput), true));
99
                $previous = null;
100
                $filenamePrevious = $input->getArgument('filenamePrevious');
101
102
                if (!empty($filenamePrevious)) {
103
                    $previous = new TranslatorDataCollection(json_decode(file_get_contents($filenamePrevious), true));
104
                }
105
106
                $sdk = $app->factorySdk($list);
107
                $manager = $sdk->factoryManager('product');
108
109
                try {
110
                    $operation = $manager->translatorUpdate($current, $previous);
111
                    $app->displayTableResults($output, [$operation]);
112
                } catch (\Exception $e) {
113
                    $app->showException($e, $output);
114
                }
115
            });
116
    }
117
118
    public function view($app)
119
    {
120
        $this->getApp()->appendCommand('product:view', 'Consulta a situação de um produto')
121
            ->addArgument('productId', InputArgument::REQUIRED, 'Product ID')
122
            ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
123
                $list = $app->processInputParameters([], $input, $output);
124
                $id = $input->getArgument('productId');
125
                $p = $app->factorySdk($list)->factoryManager('product')->findById($id);
126
127
                if (empty($p)) {
128
                    return $output->writeln('<error>Produto não encontrado!</error>');
129
                }
130
131
                $app->displayProduct($p, $output);
132
133
                $output->writeln('<fg=yellow>Detalhes</>');
134
                $command = $app->find('product:sku:details');
135
                $t = new ArrayInput([
136
                    'command' => 'product:sku:details',
137
                    'skuId'   => $id,
138
139
                ]);
140
                $command->run($t, $output);
141
            });
142
    }
143
144
    public function update($app)
145
    {
146
        $opts = [
147
            ['key' => 'file-previous'],
148
            ['key' => 'file-current'],
149
        ];
150
151
        $this->getApp()->appendCommand('product:update', 'Atualiza um SKU', $opts)
152
            ->setCode(function (InputInterface $input, OutputInterface $output) use ($app, $opts) {
153
                $list = $app->processInputParameters($opts, $input, $output);
154
155
                $data = [];
156
157
                foreach (['previous', 'current'] as $i) {
158
                    if (!file_exists($list['file-'.$i])) {
159
                        throw new \InvalidArgumentException('O arquivo ['.$list['file-'.$i].'] não existe!');
160
                    }
161
162
                    $data[$i] = json_decode(file_get_contents($list['file-'.$i]), true);
163
                }
164
165
                $sdk = $app->factorySdk($list);
166
                $current = $sdk->createProduct($data['current']);
167
                $previous = $sdk->createProduct($data['previous']);
168
                $manager = $sdk->factoryManager('product');
169
170
                try {
171
                    $operation = $manager->update($current, $previous);
172
                    $app->displayTableResults($output, [$operation]);
173
                } catch (\Exception $e) {
174
                    $app->showException($e, $output);
175
                }
176
            });
177
    }
178
}
179