AbstractCommand::outputFormatJson()   B
last analyzed

Complexity

Conditions 8
Paths 2

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.1795
c 0
b 0
f 0
cc 8
nc 2
nop 2
1
<?php
2
/**
3
 * Mage Scan
4
 *
5
 * PHP version 5
6
 *
7
 * @category  MageScan
8
 * @package   MageScan
9
 * @author    Steve Robbins <[email protected]>
10
 * @copyright 2015 Steve Robbins
11
 * @license   http://creativecommons.org/licenses/by/4.0/ CC BY 4.0
12
 * @link      https://github.com/steverobbins/magescan
13
 */
14
15
namespace MageScan\Command\Scan;
16
17
use MageScan\Request;
18
use MageScan\Url;
19
use Symfony\Component\Console\Command\Command;
20
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
21
use Symfony\Component\Console\Helper\Table;
22
use Symfony\Component\Console\Input\InputArgument;
23
use Symfony\Component\Console\Input\InputInterface;
24
use Symfony\Component\Console\Input\InputOption;
25
use Symfony\Component\Console\Output\OutputInterface;
26
27
/**
28
 * Abstract scan command
29
 *
30
 * @category  MageScan
31
 * @package   MageScan
32
 * @author    Steve Robbins <[email protected]>
33
 * @copyright 2015 Steve Robbins
34
 * @license   http://creativecommons.org/licenses/by/4.0/ CC BY 4.0
35
 * @link      https://github.com/steverobbins/magescan
36
 */
37
abstract class AbstractCommand extends Command
38
{
39
    /**
40
     * Input object
41
     *
42
     * @var \Symfony\Component\Console\Input\InputInterface
43
     */
44
    protected $input;
45
46
    /**
47
     * Output object
48
     *
49
     * @var \Symfony\Component\Console\Output\OutputInterface
50
     */
51
    protected $output;
52
53
    /**
54
     * Cached request object with desired secure flag
55
     *
56
     * @var \MageScan\Request
57
     */
58
    protected $request;
59
60
    /**
61
     * Configure command
62
     *
63
     * @return void
64
     */
65
    protected function configure()
66
    {
67
        $this
68
            ->addArgument(
69
                'url',
70
                InputArgument::REQUIRED,
71
                'The URL of the Magento application'
72
            )
73
            ->addOption(
74
                'insecure',
75
                'k',
76
                InputOption::VALUE_NONE,
77
                'Don\'t validate SSL certificate if URL is https'
78
            )
79
            ->addOption(
80
                'format',
81
                null,
82
                InputOption::VALUE_REQUIRED,
83
                'Specify output format (default, json)',
84
                'default'
85
            );
86
    }
87
88
    /**
89
     * Initialize command
90
     *
91
     * @param InputInterface  $input
92
     * @param OutputInterface $output
93
     *
94
     * @return void
95
     */
96
    protected function initialize(InputInterface $input, OutputInterface $output)
97
    {
98
        $this->input   = $input;
99
        $this->output  = $output;
100
        $url = new Url;
101
        try {
102
            $this->request = new Request(
103
                $url->clean($input->getArgument('url')),
0 ignored issues
show
Bug introduced by
It seems like $input->getArgument('url') targeting Symfony\Component\Consol...nterface::getArgument() can also be of type array<integer,string>; however, MageScan\Url::clean() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
104
                $this->input->getOption('insecure')
105
            );
106
        } catch (\InvalidArgumentException $e) {
107
            // do nothing
108
        }
109
        $style = new OutputFormatterStyle('white', 'blue', ['bold']);
110
        $this->output->getFormatter()->setStyle('header', $style);
111
    }
112
113
    /**
114
     * Output information in the correct format
115
     *
116
     * @param string       $title
117
     * @param array|string $messages
118
     *
119
     * @return void
120
     */
121
    protected function out($title, $messages = [])
122
    {
123
        $format = $this->input->getOption('format');
124
        $method = 'outputFormat' . ucfirst($format);
125
        if (!method_exists($this, $method)) {
126
            throw new \InvalidArgumentException(
127
                'Format "' . $format . '" is not supported'
128
            );
129
        }
130
        $this->$method($title, $messages);
131
    }
132
133
    /**
134
     * Output in default format
135
     *
136
     * @param string       $title
137
     * @param array|string $messages
138
     *
139
     * @return void
140
     */
141
    protected function outputFormatDefault($title, $messages)
142
    {
143
        $this->writeHeader($title);
144
        if (!is_array($messages)) {
145
            return $this->output->writeln($messages);
146
        }
147
        foreach ($messages as $message) {
148
            switch (isset($message['type']) ? $message['type'] : false) {
149
                case 'table':
150
                    $tableHelper = new Table($this->output);
151
                    $tableHelper
152
                        ->setHeaders($message['data'][0])
153
                        ->setRows($message['data'][1])
154
                        ->render();
155
                    break;
156
                default:
157
                    $this->output->writeln(is_array($message) ? $message['data'] : $message);
158
            }
159
        }
160
    }
161
162
    /**
163
     * Output in json format
164
     *
165
     * @param string       $title
166
     * @param array|string $messages
167
     *
168
     * @return void
169
     */
170
    protected function outputFormatJson($title, $messages)
171
    {
172
        $json = [
173
            'name'     => $title,
174
            'results'  => [],
175
            'messages' => [],
176
        ];
177
        if (!is_array($messages)) {
178
            $json['messages'][] = strip_tags($messages);
179
        } else {
180
            foreach ($messages as $message) {
181
                switch (isset($message['type']) ? $message['type'] : false) {
182
                    case 'table':
183
                        $result = [];
184
                        $headers = $message['data'][0];
185
                        array_map('strtolower', $headers);
186
                        foreach ($message['data'][1] as $row) {
187
                            foreach ($headers as $key => $name) {
188
                                $result[$name] = strip_tags($row[$key]);
189
                            }
190
                            $json['results'][] = $result;
191
                        }
192
                        break;
193
                    default:
194
                        $json['messages'][] = strip_tags(is_array($message) ? $message['data'] : $message);
195
                }
196
            }
197
        }
198
199
        $this->output->write(json_encode($json), false, OutputInterface::OUTPUT_RAW);
200
    }
201
202
    /**
203
     * Write a header block
204
     *
205
     * @param string $text
206
     * @param string $style
207
     *
208
     * @return void
209
     */
210
    protected function writeHeader($text, $style = 'bg=blue;fg=white')
211
    {
212
        $this->output->writeln([
213
            '',
214
            $this->getHelperSet()->get('formatter')
215
                ->formatBlock($text, $style, true),
216
            '',
217
        ]);
218
    }
219
}
220