Completed
Push — master ( 880b7a...33b151 )
by Tom
09:34 queued 06:03
created

DummyCommand::askForArguments()   C

Complexity

Conditions 11
Paths 32

Size

Total Lines 82
Code Lines 52

Duplication

Lines 26
Ratio 31.71 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 26
loc 82
rs 5.2653
cc 11
eloc 52
nc 32
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace N98\Magento\Command\Category\Create;
4
5
use Mage;
6
use RuntimeException;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Console\Question\ChoiceQuestion;
11
use Symfony\Component\Console\Question\Question;
12
13
class DummyCommand extends \N98\Magento\Command\AbstractMagentoCommand
14
{
15
    const DEFAULT_CATEGORY_NAME = "My Awesome Category";
16
    const DEFAULT_CATEGORY_STATUS = 1; // enabled
17
    const DEFAULT_CATEGORY_ANCHOR = 1; // enabled
18
    const DEFAULT_STORE_ID = 1; // Default Store ID
19
20
    protected function configure()
21
    {
22
        $this
23
            ->setName('category:create:dummy')
24
            ->addArgument('store-id', InputArgument::OPTIONAL, 'Id of Store to create categories (default: 1)')
25
            ->addArgument('category-number', InputArgument::OPTIONAL, 'Number of categories to create (default: 1)')
26
            ->addArgument(
27
                'children-categories-number',
28
                InputArgument::OPTIONAL,
29
                "Number of children for each category created (default: 0 - use '-1' for random from 0 to 5)"
30
            )
31
            ->addArgument(
32
                'category-name-prefix',
33
                InputArgument::OPTIONAL,
34
                "Category Name Prefix (default: 'My Awesome Category')"
35
            )
36
            ->setDescription('Create a dummy category');
37
    }
38
39
    /**
40
     * @param InputInterface $input
41
     * @param OutputInterface $output
42
     *
43
     * @return int|void
44
     */
45
    protected function execute(InputInterface $input, OutputInterface $output)
46
    {
47
        $this->detectMagento($output, true);
48
        $this->initMagento();
49
50
        $output->writeln("<warning>This only create sample categories, do not use on production environment</warning>");
51
52
        // Ask for Arguments
53
        $_argument = $this->askForArguments($input, $output);
54
55
        /**
56
         * Loop to create categories
57
         */
58
        for ($i = 0; $i < $_argument['category-number']; $i++) {
59
            if (!is_null($_argument['category-name-prefix'])) {
60
                $name = $_argument['category-name-prefix'] . " " . $i;
61
            } else {
62
                $name = self::DEFAULT_CATEGORY_NAME . " " . $i;
63
            }
64
65
            // Check if product exists
66
            $collection = Mage::getModel('catalog/category')->getCollection()
67
                ->addAttributeToSelect('name')
68
                ->addAttributeToFilter('name', array('eq' => $name));
69
            $_size = $collection->getSize();
70
            if ($_size > 0) {
71
                $output->writeln("<comment>CATEGORY: WITH NAME: '" . $name . "' EXISTS! Skip</comment>\r");
72
                $_argument['category-number']++;
73
                continue;
74
            }
75
            unset($collection);
76
77
            $_category_root_id = Mage::app()->getStore($_argument['store-id'])->getRootCategoryId();
78
79
            $category = Mage::getModel('catalog/category');
80
            $category->setName($name);
81
            $category->setIsActive(self::DEFAULT_CATEGORY_STATUS);
82
            $category->setDisplayMode('PRODUCTS');
83
            $category->setIsAnchor(self::DEFAULT_CATEGORY_ANCHOR);
84
85 View Code Duplication
            if (Mage::getVersion() === "1.5.1.0") {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
                $category->setStoreId(array(0, $_argument['store-id']));
87
            } else {
88
                $category->setStoreId($_argument['store-id']);
89
            }
90
            $parentCategory = Mage::getModel('catalog/category')->load($_category_root_id);
91
            $category->setPath($parentCategory->getPath());
92
93
            $category->save();
94
            $_parent_id = $category->getId();
95
            $output->writeln(
96
                "<comment>CATEGORY: '" . $category->getName() . "' WITH ID: '" . $category->getId() .
97
                "' CREATED!</comment>"
98
            );
99
            unset($category);
100
101
            // Create children Categories
102
            for ($j = 0; $j < $_argument['children-categories-number']; $j++) {
103
                $name_child = $name . " child " . $j;
104
105
                $category = Mage::getModel('catalog/category');
106
                $category->setName($name_child);
107
                $category->setIsActive(self::DEFAULT_CATEGORY_STATUS);
108
                $category->setDisplayMode('PRODUCTS');
109
                $category->setIsAnchor(self::DEFAULT_CATEGORY_ANCHOR);
110
111 View Code Duplication
                if (Mage::getVersion() === "1.5.1.0") {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
                    $category->setStoreId(array(0, $_argument['store-id']));
113
                } else {
114
                    $category->setStoreId($_argument['store-id']);
115
                }
116
                $parentCategory = Mage::getModel('catalog/category')->load($_parent_id);
117
                $category->setPath($parentCategory->getPath());
118
119
                $category->save();
120
                $output->writeln(
121
                    "<comment>CATEGORY CHILD: '" . $category->getName() . "' WITH ID: '" . $category->getId() .
122
                    "' CREATED!</comment>"
123
                );
124
                unset($category);
125
            }
126
        }
127
    }
128
129
    /**
130
     * Ask for command arguments
131
     *
132
     * @param InputInterface $input
133
     * @param OutputInterface $output
134
     *
135
     * @return array
136
     */
137
    private function askForArguments($input, $output)
138
    {
139
        $helper = $this->getHelper('question');
140
        $_argument = array();
141
142
        // Store ID
143
        if (is_null($input->getArgument('store-id'))) {
144
            $store_id = Mage::getModel('core/store')->getCollection()
145
                ->addFieldToSelect('*')
146
                ->addFieldToFilter('store_id', array('gt' => 0))
147
                ->setOrder('store_id', 'ASC');
148
            $_store_ids = array();
149
150
            foreach ($store_id as $item) {
151
                $_store_ids[$item['store_id']] = $item['store_id'] . "|" . $item['code'];
152
            }
153
154
            $question = new ChoiceQuestion('Please select Store ID (default: 1)', $_store_ids, self::DEFAULT_STORE_ID);
155
            $question->setErrorMessage('Store ID "%s" is invalid.');
156
            $response = explode("|", $helper->ask($input, $output, $question));
157
            $input->setArgument('store-id', $response[0]);
158
        }
159
        $output->writeln('<info>Store ID selected: ' . $input->getArgument('store-id') . "</info>");
160
        $_argument['store-id'] = $input->getArgument('store-id');
161
162
        // Number of Categories
163 View Code Duplication
        if (is_null($input->getArgument('category-number'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
            $question = new Question("Please enter the number of categories to create (default 1): ", 1);
165
            $question->setValidator(function ($answer) {
166
                $answer = (int) $answer;
167
                if (!is_int($answer) || $answer <= 0) {
168
                    throw new RuntimeException('Please enter an integer value or > 0');
169
                }
170
171
                return $answer;
172
            });
173
            $input->setArgument('category-number', $helper->ask($input, $output, $question));
174
        }
175
        $output->writeln(
176
            '<info>Number of categories to create: ' . $input->getArgument('category-number') . "</info>"
177
        );
178
        $_argument['category-number'] = $input->getArgument('category-number');
179
180
        // Number of child categories
181 View Code Duplication
        if (is_null($input->getArgument('children-categories-number'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
            $question = new Question(
183
                "Number of children for each category created (default: 0 - use '-1' for random from 0 to 5): ",
184
                0
185
            );
186
            $question->setValidator(function ($answer) {
187
                $answer = (int) $answer;
188
                if (!is_int($answer) || $answer < -1) {
189
                    throw new RuntimeException("Please enter an integer value or >= -1");
190
                }
191
192
                return $answer;
193
            });
194
            $input->setArgument('children-categories-number', $helper->ask($input, $output, $question));
195
        }
196
        if ($input->getArgument('children-categories-number') == -1) {
197
            $input->setArgument('children-categories-number', rand(0, 5));
198
        }
199
200
        $output->writeln(
201
            '<info>Number of categories children to create: ' . $input->getArgument('children-categories-number') .
202
            "</info>"
203
        );
204
        $_argument['children-categories-number'] = $input->getArgument('children-categories-number');
205
206
        // Category name prefix
207
        if (is_null($input->getArgument('category-name-prefix'))) {
208
            $question = new Question(
209
                "Please enter the category name prefix (default '" . self::DEFAULT_CATEGORY_NAME . "'): ",
210
                self::DEFAULT_CATEGORY_NAME
211
            );
212
            $input->setArgument('category-name-prefix', $helper->ask($input, $output, $question));
213
        }
214
        $output->writeln('<info>CATEGORY NAME PREFIX: ' . $input->getArgument('category-name-prefix') . "</info>");
215
        $_argument['category-name-prefix'] = $input->getArgument('category-name-prefix');
216
217
        return $_argument;
218
    }
219
}
220