Completed
Push — master ( 6dce2e...680b14 )
by Lucas
09:07
created

ImportCommand   C

Complexity

Total Complexity 17

Size/Duplication

Total Lines 289
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 20

Test Coverage

Coverage 80.34%

Importance

Changes 20
Bugs 1 Features 2
Metric Value
wmc 17
c 20
b 1
f 2
lcom 1
cbo 20
dl 0
loc 289
ccs 94
cts 117
cp 0.8034
rs 6.4705

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
B configure() 0 36 1
A doImport() 0 12 2
B importPaths() 0 38 4
B importResource() 0 78 5
A parseContent() 0 21 4
1
<?php
2
/**
3
 * import json data into graviton
4
 *
5
 * Supports importing json data from either a single file or a complete folder of files.
6
 *
7
 * The data needs to contain frontmatter to hint where the bits and pieces should go.
8
 */
9
10
namespace Graviton\ImportExport\Command;
11
12
use Graviton\ImportExport\Exception\MissingTargetException;
13
use Graviton\ImportExport\Exception\JsonParseException;
14
use Graviton\ImportExport\Exception\UnknownFileTypeException;
15
use Symfony\Component\Console\Input\InputArgument;
16
use Symfony\Component\Console\Input\InputOption;
17
use Symfony\Component\Console\Input\InputInterface;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Finder\Finder;
20
use Symfony\Component\Yaml\Parser;
21
use Symfony\Component\VarDumper\Cloner\VarCloner;
22
use Symfony\Component\VarDumper\Dumper\CliDumper as Dumper;
23
use GuzzleHttp\Client;
24
use GuzzleHttp\Promise;
25
use GuzzleHttp\Exception\RequestException;
26
use GuzzleHttp\Exception\BadResponseException;
27
use Webuni\FrontMatter\FrontMatter;
28
use Webuni\FrontMatter\Document;
29
use Psr\Http\Message\ResponseInterface;
30
31
/**
32
 * @author   List of contributors <https://github.com/libgraviton/import-export/graphs/contributors>
33
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
34
 * @link     http://swisscom.ch
35
 */
