GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — dev ( 4095d1...89bae3 )
by Андрей
04:02
created

EntryIdResolver::setModuleOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/**
3
 * @link  https://github.com/old-town/workflow-zf2-toolkit
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace OldTown\Workflow\ZF2\Toolkit\WorkflowRunParams;
7
8
use Zend\EventManager\AbstractListenerAggregate;
9
use Zend\EventManager\EventManagerInterface;
10
use OldTown\Workflow\ZF2\Dispatch\RunParamsHandler\RouteHandler;
11
use OldTown\Workflow\ZF2\Dispatch\RunParamsHandler\RouteHandler\ResolveEntryIdEventInterface;
12
use OldTown\Workflow\ZF2\Toolkit\DoctrineWorkflowStory\DoctrineWorkflowStoryService;
13
use OldTown\Workflow\ZF2\Toolkit\Options\ModuleOptions;
14
use OldTown\Workflow\ZF2\ServiceEngine\Workflow as WorkflowService;
15
use OldTown\Workflow\ZF2\Toolkit\DoctrineWorkflowStory\DoctrineWorkflowStory;
16
use Zend\Serializer\Adapter\AdapterInterface as Serializer;
17
use OldTown\Workflow\ZF2\Toolkit\EntityRepository\DoctrineWorkflowStory\ExtEntryRepository;
18
use Zend\Mvc\MvcEvent;
19
20
/**
21
 * Class EntryIdResolver
22
 *
23
 * @package OldTown\Workflow\ZF2\Toolkit\WorkflowRunParams
24
 */
