Completed
Push — develop ( 16b53b...b1079f )
by Tom
05:14
created

DummyCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 9
rs 9.6666
cc 1
eloc 7
nc 1
nop 0
1
<?php
2
3
namespace N98\Magento\Command\Category\Create;
4
5
use Mage;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
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->setName('category:create:dummy')
23
             ->addArgument('store-id', InputArgument::OPTIONAL, 'Id of Store to create categories (default: 1)')
24
             ->addArgument('category-number', InputArgument::OPTIONAL, 'Number of categories to create (default: 1)')
25
             ->addArgument('children-categories-number', InputArgument::OPTIONAL, "Number of children for each category created (default: 0 - use '-1' for random from 0 to 5)")
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 176 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...
26
             ->addArgument('category-name-prefix', InputArgument::OPTIONAL, "Category Name Prefix (default: 'My Awesome Category')")
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 132 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...
27
             ->setDescription('Create a dummy category');
28
    }
29
30
    /**
31
     * @param InputInterface  $input
32
     * @param OutputInterface $output
33
     *
34
     * @return int|void
35
     */
36
    protected function execute(InputInterface $input, OutputInterface $output)
37
    {
38
        $this->detectMagento($output, true);
39
        $this->initMagento();
40
41
        $output->writeln("<warning>This only create sample categories, do not use on production environment</warning>");
42
43
        // Ask for Arguments
44
        $_argument = $this->askForArguments($input, $output);
45
46
        /**
47
         * Loop to create categories
48
         */
49
        for($i = 0; $i < $_argument['category-number']; $i++) {
50
            if(!is_null($_argument['category-name-prefix'])) {
51
                $name = $_argument['category-name-prefix']." ".$i;
52
            }
53
            else {
54
                $name = self::DEFAULT_CATEGORY_NAME." ".$i;
55
            }
56
57
            // Check if product exists
58
            $collection = Mage::getModel('catalog/category')->getCollection()
59
                              ->addAttributeToSelect('name')
60
                              ->addAttributeToFilter('name', array('eq' => $name));
61
            $_size = $collection->getSize();
62
            if($_size > 0) {
63
                $output->writeln("<comment>CATEGORY: WITH NAME: '".$name."' EXISTS! Skip</comment>");
64
                $_argument['category-number']++;
65
                continue;
66
            }
67
            unset($collection);
68
69
            $_category_root_id = Mage::app()->getStore($_argument['store-id'])->getRootCategoryId();
70
71
            $category = Mage::getModel('catalog/category');
72
            $category->setName($name);
73
            $category->setIsActive(self::DEFAULT_CATEGORY_STATUS);
74
            $category->setDisplayMode('PRODUCTS');
75
            $category->setIsAnchor(self::DEFAULT_CATEGORY_ANCHOR);
76
77 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...
78
                $category->setStoreId(array(0, $_argument['store-id']));
79
            }
80
            else {
81
                $category->setStoreId($_argument['store-id']);
82
            }
83
            $parentCategory = Mage::getModel('catalog/category')->load($_category_root_id);
84
            $category->setPath($parentCategory->getPath());
85
86
            $category->save();
87
            $_parent_id = $category->getId();
88
            $output->writeln("<comment>CATEGORY: '".$category->getName()."' WITH ID: '".$category->getId()."' CREATED!</comment>");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 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...
89
            unset($category);
90
91
            // Create children Categories
92
            for($j = 0; $j < $_argument['children-categories-number']; $j++) {
93
                $name_child = $name." child ".$j;
94
95
                $category = Mage::getModel('catalog/category');
96
                $category->setName($name_child);
97
                $category->setIsActive(self::DEFAULT_CATEGORY_STATUS);
98
                $category->setDisplayMode('PRODUCTS');
99
                $category->setIsAnchor(self::DEFAULT_CATEGORY_ANCHOR);
100
101 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...
102
                    $category->setStoreId(array(0, $_argument['store-id']));
103
                }
104
                else {
105
                    $category->setStoreId($_argument['store-id']);
106
                }
107
                $parentCategory = Mage::getModel('catalog/category')->load($_parent_id);
108
                $category->setPath($parentCategory->getPath());
109
110
                $category->save();
111
                $output->writeln("<comment>CATEGORY CHILD: '".$category->getName()."' WITH ID: '".$category->getId()."' CREATED!</comment>");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 141 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...
112
                unset($category);
113
            }
