ExecutorController::getFixtureExecutorManager()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
rs 10
1
<?php
2
/**
3
 * @link    https://github.com/nnx-framework/doctrine-fixture-module
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace Nnx\DoctrineFixtureModule\Controller;
7
8
use Nnx\DoctrineFixtureModule\Event\ExecutorDispatcherEvent;
9
use Nnx\DoctrineFixtureModule\Executor\ClassListFixtureExecutor;
10
use Nnx\DoctrineFixtureModule\Executor\ExecutorInterface;
11
use Nnx\DoctrineFixtureModule\Executor\FixtureExecutorManagerInterface;
12
use Nnx\DoctrineFixtureModule\Listener\ExecutorDispatcherInterface;
13
use Zend\Mvc\Controller\AbstractConsoleController;
14
use Zend\Console\Request as ConsoleRequest;
15
use Zend\View\Model\ConsoleModel;
16
17
/**
18
 * Class ExecutorController
19
 *
20
 * @package Nnx\DoctrineFixtureModule\Entity
21
 *
22
 */
23
class ExecutorController extends AbstractConsoleController
24
{
25
    /**
26
     * Менеджер для получения Executor'ов
27
     *
28
     * @var FixtureExecutorManagerInterface
29
     */
30
    protected $fixtureExecutorManager;
31
32
    /**
33
     * Разрешенные методы
34
     *
35
     * @var array
36
     */
37
    protected $allowedMethod = [
38
        'import',
39
        'purge'
40
    ];
41
42
    /**
43
     * ExecutorController constructor.
44
     *
45
     * @param FixtureExecutorManagerInterface $fixtureExecutorManager
46
     */
47
    public function __construct(FixtureExecutorManagerInterface $fixtureExecutorManager)
48
    {
49
        $this->setFixtureExecutorManager($fixtureExecutorManager);
50
    }
51
52
    /**
53
     * Запускает фикстуры
54
     *
55
     *
56
     * @throws \Nnx\DoctrineFixtureModule\Event\Exception\RuntimeException
57
     * @throws \Nnx\DoctrineFixtureModule\Controller\Exception\RuntimeException
58
     */
59
    public function executeFixtureAction()
60
    {
61
        $method = $this->getExecutorMethod();
62
63
        $contextData = [];
64
        $objectManagerName = $this->getObjectManagerName();
65
66
        if (null !== $objectManagerName) {
67
            $contextData['objectManagerName'] = $objectManagerName;
68
        }
69
70
        $classList = $this->getFixtureClassList();
71
72
        $creationOptions = [
73
            'classList' => $classList
74
        ];
75
        $executor = $this->getFixtureExecutorManager()->get(ClassListFixtureExecutor::class, $creationOptions);
0 ignored issues
show
Unused Code introduced by
The call to FixtureExecutorManagerInterface::get() has too many arguments starting with $creationOptions.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
76
77
        $this->runFixture($executor, $method, $contextData);
78
79
80
        return [
81
            ConsoleModel::RESULT => 'All fixture completed'
82
        ];
83
    }
84
85
    /**
86
     * Возвращает список фикстур которые необходимо выпонить
87
     *
88
     * @return array
89
     * @throws \Nnx\DoctrineFixtureModule\Controller\Exception\RuntimeException
90
     */
91
    protected function getFixtureClassList()
92
    {
93
        $request = $this->getConsoleRequest();
94
        $classListStr = preg_replace('/ {2,}/', ' ', trim($request->getParam('fixtureClassName', '')));
95
96
        return explode(' ', $classListStr);
97
    }
98
99
    /**
100
     * Возвращает метод для Executor'a
101
     *
102
     * @return string
103
     * @throws \Nnx\DoctrineFixtureModule\Controller\Exception\RuntimeException
104
     */
105
    public function getExecutorMethod()
106
    {
107
        $request = $this->getConsoleRequest();
108
109
        $method = $request->getParam('method', null);
110
        if (null === $method) {
111
            $errMsg = 'Executor method not defined';
112
            throw new Exception\RuntimeException($errMsg);
113
        }
114
        $normalizeMethod = strtolower($method);
115
        if (!in_array($normalizeMethod, $this->allowedMethod, true)) {
116
            $errMsg = sprintf('Invalid executor method %s', $method);
117
            throw new Exception\RuntimeException($errMsg);
118
        }
119
120
        return $normalizeMethod;
121
    }
122
123
    /**
124
     * Возвращает имя ObjectManager'a
125
     *
126
     * @return string|null
127
     * @throws \Nnx\DoctrineFixtureModule\Controller\Exception\RuntimeException
128
     */
129
    protected function getObjectManagerName()
130
    {
131
        $request = $this->getConsoleRequest();
132
133
        return $request->getParam('object-manager', null);
134
    }
135
136
    /**
137
     * Возвращает консольный запрос
138
     *
139
     * @return ConsoleRequest
140
     * @throws \Nnx\DoctrineFixtureModule\Controller\Exception\RuntimeException
141
     */
142
    protected function getConsoleRequest()
143
    {
144
        $request = $this->getRequest();
145
        if (!$request instanceof ConsoleRequest) {
146
            $errMsg = 'Request is not console';
147
            throw new Exception\RuntimeException($errMsg);
148
        }
149
150
        return $request;
151
    }
152
153
    /**
154
     * Запук Executor'a
155
     *
156
     * @throws \Nnx\DoctrineFixtureModule\Controller\Exception\RuntimeException
157
     * @throws \Nnx\DoctrineFixtureModule\Event\Exception\RuntimeException
158
     */
159
    public function runExecutorAction()
160
    {
161
        $executorName = $this->getExecutorName();
162
        $method = $this->getExecutorMethod();
163
164
        $contextData = [];
165
        $objectManagerName = $this->getObjectManagerName();
166
        if (null !== $objectManagerName) {
167
            $contextData['objectManagerName'] = $objectManagerName;
168
        }
169
170
        $executor = $this->getFixtureExecutorManager()->get($executorName);
171
172
        $this->runFixture($executor, $method, $contextData);
173
174
        return [
175
            ConsoleModel::RESULT => 'All fixture completed'
176
        ];
177
    }
178
179
    /**
180
     * Запуск выполнения фикстур
181
     *
182
     * @param ExecutorInterface $executor
183
     * @param                   $method
184
     * @param array             $contextData
185
     */
186
    protected function runFixture(ExecutorInterface $executor, $method, array $contextData = [])
187
    {
188
        $console = $this->getConsole();
189
        $console->writeLine(sprintf('Run fixture executor %s', $executor->getName()));
190
191
        $eventSharedManager = $this->getEventManager()->getSharedManager();
192
        $listener = $eventSharedManager->attach(
193
            ExecutorDispatcherInterface::class,
194
            ExecutorDispatcherEvent::FINISH_FIXTURE_EVENT,
195
            function (ExecutorDispatcherEvent $e) use ($console) {
196
                $console->writeLine(sprintf('Execute fixture: %s', get_class($e->getFixture())));
197
            }
198
        );
199
200
        $console->writeLine("\n");
201
202
        switch ($method) {
203
            case 'import': {
0 ignored issues
show
Coding Style introduced by
CASE statements must be defined using a colon

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
204
                $executor->import($contextData);
205
                break;
206
            }
207
            case 'purge': {
0 ignored issues
show
Coding Style introduced by
CASE statements must be defined using a colon

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
208
                $executor->purge($contextData);
209
                break;
210
            }
211
        }
212
        $eventSharedManager->detach(ExecutorDispatcherInterface::class, $listener);
0 ignored issues
show
Bug introduced by
It seems like $listener defined by $eventSharedManager->att...$e->getFixture()))); }) on line 192 can also be of type array; however, Zend\EventManager\Shared...agerInterface::detach() does only seem to accept object<Zend\Stdlib\CallbackHandler>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
213
    }
214
215
216
    /**
217
     * Вовзращает имя Executor'a
218
     *
219
     * @return string
220
     * @throws \Nnx\DoctrineFixtureModule\Controller\Exception\RuntimeException
221
     */
222
    public function getExecutorName()
223
    {
224
        $request = $this->getConsoleRequest();
225
        $executorName = $request->getParam('executorName', null);
226
227
        if (null === $executorName) {
228
            $errMsg = 'Executor name is not defined';
229
            throw new Exception\RuntimeException($errMsg);
230
        }
231
232
        return $executorName;
233
    }
234
235
236
    /**
237
     * Возвращает менеджер для получения Executor'ов
238
     *
239
     * @return FixtureExecutorManagerInterface
240
     */
241
    public function getFixtureExecutorManager()
242
    {
243
        return $this->fixtureExecutorManager;
244
    }
245
246
    /**
247
     * Устанавливает менеджер для получения Executor'ов
248
     *
249
     * @param FixtureExecutorManagerInterface $fixtureExecutorManager
250
     *
251
     * @return $this
252
     */
253
    public function setFixtureExecutorManager($fixtureExecutorManager)
254
    {
255
        $this->fixtureExecutorManager = $fixtureExecutorManager;
256
257
        return $this;
258
    }
259
}
260