Completed
Push — develop ( fdd383...7ecf5e )
by Tom
15s
created

DummyCommand::attributeValueExists()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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