Completed
Pull Request — master (#177)
by
unknown
04:33
created

GetCommand::renderAsTable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 16
rs 9.4285
cc 2
eloc 12
nc 2
nop 3
1
<?php
2
3
namespace N98\Magento\Command\Config;
4
5
use Symfony\Component\Console\Input\InputArgument;
6
use Symfony\Component\Console\Input\InputInterface;
7
use Symfony\Component\Console\Input\InputOption;
8
use Symfony\Component\Console\Output\Output;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use N98\Util\Console\Helper\Table\Renderer\RendererFactory;
11
12
class GetCommand extends AbstractConfigCommand
13
{
14
    /**
15
     * @var \Magento\Config\Model\ResourceModel\Config\Data\Collection
16
     */
17
    protected $_collection;
18
19
    protected function configure()
20
    {
21
        $this
22
            ->setName('config:get')
23
            ->setDescription('Get a core config item')
24
            ->setHelp(<<<EOT
25
If <info>path</info> is not set, all available config items will be listed.
26
The <info>path</info> may contain wildcards (*).
27
If <info>path</info> ends with a trailing slash, all child items will be listed. E.g.
28
29
    config:get web/ 
30
is the same as
31
    config:get web/*
32
EOT
33
                )
34
            ->addArgument('path', InputArgument::OPTIONAL, 'The config path')
35
            ->addOption('scope', null, InputOption::VALUE_REQUIRED, 'The config value\'s scope')
36
            ->addOption('scope-id', null, InputOption::VALUE_REQUIRED, 'The config value\'s scope ID')
37
            ->addOption('decrypt', null, InputOption::VALUE_NONE, 'Decrypt the config value using local.xml\'s crypt key')
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
38
            ->addOption('update-script', null, InputOption::VALUE_NONE, 'Output as update script lines')
39
            ->addOption('magerun-script', null, InputOption::VALUE_NONE, 'Output for usage with config:set')
40
            ->addOption(
41
                'format',
42
                null,
43
                InputOption::VALUE_OPTIONAL,
44
                'Output Format. One of [' . implode(',', RendererFactory::getFormats()) . ']'
45
            )
46
        ;
47
48
        $help = <<<HELP
49
If path is not set, all available config items will be listed. path may contain wildcards (*)
50
HELP;
51
        $this->setHelp($help);
52
    }
53
54
    /**
55
     * @param \Magento\Config\Model\ResourceModel\Config\Data\Collection $collection
56
     */
57
    public function inject(\Magento\Config\Model\ResourceModel\Config\Data\Collection $collection)
58
    {
59
        $this->_collection = $collection;
60
    }
61
62
    /**
63
     * @param InputInterface $input
64
     * @param \Symfony\Component\Console\Output\OutputInterface $output
65
     * @return int|void
66
     */
67
    protected function execute(InputInterface $input, OutputInterface $output)
68
    {
69
        $searchPath = $input->getArgument('path');
70
71
        if (substr($input->getArgument('path'), -1, 1) === '/') {
72
            $searchPath .= '*';
73
        }
74
75
        $this->_collection->addFieldToFilter('path', array(
76
            'like' => str_replace('*', '%', $searchPath)
77
        ));
78
79
        if ($scopeId = $input->getOption('scope')) {
80
            $this->_collection->addFieldToFilter(
81
                'scope',
82
                array(
83
                     'eq' => $scopeId
84
                )
85
            );
86
        }
87
88
        if ($scopeId = $input->getOption('scope-id')) {
89
            $this->_collection->addFieldToFilter(
90
                'scope_id',
91
                array(
92
                    'eq' => $scopeId
93
                )
94
            );
95
        }
96
97
        $this->_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
        $this->_collection->addOrder('REPLACE(scope, "website", "fwebsite")', 'ASC');
102
103
        $this->_collection->addOrder('scope_id', 'ASC');
104
105
        if ($this->_collection->count() == 0) {
106
            $output->writeln(sprintf("Couldn't find a config value for \"%s\"", $input->getArgument('path')));
107
            return;
108
        }
109
110
        foreach ($this->_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($item->getValue(), ($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...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
116
            );
117
        }
118
119
        ksort($table);
120
121
        if ($input->getOption('update-script')) {
122
            $this->renderAsUpdateScript($output, $table);
123
        } elseif ($input->getOption('magerun-script')) {
124
            $this->renderAsMagerunScript($output, $table);
125
        } else {
126
            $this->renderAsTable($output, $table, $input->getOption('format'));
127
        }
128
    }
129
130
    /**
131
     * @param OutputInterface $output
132
     * @param array $table
133
     * @param string $format
134
     */
135
    protected function renderAsTable(OutputInterface $output, $table, $format)
136
    {
137
        $formattedTable = array();
138
        foreach ($table as $row) {
139
            $formattedTable[] = array(
140
                $row['path'],
141
                $row['scope'],
142
                $row['scope_id'],
143
                $row['value'],
144
            );
145
        }
146
        $this->getHelper('table')
147
            ->setHeaders(array('Path', 'Scope', 'Scope-ID', 'Value'))
148
            ->setRows($formattedTable)
149
            ->renderByFormat($output, $formattedTable, $format);
150
    }
151
152
    /**
153
     * @param OutputInterface $output
154
     * @param array           $table
155
     */
156
    protected function renderAsUpdateScript(OutputInterface $output, $table)
157
    {
158
        $output->writeln('<?php');
159
        $output->writeln('$installer = $this;');
160
        $output->writeln('# generated by n98-magerun');
161
162
        foreach ($table as $row) {
163
            if ($row['scope'] == 'default') {
164
                $output->writeln(
165
                    sprintf(
166
                        '$installer->setConfigData(%s, %s);', var_export($row['path'], true),
167
                        var_export($row['value'], true)
168
                    )
169
                );
170
            } else {
171
                $output->writeln(
172
                    sprintf(
173
                        '$installer->setConfigData(%s, %s, %s, %s);',
174
                        var_export($row['path'], true),
175
                        var_export($row['value'], true),
176
                        var_export($row['scope'], true),
177
                        var_export($row['scope_id'], true)
178
                    )
179
                );
180
            }
181
        }
182
    }
183
184
    /**
185
     * @param OutputInterface $output
186
     * @param array           $table
187
     */
188
    protected function renderAsMagerunScript(OutputInterface $output, $table)
189
    {
190
        foreach ($table as $row) {
191
            $value = str_replace(array("\n", "\r"), array('\n', '\r'), $row['value']);
192
            $line = 'config:set ' . $row['path']
193
                  . ' --scope-id=' . $row['scope_id']
194
                  . ' --scope=' . $row['scope']
195
                  . ' ' . escapeshellarg($value);
196
            $output->writeln($line);
197
        }
198
    }
199
}
200