114
        }
115
    }
116
117
    /**
118
     * Ask for command arguments
119
     *
120
     * @param InputInterface  $input
121
     * @param OutputInterface $output
122
     *
123
     * @return array
124
     */
125
    private function askForArguments($input, $output)
126
    {
127
        $helper = $this->getHelper('question');
128
        $_argument = array();
129
130
        // Store ID
131
        if(is_null($input->getArgument('store-id'))) {
132
            $store_id = Mage::getModel('core/store')->getCollection()
133
                            ->addFieldToSelect('*')
134
                            ->addFieldToFilter('store_id', array('gt' => 0))
135
                            ->setOrder('store_id', 'ASC');
136
            $_store_ids = array();
137
138
            foreach($store_id as $item) {
139
                $_store_ids[$item['store_id']] = $item['store_id']."|".$item['code'];
140
            }
141
142
            $question = new ChoiceQuestion('Please select Store ID (default: 1)', $_store_ids, self::DEFAULT_STORE_ID);
143
            $question->setErrorMessage('Store ID "%s" is invalid.');
144
            $response = explode("|", $helper->ask($input, $output, $question));
145
            $input->setArgument('store-id', $response[0]);
146
        }
147
        $output->writeln('<info>Store ID selected: '.$input->getArgument('store-id')."</info>");
148
        $_argument['store-id'] = $input->getArgument('store-id');
149
150
        // Number of Categories
151 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...
152
            $question = new Question("Please enter the number of categories to create (default 1): ", 1);
153
            $question->setValidator(function($answer) {
154
                $answer = (int)($answer);
155
                if(!is_int($answer) || $answer <= 0) {
156
                    throw new \RuntimeException('Please enter an integer value or > 0');
157
                }
158
159
                return $answer;
160
            });
161
            $input->setArgument('category-number', $helper->ask($input, $output, $question));
162
        }
163
        $output->writeln('<info>Number of categories to create: '.$input->getArgument('category-number')."</info>");
164
        $_argument['category-number'] = $input->getArgument('category-number');
165
166
        // Number of children categories
167 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...
168
            $question = new Question("Number of children for each category created (default: 0 - use '-1' for random from 0 to 5): ", 0);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 137 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...
169
            $question->setValidator(function($answer) {
170
                $answer = (int)($answer);
171
                if(!is_int($answer) || $answer < -1) {
172
                    throw new \RuntimeException("Please enter an integer value or >= -1");
173
                }
174
175
                return $answer;
176
            });
177
            $input->setArgument('children-categories-number', $helper->ask($input, $output, $question));
178
        }
179
        if($input->getArgument('children-categories-number') == -1)
180
            $input->setArgument('children-categories-number', rand(0, 5));
181
182
        $output->writeln('<info>Number of categories children to create: '.$input->getArgument('children-categories-number')."</info>");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 136 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...
183
        $_argument['children-categories-number'] = $input->getArgument('children-categories-number');
184
185
        // Category name prefix
186
        if(is_null($input->getArgument('category-name-prefix'))) {
187
            $question = new Question("Please enter the category name prefix (default '".self::DEFAULT_CATEGORY_NAME."'): ", self::DEFAULT_CATEGORY_NAME);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 153 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...
188
            $input->setArgument('category-name-prefix', $helper->ask($input, $output, $question));
189
        }
190
        $output->writeln('<info>CATEGORY NAME PREFIX: '.$input->getArgument('category-name-prefix')."</info>");
191
        $_argument['category-name-prefix'] = $input->getArgument('category-name-prefix');
192
193
        return $_argument;
194
    }
195
}
196