Completed
Push — develop ( e5a1d6...4fa884 )
by Tom
03:46
created

GetCommand::renderTableValue()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
rs 8.6737
cc 6
eloc 16
nc 6
nop 2
1
<?php
2
3
namespace N98\Magento\Command\Config;
4
5
use Magento\Config\Model\ResourceModel\Config\Data\Collection;
6
use N98\Util\Console\Helper\Table\Renderer\RendererFactory;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
class GetCommand extends AbstractConfigCommand
13
{
14
    /**
15
     * @var Collection
16
     */
17
    private $collection;
18
19
    protected function configure()
20
    {
21
        $this
22
            ->setName('config:get')
23
            ->setDescription('Get a core config item')
24
            ->setHelp(
25
                <<<EOT
26
                If <info>path</info> is not set, all available config items will be listed.
27
The <info>path</info> may contain wildcards (*).
28
If <info>path</info> ends with a trailing slash, all child items will be listed. E.g.
29
30
    config:get web/
31
is the same as
32
    config:get web/*
33
EOT
34
            )
35
            ->addArgument('path', InputArgument::OPTIONAL, 'The config path')
36
            ->addOption('scope', null, InputOption::VALUE_REQUIRED, 'The config value\'s scope')
37
            ->addOption('scope-id', null, InputOption::VALUE_REQUIRED, 'The config value\'s scope ID')
38
            ->addOption(
39
                'decrypt',
40
                null,
41
                InputOption::VALUE_NONE,
42
                'Decrypt the config value using env.php\'s crypt key'
43
            )
44
            ->addOption('update-script', null, InputOption::VALUE_NONE, 'Output as update script lines')
45
            ->addOption('magerun-script', null, InputOption::VALUE_NONE, 'Output for usage with config:set')
46
            ->addOption(
47
                'format',
48
                null,
49
                InputOption::VALUE_OPTIONAL,
50
                'Output Format. One of [' . implode(',', RendererFactory::getFormats()) . ']'
51
            );
52
53
        $help = <<<HELP
54
If path is not set, all available config items will be listed. path may contain wildcards (*)
55
HELP;
56
        $this->setHelp($help);
57
    }
58
59
    /**
60
     * @param Collection $collection
61
     */
62
    public function inject(Collection $collection)
63
    {
64
        $this->collection = $collection;
65
    }
66
67
    /**
68
     * @param InputInterface $input
69
     * @param OutputInterface $output
70
     * @return int|void
71
     */
72
    protected function execute(InputInterface $input, OutputInterface $output)
73
    {
74
        $collection = $this->collection;
75
76
        $searchPath = $input->getArgument('path');
77
78
        if (substr($input->getArgument('path'), -1, 1) === '/') {
79
            $searchPath .= '*';
80
        }
81
82
        $collection->addFieldToFilter('path', array(
83
            'like' => str_replace('*', '%', $searchPath),
84
        ));
85
86
        if ($scopeId = $input->getOption('scope')) {
87
            $collection->addFieldToFilter('scope', array('eq' => $scopeId));
88
        }
89
90
        if ($scopeId = $input->getOption('scope-id')) {
91
            $collection->addFieldToFilter(
92
                'scope_id',
93
                array('eq' => $scopeId)
94
            );
95
        }
96
97
        $collection->addOrder('path', 'ASC');
98
99
        // sort according to the config overwrite order
100
        // trick to force order default -> (f)website -> store , because f comes after d and before s
101
        $collection->addOrder('REPLACE(scope, "website", "fwebsite")', 'ASC');
102
103
        $collection->addOrder('scope_id', 'ASC');
104
105
        if ($collection->count() == 0) {
106
            $output->writeln(sprintf("Couldn't find a config value for \"%s\"", $input->getArgument('path')));
107
108
            return;
109
        }
110
111
        foreach ($collection as $item) {
112
            $table[] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$table was never initialized. Although not strictly required by PHP, it is generally a good practice to add $table = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
113
                'path'     => $item->getPath(),
114
                'scope'    => $item->getScope(),
115
                'scope_id' => $item->getScopeId(),
116
                'value'    => $this->_formatValue(
117
                    $item->getValue(),
118
                    $input->getOption('decrypt') ? 'decrypt' : false
0 ignored issues
show
Security Bug introduced by
It seems like $input->getOption('decrypt') ? 'decrypt' : false can also be of type false; however, N98\Magento\Command\Conf...Command::_formatValue() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
119
                ),
120
            );
121
        }
122
123
        ksort($table);
124
125
        if ($input->getOption('update-script')) {
126
            $this->renderAsUpdateScript($output, $table);
127
        } elseif ($input->getOption('magerun-script')) {
128
            $this->renderAsMagerunScript($output, $table);
129
        } else {
130
            $this->renderAsTable($output, $table, $input->getOption('format'));
131
        }
132
    }
133
134
    /**
135
     * @param OutputInterface $output
136
     * @param array $table
137
     * @param string $format
138
     */
139
    protected function renderAsTable(OutputInterface $output, $table, $format)
140
    {
141
        $formattedTable = array();
142
        foreach ($table as $row) {
143
            $formattedTable[] = array(
144
                $row['path'],
145
                $row['scope'],
146
                $row['scope_id'],
147
                $this->renderTableValue($row['value'], $format),
148
            );
149
        }
150
151
        /* @var $tableHelper \N98\Util\Console\Helper\TableHelper */
152
        $tableHelper = $this->getHelper('table');
153
        $tableHelper
154
            ->setHeaders(array('Path', 'Scope', 'Scope-ID', 'Value'))
155
            ->setRows($formattedTable)
156
            ->renderByFormat($output, $formattedTable, $format);
157
    }
158
159
    private function renderTableValue($value, $format)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
160
    {
161
        if ($value === null) {
162
            switch ($format) {
163
                case null:
164
                    $value = self::DISPLAY_NULL_UNKOWN_VALUE;
165
                    break;
166
                case 'json':
167
                    break;
168
                case 'csv':
169
                case 'xml':
170
                    $value = 'NULL';
171
                    break;
172
                default:
173
                    throw new \UnexpectedValueException(
174
                        sprintf("Unhandled format %s", var_export($value, true))
175
                    );
176
            }
177
        }
178
179
        return $value;
180
    }
181
182
    /**
183
     * @param OutputInterface $output
184
     * @param array $table
185
     */
186
    protected function renderAsUpdateScript(OutputInterface $output, $table)
187
    {
188
        $output->writeln('<?php');
189
        $output->writeln('$installer = $this;');
190
        $output->writeln('# generated by n98-magerun');
191
192
        foreach ($table as $row) {
193
            if ($row['scope'] == 'default') {
194
                $output->writeln(
195
                    sprintf(
196
                        '$installer->setConfigData(%s, %s);',
197
                        var_export($row['path'], true),
198
                        var_export($row['value'], true)
199
                    )
200
                );
201
            } else {
202
                $output->writeln(
203
                    sprintf(
204
                        '$installer->setConfigData(%s, %s, %s, %s);',
205
                        var_export($row['path'], true),
206
                        var_export($row['value'], true),
207
                        var_export($row['scope'], true),
208
                        var_export($row['scope_id'], true)
209
                    )
210
                );
211
            }
212
        }
213
    }
214
215
    /**
216
     * @param OutputInterface $output
217
     * @param array $table
218
     */
219
    protected function renderAsMagerunScript(OutputInterface $output, $table)
220
    {
221
        foreach ($table as $row) {
222
            $value = $row['value'];
223
            if ($value !== null) {
224
                $value = str_replace(array("\n", "\r"), array('\n', '\r'), $value);
225
            }
226
227
            $disaplayValue = $value === null ? "NULL" : escapeshellarg($value);
228
            $protectNullString = $value === "NULL" ? '--no-null ' : '';
229
230
            $line = sprintf(
231
                'config:set %s--scope-id=%s --scope=%s -- %s %s',
232
                $protectNullString,
233
                $row['scope_id'],
234
                $row['scope'],
235
                escapeshellarg($row['path']),
236
                $disaplayValue
237
            );
238
            $output->writeln($line);
239
        }
240
    }
241
}
242