Completed
Push — develop ( 5c5b81...f452b8 )
by Tom
07:08
created

AbstractIndexerCommand::writeFailedResult()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 12
c 0
b 0
f 0
nc 1
nop 5
dl 0
loc 16
rs 9.4285
1
<?php
2
3
namespace N98\Magento\Command\Indexer;
4
5
use Exception;
6
use Mage;
7
use Mage_Index_Model_Indexer;
8
use Mage_Index_Model_Process;
9
use N98\Magento\Command\AbstractMagentoCommand;
10
use N98\Util\DateTime as DateTimeUtils;
11
use Symfony\Component\Console\Output\OutputInterface;
12
13
/**
14
 * Class AbstractIndexerCommand
15
 *
16
 * @package N98\Magento\Command\Indexer
17
 */
18
class AbstractIndexerCommand extends AbstractMagentoCommand
19
{
20
    /**
21
     * @return Mage_Index_Model_Indexer
22
     */
23
    protected function getIndexerModel()
24
    {
25
        /* @var $indexer Mage_Index_Model_Indexer */
26
        $indexer = Mage::getModel('index/indexer');
27
        if (!$indexer instanceof Mage_Index_Model_Indexer) {
28
            throw new \UnexpectedValueException('Failure getting indexer model');
29
        }
30
31
        return $indexer;
32
    }
33
34
    /**
35
     * @return Mage_Index_Model_Indexer
36
     * @deprecated since 1.97.28
37
     */
38
    protected function _getIndexerModel()
39
    {
40
        trigger_error(__METHOD__ . ' moved, use ->getIndexerModel() instead', E_USER_DEPRECATED);
41
        return $this->getIndexerModel();
42
    }
43
44
    /**
45
     * @return array
46
     */
47
    protected function getIndexerList()
48
    {
49
        $list = array();
50
        $indexCollection = $this->getIndexerModel()->getProcessesCollection();
51
        foreach ($indexCollection as $indexer) {
52
            $lastReadbleRuntime = $this->getRuntime($indexer);
53
            $runtimeInSeconds = $this->getRuntimeInSeconds($indexer);
54
            $list[] = array(
55
                'code'            => $indexer->getIndexerCode(),
56
                'status'          => $indexer->getStatus(),
57
                'last_runtime'    => $lastReadbleRuntime,
58
                'runtime_seconds' => $runtimeInSeconds,
59
            );
60
        }
61
62
        return $list;
63
    }
64
65
    /**
66
     * Returns a readable runtime
67
     *
68
     * @param Mage_Index_Model_Process $indexer
69
     * @return string
70
     */
71
    protected function getRuntime(Mage_Index_Model_Process $indexer)
72
    {
73
        $dateTimeUtils = new DateTimeUtils();
74
        $startTime = new \DateTime($indexer->getStartedAt());
75
        $endTime = new \DateTime($indexer->getEndedAt());
76
        if ($startTime > $endTime) {
77
            return 'index not finished';
78
        }
79
        $lastRuntime = $dateTimeUtils->getDifferenceAsString($startTime, $endTime);
80
        return $lastRuntime;
81
    }
82
83
    /**
84
     * Disable observer which try to create adminhtml session on CLI
85
     */
86
    protected function disableObservers()
87
    {
88
        $node = Mage::app()->getConfig()->getNode('adminhtml/events/core_locale_set_locale/observers/bind_locale');
89
        if ($node) {
90
            $node->appendChild(new \Varien_Simplexml_Element('<type>disabled</type>'));
91
        }
92
    }
93
94
    /**
95
     * Returns the runtime in total seconds
96
     *
97
     * @param Mage_Index_Model_Process $indexer
98
     * @return int
99
     */
100
    protected function getRuntimeInSeconds(Mage_Index_Model_Process $indexer)
101
    {
102
        $startTimestamp = strtotime($indexer->getStartedAt());
103
        $endTimestamp = strtotime($indexer->getEndedAt());
104
105
        return $endTimestamp - $startTimestamp;
106
    }
107
108
    /**
109
     * @param OutputInterface $output
110
     * @param Mage_Index_Model_Process $process
111
     */
112
    protected function writeEstimatedEnd(OutputInterface $output, Mage_Index_Model_Process $process)
113
    {
114
        $runtimeInSeconds = $this->getRuntimeInSeconds($process);
115
116
        /**
117
         * Try to estimate runtime. If index was aborted or never created we have a timestamp < 0
118
         */
119
        if ($runtimeInSeconds <= 0) {
120
            return;
121
        }
122
123
        $estimatedEnd = new \DateTime('now', new \DateTimeZone('UTC'));
124
        $estimatedEnd->add(new \DateInterval('PT' . $runtimeInSeconds . 'S'));
125
        $output->writeln(
126
            sprintf('<info>Estimated end: <comment>%s</comment></info>', $estimatedEnd->format('Y-m-d H:i:s T'))
127
        );
128
    }
129
130
    /**
131
     * @param OutputInterface $output
132
     * @param Mage_Index_Model_Process $process
133
     * @param \DateTime $startTime
134
     * @param \DateTime $endTime
135
     */
136
    protected function writeSuccessResult(
137
        OutputInterface $output, Mage_Index_Model_Process $process, \DateTime $startTime, \DateTime $endTime
138
    ) {
139
        $output->writeln(
140
            sprintf(
141
                '<info>Successfully reindexed <comment>%s</comment> (Runtime: <comment>%s</comment>)</info>',
142
                $process->getIndexerCode(),
143
                DateTimeUtils::difference($startTime, $endTime)
144
            )
145
        );
146
    }
147
148
    /**
149
     * @param OutputInterface $output
150
     * @param Mage_Index_Model_Process $process
151
     * @param \DateTime $startTime
152
     * @param \DateTime $endTime
153
     * @param string $errorMessage
154
     */
155
    protected function writeFailedResult(
156
        OutputInterface $output,
157
        Mage_Index_Model_Process $process,
158
        \DateTime $startTime,
159
        \DateTime $endTime,
160
        $errorMessage
161
    ) {
162
        $output->writeln(
163
            sprintf(
164
                '<error>Reindex finished with error message "%s". %s</error> (Runtime: <comment>%s</comment>)</error>',
165
                $errorMessage,
166
                $process->getIndexerCode(),
167
                DateTimeUtils::difference($startTime, $endTime)
168
            )
169
        );
170
    }
171
172
    /**
173
     * @param OutputInterface $output
174
     * @param array $processes
175
     * @return bool
176
     */
177
    protected function executeProcesses(OutputInterface $output, array $processes)
178
    {
179
        $isSuccessful = true;
180
181
        try {
182
            \Mage::dispatchEvent('shell_reindex_init_process');
183
            foreach ($processes as $process) {
184
                if (!$this->executeProcess($output, $process)) {
185
                    $isSuccessful = false;
186
                }
187
            }
188
            \Mage::dispatchEvent('shell_reindex_finalize_process');
189
        } catch (Exception $e) {
190
            $isSuccessful = false;
191
            \Mage::dispatchEvent('shell_reindex_finalize_process');
192
        }
193
194
        return $isSuccessful;
195
    }
196
197
    /**
198
     * @param OutputInterface $output
199
     * @param Mage_Index_Model_Process $process
200
     * @return bool
201
     */
202
    private function executeProcess(OutputInterface $output, Mage_Index_Model_Process $process)
203
    {
204
        $output->writeln(
205
            sprintf('<info>Started reindex of: <comment>%s</comment></info>', $process->getIndexerCode())
206
        );
207
        $this->writeEstimatedEnd($output, $process);
208
209
        $startTime = new \DateTime('now');
210
211
        $isSuccessful = true;
212
        $errorMessage = '';
213
214
        try {
215
            $process->reindexEverything();
216
            \Mage::dispatchEvent($process->getIndexerCode() . '_shell_reindex_after');
217
        } catch (Exception $e) {
218
            $errorMessage = $e->getMessage();
219
            $isSuccessful = false;
220
        }
221
222
        $endTime = new \DateTime('now');
223
224
        if ($isSuccessful) {
225
            $this->writeSuccessResult($output, $process, $startTime, $endTime);
226
        } else {
227
            $this->writeFailedResult($output, $process, $startTime, $endTime, $errorMessage);
228
        }
229
230
        return $isSuccessful;
231
    }
232
}
233