Failed Conditions
Push — master ( 6560de...8483ce )
by Florent
05:17
created

ObjectOutputCommand::prepareJsonOutput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\Console;
15
16
use Jose\Component\Core\Converter\JsonConverter;
17
use Symfony\Component\Console\Command\Command;
18
use Symfony\Component\Console\Input\InputInterface;
19
use Symfony\Component\Console\Input\InputOption;
20
use Symfony\Component\Console\Output\OutputInterface;
21
22
/**
23
 * Class AbstractObjectOutputCommand.
24
 */
25
abstract class ObjectOutputCommand extends Command
26
{
27
    /**
28
     * @var JsonConverter
29
     */
30
    protected $jsonConverter;
31
32
    /**
33
     * AbstractGeneratorCommand constructor.
34
     *
35
     * @param JsonConverter $jsonConverter
36
     * @param string|null   $name
37
     */
38
    public function __construct(JsonConverter $jsonConverter, string $name = null)
39
    {
40
        $this->jsonConverter = $jsonConverter;
41
        parent::__construct($name);
42
    }
43
44
    /**
45
     * Configures the current command.
46
     */
47
    protected function configure()
48
    {
49
        $this
50
            ->addOption('out', 'o', InputOption::VALUE_OPTIONAL, 'File where to save the key. Must be a valid and writable file name.')
51
        ;
52
    }
53
54
    /**
55
     * @param InputInterface    $input
56
     * @param OutputInterface   $output
57
     * @param \JsonSerializable $json
58
     */
59
    protected function prepareJsonOutput(InputInterface $input, OutputInterface $output, \JsonSerializable $json)
60
    {
61
        $json = $this->jsonConverter->encode($json);
62
        $this->prepareOutput($input, $output, $json);
63
    }
64
65
    /**
66
     * @param InputInterface  $input
67
     * @param OutputInterface $output
68
     * @param string          $data
69
     */
70
    protected function prepareOutput(InputInterface $input, OutputInterface $output, string $data)
71
    {
72
        $file = $input->getOption('out');
73
        if (null !== $file) {
74
            file_put_contents($file, $data, LOCK_EX);
75
        } else {
76
            $output->write($data);
77
        }
78
    }
79
}
80