25
class EntryIdResolver extends AbstractListenerAggregate
26
{
27
    /**
28
     * Имя параметра в конфиги модуля, по которому можно получить имя менеджера wf
29
     *
30
     * @var string
31
     */
32
    const WORKFLOW_MANAGER_NAME = 'workflowManagerName';
33
34
    /**
35
     * Имя параметра в конфиге модуля, по которому можно получить имя wf
36
     *
37
     * @var string
38
     */
39
    const WORKFLOW_NAME = 'workflowName';
40
41
    /**
42
     * Имя параметра в конфиге модуля, по которому можно конфиг описывающий какие классы и какие имена параметров роуетера
43
     * используется, для получения entryId
44
     *
45
     * @var string
46
     */
47
    const MAP = 'map';
48
49
    /**
50
     * Имя параметра в карте(@see const MAP), по которому можно получить класс сущности
51
     *
52
     * @var string
53
     */
54
    const ENTITY_CLASS_NAME = 'entityClassName';
55
56
    /**
57
     * Имя параметра в карте(@see const MAP), по которому можно получить имя параметра роутера содержащего id сущности
58
     *
59
     * @var string
60
     */
61
    const ROUTER_PARAM_NAME = 'routerParamName';
62
63
    /**
64
     * Сервис реализующий функционал, для привязки процессов wf и информации о объектаъ
65
     *
66
     * @var DoctrineWorkflowStoryService
67
     */
68
    protected $doctrineWorkflowStoryService;
69
70
    /**
71
     * Настройки модуля
72
     *
73
     * @var ModuleOptions
74
     */
75
    protected $moduleOptions;
76
77
    /**
78
     * Индекс для маппинга
79
     *
80
     * @var null|array
81
     */
82
    protected $indexMetadata;
83
84
    /**
85
     * Сервис для работы с wf
86
     *
87
     * @var WorkflowService
88
     */
89
    protected $workflowService;
90
91
    /**
92
     * @var MvcEvent
93
     */
94
    protected $mvcEvent;
95
96
    /**
97
     * @var Serializer
98
     */
99
    protected $serializer;
100
101
    /**
102
     * EntryIdResolver constructor.
103
     *
104
     * @param array $options
105
     */
106
    public function __construct(array $options = [])
107
    {
108
        $initOptions = [
109
            array_key_exists('doctrineWorkflowStoryService', $options) ? $options['doctrineWorkflowStoryService'] : null,
110
            array_key_exists('moduleOptions', $options) ? $options['moduleOptions'] : null,
111
            array_key_exists('workflowService', $options) ? $options['workflowService'] : null,
112
            array_key_exists('mvcEvent', $options) ? $options['mvcEvent'] : null,
113
            array_key_exists('serializer', $options) ? $options['serializer'] : null,
114
        ];
115
        call_user_func_array([$this, 'init'], $initOptions);
116
    }
117
118
    /**
119
     * @param DoctrineWorkflowStoryService $doctrineWorkflowStoryService
120
     * @param ModuleOptions                $moduleOptions
121
     * @param WorkflowService              $workflowService
122
     * @param MvcEvent                     $mvcEvent
123
     * @param Serializer                   $serializer
124
     */
125
    protected function init(
126
        DoctrineWorkflowStoryService $doctrineWorkflowStoryService,
127
        ModuleOptions $moduleOptions,
128
        WorkflowService $workflowService,
129
        MvcEvent $mvcEvent,
130
        Serializer $serializer
131
    ) {
132
        $this->setDoctrineWorkflowStoryService($doctrineWorkflowStoryService);
133
        $this->setModuleOptions($moduleOptions);
134
        $this->setWorkflowService($workflowService);
135
        $this->setMvcEvent($mvcEvent);
136
        $this->setSerializer($serializer);
137
    }
138
139
    /**
140
     * @param EventManagerInterface $events
141
     */
142
    public function attach(EventManagerInterface $events)
143
    {
144
        $events->getSharedManager()->attach(RouteHandler::class, ResolveEntryIdEventInterface::RESOLVE_ENTRY_ID_EVENT, [$this, 'onResolveEntryId'], 80);
145
    }
146
147
    /**
148
     * Обработчик содержащий логику получения entryId
149
     *
150
     * @param ResolveEntryIdEventInterface $resolveEntryIdEvent
151
     *
152
     * @return null|void
153
     * @throws Exception\InvalidWorkflowEntryToObjectMetadataException
154
     * @throws \OldTown\Workflow\ZF2\ServiceEngine\Exception\InvalidManagerNameException
155
     * @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
156
     * @throws \OldTown\Workflow\ZF2\ServiceEngine\Exception\InvalidWorkflowManagerException
157
     * @throws \OldTown\Workflow\Spi\Doctrine\Exception\DoctrineRuntimeException
158
     * @throws \Doctrine\ORM\Mapping\MappingException
159
     * @throws \Zend\Serializer\Exception\ExceptionInterface
160
     * @throws \Doctrine\ORM\NonUniqueResultException
161
     * @throws \Doctrine\ORM\NoResultException
162
     */
163
    public function onResolveEntryId(ResolveEntryIdEventInterface $resolveEntryIdEvent)
164
    {
165
        $index = $this->getIndexMetadata();
166
167
        $managerName = $resolveEntryIdEvent->getManagerName();
168
        if (!array_key_exists($managerName, $index)) {
169
            return null;
170
        }
171
172
        $workflowName = $resolveEntryIdEvent->getWorkflowName();
173
        if (!array_key_exists($workflowName, $index[$managerName]) || !is_array($index[$managerName][$workflowName])) {
174
            return null;
175
        }
176
177
        $workflowManager = $this->getWorkflowService()->getWorkflowManager($managerName);
178
179
        $store = $workflowManager->getConfiguration()->getWorkflowStore();
180
181
        if (!$store instanceof DoctrineWorkflowStory) {
182
            return null;
183
        }
184
        $em = $store->getEntityManager();
185
186
        $objectHash = [];
187
        $routeMatch = $this->getMvcEvent()->getRouteMatch();
188
189
        $serializer = $this->getSerializer();
190
191
        foreach ($index[$managerName][$workflowName] as $entityClassName => $routerParamName) {
192
            $entityId = $routeMatch->getParam($routerParamName, null);
193
            if (null === $entityId) {
194
                return null;
195
            }
196
197
            $identifierFieldName = $em->getClassMetadata($entityClassName)->getSingleIdentifierFieldName();
198
            $id = [
199
                $identifierFieldName => (string)$entityId
200
            ];
201
202
            $serializedId = $serializer->serialize($id);
203
204
            $hash = $entityClassName . '_' . $serializedId;
205
            $base64Hash = base64_encode($hash);
206
207
            $objectHash[$base64Hash] = $base64Hash;
208
        }
209
210
        $extEntryClassName = $this->getModuleOptions()->getEntityClassName('DoctrineWorkflowStory\ExtEntry');
211
        /** @var ExtEntryRepository $extEntryRepository */
212
        $extEntryRepository = $em->getRepository($extEntryClassName);
0 ignored issues
show
Bug introduced by
It seems like $extEntryClassName defined by $this->getModuleOptions(...rkflowStory\\ExtEntry') on line 210 can also be of type array; however, Doctrine\Common\Persiste...anager::getRepository() does only seem to accept string, 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
        $entry = $extEntryRepository->findEntryByObjectInfo($workflowName, $objectHash);
215
        if (null === $entry) {
216
            return null;
217
        }
218
219
        return $entry->getId();
220
    }
221
222
    /**
223
     * @return array|null
224
     *
225
     * @throws Exception\InvalidWorkflowEntryToObjectMetadataException
226
     */
227
    public function getIndexMetadata()
228
    {
229
        if (null !== $this->indexMetadata) {
230
            return $this->indexMetadata;
231
        }
232
        $metadata = $this->getModuleOptions()->getWorkflowEntryToObjectMetadata();
233
234
        $index = [];
235
        foreach ($metadata as $metadataItem) {
236 View Code Duplication
            if (!array_key_exists(static::WORKFLOW_MANAGER_NAME, $metadataItem)) {
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...
237
                $errMsg = sprintf('there is no option %s', static::WORKFLOW_MANAGER_NAME);
238
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
239
            }
240
            $workflowManagerName = $metadataItem[static::WORKFLOW_MANAGER_NAME];
241
242 View Code Duplication
            if (!array_key_exists(static::WORKFLOW_NAME, $metadataItem)) {
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...
243
                $errMsg = sprintf('there is no option %s', static::WORKFLOW_NAME);
244
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
245
            }
246
            $workflowName = $metadataItem[static::WORKFLOW_NAME];
247
248 View Code Duplication
            if (!array_key_exists(static::MAP, $metadataItem)) {
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...
249
                $errMsg = sprintf('there is no option %s', static::MAP);
250
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
251
            }
252 View Code Duplication
            if (!is_array($metadataItem[static::MAP])) {
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...
253
                $errMsg = sprintf('option %s is not array', static::MAP);
254
                throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
255
            }
256
            $map = $metadataItem[static::MAP];
257
258
            if (!array_key_exists($workflowManagerName, $index)) {
259
                $index[$workflowManagerName] = [];
260
            }
261
            if (!array_key_exists($workflowName, $index[$workflowManagerName])) {
262
                $index[$workflowManagerName][$workflowName] = [];
263
            }
264
265
            foreach ($map as $mapItem) {
266 View Code Duplication
                if (!array_key_exists(static::ENTITY_CLASS_NAME, $mapItem)) {
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...
267
                    $errMsg = sprintf('there is no option %s', static::ENTITY_CLASS_NAME);
268
                    throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
269
                }
270
                $entityClassName = $mapItem[static::ENTITY_CLASS_NAME];
271
272
                if (array_key_exists($entityClassName, $index[$workflowManagerName][$workflowName])) {
273
                    $errMsg = sprintf('Metadata for entities already exist %s', $mapItem[static::ENTITY_CLASS_NAME]);
274
                    throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
275
                }
276
277 View Code Duplication
                if (!array_key_exists(static::ROUTER_PARAM_NAME, $mapItem)) {
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...
278
                    $errMsg = sprintf('there is no option %s', static::ROUTER_PARAM_NAME);
279
                    throw new Exception\InvalidWorkflowEntryToObjectMetadataException($errMsg);
280
                }
281
                $routerParamName = $mapItem[static::ROUTER_PARAM_NAME];
282
283
                $index[$workflowManagerName][$workflowName][$entityClassName] = $routerParamName;
284
            }
285
        }
286
        $this->indexMetadata = $index;
287
288
        return $this->indexMetadata;
289
    }
290
291
    /**
292
     * @param array|null $indexMetadata
293
     *
294
     * @return $this
295
     */
296
    public function setIndexMetadata(array $indexMetadata = null)
297
    {
298
        $this->indexMetadata = $indexMetadata;
299
300
        return $this;
301
    }
302
303
304
    /**
305
     * Сервис реализующий функционал, для привязки процессов wf и информации о объектаъ
306
     *
307
     * @return DoctrineWorkflowStoryService
308
     */
309
    public function getDoctrineWorkflowStoryService()
310
    {
311
        return $this->doctrineWorkflowStoryService;
312
    }
313
314
    /**
315
     * Устанавливает сервис реализующий функционал, для привязки процессов wf и информации о объектаъ
316
     *
317
     * @param DoctrineWorkflowStoryService $doctrineWorkflowStoryService
318
     *
319
     * @return $this
320
     */
321
    public function setDoctrineWorkflowStoryService(DoctrineWorkflowStoryService $doctrineWorkflowStoryService)
322
    {
323
        $this->doctrineWorkflowStoryService = $doctrineWorkflowStoryService;
324
325
        return $this;
326
    }
327
328
    /**
329
     * Настройки модуля
330
     *
331
     * @return ModuleOptions
332
     */
333
    public function getModuleOptions()
334
    {
335
        return $this->moduleOptions;
336
    }
337
338
    /**
339
     * Устанавливает настройки модуля
340
     *
341
     * @param ModuleOptions $moduleOptions
342
     *
343
     * @return $this
344
     */
345
    public function setModuleOptions(ModuleOptions $moduleOptions)
346
    {
347
        $this->moduleOptions = $moduleOptions;
348
349
        return $this;
350
    }
351
352
    /**
353
     * @return WorkflowService
354
     */
355
    public function getWorkflowService()
356
    {
357
        return $this->workflowService;
358
    }
359
360
    /**
361
     * @param WorkflowService $workflowService
362
     *
363
     * @return $this
364
     */
365
    public function setWorkflowService(WorkflowService $workflowService)
366
    {
367
        $this->workflowService = $workflowService;
368
369
        return $this;
370
    }
371
372
    /**
373
     * @return MvcEvent
374
     */
375
    public function getMvcEvent()
376
    {
377
        return $this->mvcEvent;
378
    }
379
380
    /**
381
     * @param MvcEvent $mvcEvent
382
     *
383
     * @return $this
384
     */
385
    public function setMvcEvent(MvcEvent $mvcEvent)
386
    {
387
        $this->mvcEvent = $mvcEvent;
388
389
        return $this;
390
    }
391
392
    /**
393
     * @return Serializer
394
     */
395
    public function getSerializer()
396
    {
397
        return $this->serializer;
398
    }
399
400
    /**
401
     * @param Serializer $serializer
402
     *
403
     * @return $this
404
     */
405
    public function setSerializer(Serializer $serializer)
406
    {
407
        $this->serializer = $serializer;
408
409
        return $this;
410
    }
411
}
412