36
class ImportCommand extends ImportCommandAbstract
37
{
38
    /**
39
     * @var Client
40
     */
41
    private $client;
42
43
    /**
44
     * @var FrontMatter
45
     */
46
    private $frontMatter;
47
48
    /**
49
     * @var Parser
50
     */
51
    private $parser;
52
53
    /**
54
     * @var VarCloner
55
     */
56
    private $cloner;
57
58
    /**
59
     * @var Dumper
60
     */
61
    private $dumper;
62
63
    /**
64
     * @param Client      $client      guzzle http client
65
     * @param Finder      $finder      symfony/finder instance
66
     * @param FrontMatter $frontMatter frontmatter parser
67
     * @param Parser      $parser      yaml/json parser
68
     * @param VarCloner   $cloner      var cloner for dumping reponses
69
     * @param Dumper      $dumper      dumper for outputing responses
70
     */
71 4
    public function __construct(
72
        Client $client,
73
        Finder $finder,
74
        FrontMatter $frontMatter,
75
        Parser $parser,
76
        VarCloner $cloner,
77
        Dumper $dumper
78
    ) {
79 4
        parent::__construct(
80
            $finder
81 4
        );
82 4
        $this->client = $client;
83 4
        $this->frontMatter = $frontMatter;
84 4
        $this->parser = $parser;
85 4
        $this->cloner = $cloner;
86 4
        $this->dumper = $dumper;
87 4
    }
88
89
    /**
90
     * Configures the current command.
91
     *
92
     * @return void
93
     */
94 4
    protected function configure()
95
    {
96 4
        $this
97 4
            ->setName('graviton:import')
98 4
            ->setDescription('Import files from a folder or file.')
99 4
            ->addOption(
100 4
                'rewrite-host',
101 4
                'r',
102 4
                InputOption::VALUE_OPTIONAL,
103 4
                'Replace the value of this option with the <host> value before importing.',
104
                'http://localhost'
105 4
            )
106 4
            ->addOption(
107 4
                'rewrite-to',
108 4
                't',
109 4
                InputOption::VALUE_OPTIONAL,
110
                'String to use as the replacement value for the [REWRITE-HOST] string.',
111 4
                '<host>'
112 4
            )
113 4
            ->addOption(
114 4
                'sync-requests',
115
                's',
116 4
                InputOption::VALUE_NONE,
117 4
                'Send requests synchronously'
118 4
            )
119 4
            ->addArgument(
120
                'host',
121 4
                InputArgument::REQUIRED,
122 4
                'Protocol and host to load data into (ie. https://graviton.nova.scapp.io)'
123
            )
124
            ->addArgument(
125
                'file',
126
                InputArgument::REQUIRED + InputArgument::IS_ARRAY,
127
                'Directories or files to load'
128
            );
129
    }
130
131
    /**
132
     * Executes the current command.
133 4
     *
134
     * @param Finder          $finder Finder
135 4
     * @param InputInterface  $input  User input on console
136 4
     * @param OutputInterface $output Output of the command
137 4
     *
138
     * @return void
139 4
     */
140 3
    protected function doImport(Finder $finder, InputInterface $input, OutputInterface $output)
141
    {
142
        $host = $input->getArgument('host');
143
        $rewriteHost = $input->getOption('rewrite-host');
144
        $rewriteTo = $input->getOption('rewrite-to');
145
        if ($rewriteTo === $this->getDefinition()->getOption('rewrite-to')->getDefault()) {
146
            $rewriteTo = $host;
147
        }
148
        $sync = $input->getOption('sync-requests');
149
150
        $this->importPaths($finder, $output, $host, $rewriteHost, $rewriteTo, $sync);
151
    }
152
153 4
    /**
154
     * @param Finder          $finder      finder primmed with files to import
155 4
     * @param OutputInterface $output      output interfac
156 4
     * @param string          $host        host to import into
157 4
     * @param string          $rewriteHost string to replace with value from $rewriteTo during loading
158
     * @param string          $rewriteTo   string to replace value from $rewriteHost with during loading
159 4
     * @param boolean         $sync        send requests syncronously
160
     *
161 4
     * @return void
162 1
     *
163
     * @throws MissingTargetException
164
     */
165 3
    protected function importPaths(
166
        Finder $finder,
167 3
        OutputInterface $output,
168 3
        $host,
169
        $rewriteHost,
170
        $rewriteTo,
171
        $sync = false
172
    ) {
173
        $promises = [];
174
        foreach ($finder as $file) {
175
            $doc = $this->frontMatter->parse($file->getContents());
176
177
            $output->writeln("<info>Loading data from ${file}</info>");
178
179
            if (!array_key_exists('target', $doc->getData())) {
180
                throw new MissingTargetException('Missing target in \'' . $file . '\'');
181
            }
182
183
            $targetUrl = sprintf('%s%s', $host, $doc->getData()['target']);
184
185
            $promises[] = $this->importResource(
186
                $targetUrl,
187
                (string) $file,
188
                $output,
189
                $doc,
190
                $host,
191
                $rewriteHost,
192
                $rewriteTo,
193
                $sync
194
            );
195
        }
196
197 3
        try {
198
            Promise\unwrap($promises);
199
        } catch (\GuzzleHttp\Exception\ClientException $e) {
200 2
            // silently ignored since we already output an error when the promise fails
201 2
        }
202 2
    }
203 3
204
    /**
205
     * @param string          $targetUrl   target url to import resource into
206 1
     * @param string          $file        path to file being loaded
207 1
     * @param OutputInterface $output      output of the command
208 1
     * @param Document        $doc         document to load
209 1
     * @param string          $host        host to import into
210 1
     * @param string          $rewriteHost string to replace with value from $host during loading
211 1
     * @param string          $rewriteTo   string to replace value from $rewriteHost with during loading
212 1
     * @param boolean         $sync        send requests syncronously
213 1
     *
214 1
     * @return Promise\Promise|null
215
     */
216 1
    protected function importResource(
217 1
        $targetUrl,
218 1
        $file,
219 1
        OutputInterface $output,
220 1
        Document $doc,
221 1
        $host,
0 ignored issues
show
Unused Code introduced by
The parameter $host is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
222 1
        $rewriteHost,
223
        $rewriteTo,
224 1
        $sync = false
225 1
    ) {
226 1
        $content = str_replace($rewriteHost, $rewriteTo, $doc->getContent());
227 1
228 1
        $successFunc = function (ResponseInterface $response) use ($output) {
229 1
            $output->writeln(
230 1
                '<comment>Wrote ' . $response->getHeader('Link')[0] . '</comment>'
231 1
            );
232 3
        };
233
234 3
        $errFunc = function (RequestException $e) use ($output, $file) {
235 3
            $output->writeln(
236 3
                '<error>' . str_pad(
237 3
                    sprintf(
238
                        'Failed to write <%s> from \'%s\' with message \'%s\'',
239 3
                        $e->getRequest()->getUri(),
240 3
                        $file,
241 3
                        $e->getMessage()
242 3
                    ),
243 3
                    140,
244
                    ' '
245
                ) . '</error>'
246
            );
247
            if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
248
                $this->dumper->dump(
249
                    $this->cloner->cloneVar(
250
                        $this->parser->parse($e->getResponse()->getBody(), false, false, true)
251
                    ),
252
                    function ($line, $depth) use ($output) {
253
                        if ($depth > 0) {
254
                            $output->writeln(
255
                                '<error>' . str_pad(str_repeat('  ', $depth) . $line, 140, ' ') . '</error>'
256
                            );
257
                        }
258
                    }
259
                );
260
            }
261
        };
262
263 3
        if ($sync === false) {
264
            $promise = $this->client->requestAsync(
265
                'PUT',
266
                $targetUrl,
267
                [
268
                    'json' => $this->parseContent($content, $file)
269
                ]
270
            );
271
            $promise->then($successFunc, $errFunc);
272
        } else {
273
            $promise = new Promise\Promise;
274
            try {
275
                $promise->resolve(
276 3
                    $successFunc(
277 3
                        $this->client->request(
278 3
                            'PUT',
279
                            $targetUrl,
280
                            [
281
                                'json' => $this->parseContent($content, $file),
282
                            ]
283
                        )
284
                    )
285
                );
286
            } catch (BadResponseException $e) {
287 3
                $promise->resolve(
288
                    $errFunc($e)
289
                );
290
            }
291
        }
292
        return $promise;
293 3
    }
294
295
    /**
296
     * parse contents of a file depending on type
297
     *
298
     * @param string $content contents part of file
299
     * @param string $file    full path to file
300
     *
301
     * @return mixed
302
     */
303
    protected function parseContent($content, $file)
304
    {
305
        if (substr($file, -5) == '.json') {
306
            $data = json_decode($content);
307
            if (json_last_error() !== JSON_ERROR_NONE) {
308
                throw new JsonParseException(
309
                    sprintf(
310
                        '%s in %s',
311
                        json_last_error_msg(),
312
                        $file
313
                    )
314
                );
315
            }
316
        } elseif (substr($file, -4) == '.yml') {
317
            $data = $this->parser->parse($content);
318
        } else {
319
            throw new UnknownFileTypeException($file);
320
        }
321
322
        return $data;
323
    }
324
}
325