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