Completed
Push — develop ( f3a4fe...df0b60 )
by Tom
03:55
created

GetCommand::renderAsUpdateScript()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 19
nc 3
nop 2
1
<?php
2
3
namespace N98\Magento\Command\Config\Store;
4
5
use Magento\Config\Model\ResourceModel\Config\Data\Collection;
6
use N98\Magento\Command\Config\AbstractConfigCommand;
7
use N98\Util\Console\Helper\Table\Renderer\RendererFactory;
8
use Symfony\Component\Console\Input\InputArgument;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Input\InputOption;
11
use Symfony\Component\Console\Output\OutputInterface;
12
13
class GetCommand extends AbstractConfigCommand
14
{
15
    /**
16
     * @var Collection
17
     */
18
    private $collection;
19
20
    protected function configure()
21
    {
22
        $this
23
            ->setName('config:store:get')
24
            ->setDescription('Get a store config item')
25
            ->setHelp(
26
                <<<EOT
27
                If <info>path</info> is not set, all available config items will be listed.
28
The <info>path</info> may contain wildcards (*).
29
If <info>path</info> ends with a trailing slash, all child items will be listed. E.g.
30
31
    config:store:get web/
32
is the same as
33
    config:store:get web/*
34
EOT
35
            )
36
            ->addArgument('path', InputArgument::OPTIONAL, 'The config path')
37
            ->addOption(
38
                'scope',
39
                null,
40
                InputOption::VALUE_REQUIRED,
41
                'The config value\'s scope (default, websites, stores)'
42
            )
43
            ->addOption('scope-id', null, InputOption::VALUE_REQUIRED, 'The config value\'s scope ID')
44
            ->addOption(
45
                'decrypt',
46
                null,
47
                InputOption::VALUE_NONE,
48
                'Decrypt the config value using env.php\'s crypt key'
49
            )
50
            ->addOption('update-script', null, InputOption::VALUE_NONE, 'Output as update script lines')
51
            ->addOption('magerun-script', null, InputOption::VALUE_NONE, 'Output for usage with config:store:set')
52
            ->addOption(
53
                'format',
54
                null,
55
                InputOption::VALUE_OPTIONAL,
56
                'Output Format. One of [' . implode(',', RendererFactory::getFormats()) . ']'
57
            );
58
59
        $help = <<<HELP
60
If path is not set, all available config items will be listed. path may contain wildcards (*)
61
HELP;
62
        $this->setHelp($help);
63
    }
64
65
    /**
66
     * @param Collection $collection
67
     */
68
    public function inject(Collection $collection)
69
    {
70
        $this->collection = $collection;
71
    }
72
73
    /**
74
     * @param InputInterface $input
75
     * @param OutputInterface $output
76
     * @return int|void
77
     */
78
    protected function execute(InputInterface $input, OutputInterface $output)
79
    {
80
        $collection = $this->collection;
81
82
        $searchPath = $input->getArgument('path');
83
84
        if (substr($input->getArgument('path'), -1, 1) === '/') {
85
            $searchPath .= '*';
86
        }
87
88
        $collection->addFieldToFilter('path', array(
89
            'like' => str_replace('*', '%', $searchPath),
90
        ));
91
92
        if ($scope = $input->getOption('scope')) {
93
            $collection->addFieldToFilter('scope', array('eq' => $scope));
94
        }
95
96
        if ($scopeId = $input->getOption('scope-id')) {
97
            $collection->addFieldToFilter(
98
                'scope_id',
99
                array('eq' => $scopeId)
100
            );
101
        }
102
103
        $collection->addOrder('path', 'ASC');
104
105
        // sort according to the config overwrite order
106
        // trick to force order default -> (f)website -> store , because f comes after d and before s
107
        $collection->addOrder('REPLACE(scope, "website", "fwebsite")', 'ASC');
108
109
        $collection->addOrder('scope_id', 'ASC');
110
111
        if ($collection->count() == 0) {
112
            $output->writeln(sprintf("Couldn't find a config value for \"%s\"", $input->getArgument('path')));
113
114
            return;
115
        }
116
117
        foreach ($collection as $item) {
118
            $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...
119
                'path'     => $item->getPath(),
120
                'scope'    => $item->getScope(),
121
                'scope_id' => $item->getScopeId(),
122
                'value'    => $this->_formatValue(
123
                    $item->getValue(),
124
                    $input->getOption('decrypt') ? 'decrypt' : ''
125
                ),
126
            );
127
        }
128
129
        ksort($table);
130
131
        if ($input->getOption('update-script')) {
132
            $this->renderAsUpdateScript($output, $table);
133
        } elseif ($input->getOption('magerun-script')) {
134
            $this->renderAsMagerunScript($output, $table);
135
        } else {
136
            $this->renderAsTable($output, $table, $input->getOption('format'));
137
        }
138
    }
139
140
    /**
141
     * @param OutputInterface $output
142
     * @param array $table
143
     * @param string $format
144
     */
145
    protected function renderAsTable(OutputInterface $output, $table, $format)
146
    {
147
        $formattedTable = array();
148
        foreach ($table as $row) {
149
            $formattedTable[] = array(
150
                $row['path'],
151
                $row['scope'],
152
                $row['scope_id'],
153
                $this->renderTableValue($row['value'], $format),
154
            );
155
        }
156
157
        /* @var $tableHelper \N98\Util\Console\Helper\TableHelper */
158
        $tableHelper = $this->getHelper('table');
159
        $tableHelper
160
            ->setHeaders(array('Path', 'Scope', 'Scope-ID', 'Value'))
161
            ->setRows($formattedTable)
162
            ->renderByFormat($output, $formattedTable, $format);
163
    }
164
165
    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...
166
    {
167
        if ($value === null) {
168
            switch ($format) {
169
                case null:
170
                    $value = self::DISPLAY_NULL_UNKOWN_VALUE;
171
                    break;
172
                case 'json':
173
                    break;
174
                case 'csv':
175
                case 'xml':
176
                    $value = 'NULL';
177
                    break;
178
                default:
179
                    throw new \UnexpectedValueException(
180
                        sprintf("Unhandled format %s", var_export($value, true))
181
                    );
182
            }
183
        }
184
185
        return $value;
186
    }
187
188
    /**
189
     * @param OutputInterface $output
190
     * @param array $table
191
     */
192
    protected function renderAsUpdateScript(OutputInterface $output, $table)
193
    {
194
        $output->writeln('<?php');
195
        $output->writeln('$installer = $this;');
196
        $output->writeln('# generated by n98-magerun');
197
198
        foreach ($table as $row) {
199
            if ($row['scope'] == 'default') {
200
                $output->writeln(
201
                    sprintf(
202
                        '$installer->setConfigData(%s, %s);',
203
                        var_export($row['path'], true),
204
                        var_export($row['value'], true)
205
                    )
206
                );
207
            } else {
208
                $output->writeln(
209
                    sprintf(
210
                        '$installer->setConfigData(%s, %s, %s, %s);',
211
                        var_export($row['path'], true),
212
                        var_export($row['value'], true),
213
                        var_export($row['scope'], true),
214
                        var_export($row['scope_id'], true)
215
                    )
216
                );
217
            }
218
        }
219
    }
220
221
    /**
222
     * @param OutputInterface $output
223
     * @param array $table
224
     */
225
    protected function renderAsMagerunScript(OutputInterface $output, $table)
226
    {
227
        foreach ($table as $row) {
228
            $value = $row['value'];
229
            if ($value !== null) {
230
                $value = str_replace(array("\n", "\r"), array('\n', '\r'), $value);
231
            }
232
233
            $disaplayValue = $value === null ? "NULL" : escapeshellarg($value);
234
            $protectNullString = $value === "NULL" ? '--no-null ' : '';
235
236
            $line = sprintf(
237
                'config:store:set %s--scope-id=%s --scope=%s -- %s %s',
238
                $protectNullString,
239
                $row['scope_id'],
240
                $row['scope'],
241
                escapeshellarg($row['path']),
242
                $disaplayValue
243
            );
244
            $output->writeln($line);
245
        }
246
    }
247
}
248