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

DummyCommand::askForArguments()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 55
Code Lines 36

Duplication

Lines 13
Ratio 23.64 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 13
loc 55
rs 7.8235
cc 7
eloc 36
nc 8
nop 2

How to fix   Long Method   

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\Eav\Attribute\Create;
4
5
use Mage;
6
use Mage_Eav_Model_Entity_Attribute;
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
    private $supportedLocales = array(
16
        'en_US', 'en_GB',
17
    );
18
19
    protected function configure()
20
    {
21
        $help = <<<HELP
22
Supported Locales:
23
24
- en_US
25
- en_GB
26
HELP;
27
        $this
28
            ->setName('eav:attribute:create-dummy-values')->addArgument('locale', InputArgument::OPTIONAL, 'Locale')
29
            ->addArgument('attribute-id', InputArgument::OPTIONAL, 'Attribute ID to add values')
30
            ->addArgument('values-type', InputArgument::OPTIONAL, 'Types of Values to create (default int)')
31
            ->addArgument('values-number', InputArgument::OPTIONAL, 'Number of Values to create (default 1)')
32
            ->setDescription('Create a dummy values for dropdown attributes')->setHelp($help)
33
        ;
34
    }
35
36
    /**
37
     * @param InputInterface  $input
38
     * @param OutputInterface $output
39
     *
40
     * @return int|void
41
     */
42
    protected function execute(InputInterface $input, OutputInterface $output)
43
    {
44
        $this->detectMagento($output, true);
45
        if (!$this->initMagento()) {
46
            return;
47
        }
48
49
        $output->writeln(
50
            "<warning>This only create sample attribute values, do not use on production environment</warning>"
51
        );
52
53
        // Ask for Arguments
54
        $argument = $this->askForArguments($input, $output);
55
        if (!in_array($input->getArgument('locale'), $this->supportedLocales)) {
56
            $output->writeln(
57
                sprintf(
58
                    "<warning>Locale '%s' not supported, switch to default locale 'us_US'.</warning>",
59
                    $input->getArgument('locale')
60
                )
61
            );
62
            $argument['locale'] = "en_US";
63
        } else {
64
            $argument['locale'] = $input->getArgument('locale');
65
        }
66
67
        /** @var $attribute Mage_Eav_Model_Entity_Attribute */
68
        $attribute = Mage::getModel('eav/entity_attribute')->load($argument['attribute-id']);
69
        $dummyValues = new DummyValues();
70
        for ($i = 0; $i < $argument['values-number']; $i++) {
71
            $value = $dummyValues->createValue($argument['values-type'], $argument['locale']);
72
            if (!$this->attributeValueExists($attribute, $value)) {
73
                try {
74
                    $attribute->setData('option', array('value' => array('option' => array($value, $value))));
75
                    $attribute->save();
76
                } catch (\Exception $e) {
77
                    $output->writeln("<error>" . $e->getMessage() . "</error>");
78
                }
79
                $output->writeln("<comment>ATTRIBUTE VALUE: '" . $value . "' ADDED!</comment>\r");
80
            }
81
        }
82
    }
83
84
    /**
85
     * Ask for command arguments
86
     *
87
     * @param InputInterface  $input
88
     * @param OutputInterface $output
89
     *
90
     * @return array
91
     */
92
    private function askForArguments(InputInterface $input, OutputInterface $output)
93
    {
94
        $helper = $this->getHelper('question');
95
        $argument = array();
96
97
        // Attribute ID
98
        if (is_null($input->getArgument('attribute-id'))) {
99
            $attribute_code = Mage::getModel('eav/entity_attribute')
100
                ->getCollection()->addFieldToSelect('*')
101
                ->addFieldToFilter('entity_type_id', array('eq' => 4))
102
                ->addFieldToFilter('backend_type', array('in' => array('int')))
103
                ->setOrder('attribute_id', 'ASC')
104
            ;
105
            $attribute_codes = array();
106
107
            foreach ($attribute_code as $item) {
108
                $attribute_codes[$item['attribute_id']] = $item['attribute_id'] . "|" . $item['attribute_code'];
109
            }
110
111
            $question = new ChoiceQuestion('Please select Attribute ID', $attribute_codes);
112
            $question->setErrorMessage('Attribute ID "%s" is invalid.');
113
            $response = explode("|", $helper->ask($input, $output, $question));
114
            $input->setArgument('attribute-id', $response[0]);
115
        }
116
        $output->writeln('<info>Attribute code selected: ' . $input->getArgument('attribute-id') . "</info>");
117
        $argument['attribute-id'] = (int) $input->getArgument('attribute-id');
118
119
        // Type of Values
120
        if (is_null($input->getArgument('values-type'))) {
121
            $valueTypes = DummyValues::getValueTypeList();
122
            $question = new ChoiceQuestion('Please select Attribute Value Type', $valueTypes, 'int');
123
            $question->setErrorMessage('Attribute Value Type "%s" is invalid.');
124
            $input->setArgument('values-type', $helper->ask($input, $output, $question));
125
        }
126
        $output->writeln('<info>Attribute Value Type selected: ' . $input->getArgument('values-type') . "</info>");
127
        $argument['values-type'] = $input->getArgument('values-type');
128
129
        // Number of Values
130 View Code Duplication
        if (is_null($input->getArgument('values-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...
131
            $question = new Question("Please enter the number of values to create (default 1): ", 1);
132
            $question->setValidator(function ($answer) {
133
                $answer = (int) ($answer);
134
                if (!is_int($answer) || $answer <= 0) {
135
                    throw new \RuntimeException('Please enter an integer value or > 0');
136
                }
137
138
                return $answer;
139
            });
140
            $input->setArgument('values-number', $helper->ask($input, $output, $question));
141
        }
142
        $output->writeln('<info>Number of values to create: ' . $input->getArgument('values-number') . "</info>");
143
        $argument['values-number'] = $input->getArgument('values-number');
144
145
        return $argument;
146
    }
147
148
    /**
149
     * Check if an option exist
150
     *
151
     * @param Mage_Eav_Model_Entity_Attribute $attribute
152
     * @param string                          $arg_value
153
     *
154
     * @return bool
155
     */
156
    private function attributeValueExists(Mage_Eav_Model_Entity_Attribute $attribute, $arg_value)
157
    {
158
        $options = Mage::getModel('eav/entity_attribute_source_table');
159
        $options->setAttribute($attribute);
160
        $options = $options->getAllOptions(false);
161
162
        foreach ($options as $option) {
163
            if ($option['label'] === $arg_value) {
164
                return true;
165
            }
166
        }
167
168
        return false;
169
    }
170
}
171