/
WorkflowManager.php
762 lines (660 loc) · 24.6 KB
/
WorkflowManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
<?php
namespace Oro\Bundle\WorkflowBundle\Model;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\EntityManager;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
use Oro\Bundle\WorkflowBundle\Entity\Repository\WorkflowItemRepository;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowItem;
use Oro\Bundle\WorkflowBundle\Event\WorkflowChangesEvent;
use Oro\Bundle\WorkflowBundle\Event\WorkflowEvents;
use Oro\Bundle\WorkflowBundle\Exception\ForbiddenTransitionException;
use Oro\Bundle\WorkflowBundle\Exception\InvalidTransitionException;
use Oro\Bundle\WorkflowBundle\Exception\WorkflowException;
use Oro\Bundle\WorkflowBundle\Exception\WorkflowRecordGroupException;
use Oro\Bundle\WorkflowBundle\Model\Tools\StartedWorkflowsBag;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Handles logic for getting workflow, transitions, workflow items as well as all other related actions
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class WorkflowManager implements LoggerAwareInterface
{
use LoggerAwareTrait;
const MASS_START_BATCH_SIZE = 100;
/** @var DoctrineHelper */
protected $doctrineHelper;
/** @var EventDispatcherInterface */
private $eventDispatcher;
/** @var WorkflowEntityConnector */
private $entityConnector;
/** @var WorkflowRegistry */
private $workflowRegistry;
/** @var WorkflowApplicabilityFilterInterface[] */
private $applicabilityFilters = [];
/** @var StartedWorkflowsBag */
private $startedWorkflowsBag;
public function __construct(
WorkflowRegistry $workflowRegistry,
DoctrineHelper $doctrineHelper,
EventDispatcherInterface $eventDispatcher,
WorkflowEntityConnector $entityConnector,
StartedWorkflowsBag $startedWorkflowsBag
) {
$this->workflowRegistry = $workflowRegistry;
$this->doctrineHelper = $doctrineHelper;
$this->eventDispatcher = $eventDispatcher;
$this->entityConnector = $entityConnector;
$this->startedWorkflowsBag = $startedWorkflowsBag;
}
/**
* @param string|Workflow|WorkflowItem $workflowIdentifier
* @return Workflow
* @throws WorkflowException
*/
public function getWorkflow($workflowIdentifier)
{
if (is_string($workflowIdentifier)) {
return $this->workflowRegistry->getWorkflow($workflowIdentifier);
}
if ($workflowIdentifier instanceof WorkflowItem) {
return $this->workflowRegistry->getWorkflow($workflowIdentifier->getWorkflowName());
}
if ($workflowIdentifier instanceof Workflow) {
return $workflowIdentifier;
}
throw new WorkflowException('Can\'t find workflow by given identifier.');
}
/**
* @param WorkflowItem $workflowItem
* @return Collection|Transition[]
*/
public function getTransitionsByWorkflowItem(WorkflowItem $workflowItem)
{
$workflow = $this->workflowRegistry->getWorkflow($workflowItem->getWorkflowName());
return $workflow->getTransitionsByWorkflowItem($workflowItem);
}
/**
* @param string|Transition $transition
* @param WorkflowItem $workflowItem
* @param Collection|null $errors
* @return bool
*/
public function isTransitionAvailable(WorkflowItem $workflowItem, $transition, Collection $errors = null)
{
$workflow = $this->workflowRegistry->getWorkflow($workflowItem->getWorkflowName());
return $workflow->isTransitionAvailable($workflowItem, $transition, $errors);
}
/**
* @param string|Workflow $workflow
* @param string|Transition $transition
* @param object $entity
* @param array $data
* @param Collection|null $errors
* @return bool
*/
public function isStartTransitionAvailable(
$workflow,
$transition,
$entity,
array $data = [],
Collection $errors = null
) {
//consider to refactor (e.g. remove) type check in favor of string usage only as most cases are.
//Any way - if developer has Workflow instance already it is possible to get decision from it directly as below
$workflow = $workflow instanceof Workflow ? $workflow : $this->workflowRegistry->getWorkflow($workflow);
return $workflow->isStartTransitionAvailable($transition, $entity, $data, $errors);
}
/**
* Perform reset of workflow item data - set $workflowItem and $workflowStep references into null
* and remove workflow item. If active workflow definition has a start step,
* then active workflow will be started automatically.
*
* @param WorkflowItem $workflowItem
* @return WorkflowItem|null workflowItem for workflow definition with a start step, null otherwise
* @throws \Exception
*/
public function resetWorkflowItem(WorkflowItem $workflowItem)
{
$entity = $workflowItem->getEntity();
return $this->inTransaction(
function (EntityManager $em) use ($workflowItem, $entity) {
$currentWorkflowName = $workflowItem->getWorkflowName();
$em->remove($workflowItem);
$em->flush();
$workflow = $this->workflowRegistry->getWorkflow($currentWorkflowName);
if ($workflow->isActive() && $workflow->getStepManager()->hasStartStep()) {
return $this->startWorkflow($currentWorkflowName, $entity);
}
return null;
},
WorkflowItem::class
);
}
/**
* @param string|Workflow $workflow
* @param object $entity
* @param string|Transition|null $transition
* @param array $data
* @param bool $throwGroupException
* @param Collection|null $errors
*
* @return WorkflowItem|null
* @throws WorkflowRecordGroupException
*/
public function startWorkflow(
$workflow,
$entity,
$transition = null,
array $data = [],
$throwGroupException = true,
Collection $errors = null
) {
try {
$workflowItem = $this->doStartWorkflow($workflow, $entity, $transition, $data, [], $errors);
} catch (WorkflowRecordGroupException $exception) {
if ($throwGroupException) {
throw $exception;
}
return null;
}
if ($workflowItem) {
$workflowItem = $this->inTransaction(
function (EntityManager $em) use ($workflowItem) {
$em->persist($workflowItem);
$em->flush();
return $workflowItem;
},
WorkflowItem::class
);
}
return $workflowItem;
}
/**
* @param string|Workflow $workflow
* @param object $entity
* @param string|Transition|null $transition
* @param array $data
* @param array $workflowItems
* @param Collection|null $errors
*
* @return WorkflowItem|null
*
* @throws WorkflowRecordGroupException
*/
protected function doStartWorkflow(
$workflow,
$entity,
$transition = null,
array $data = [],
array $workflowItems = [],
Collection $errors = null
) {
//consider to refactor (e.g. remove) type check in favor of string usage only as most cases are
$workflow = $this->getWorkflow($workflow);
//If transition passed as "null", then check if default "start" transition allowed
if (!$transition) {
$transition = $workflow->getTransitionManager()->getDefaultStartTransition();
if (!$workflow->isStartTransitionAvailable($transition, $entity, $data, $errors)) {
return null;
}
}
$transition = $workflow->getTransitionManager()->getStartTransition($transition);
if (!$this->isStartAllowedForEntity($workflow, $entity)) {
return null;
}
//Collect and merge existing workflow items
$workflowItems = array_merge($workflowItems, $this->getWorkflowItemsByEntity($entity));
if (!$this->isStartAllowedByRecordGroups($entity, $workflow, $workflowItems)) {
$message = sprintf(
'Workflow "%s" can not be started because it belongs to exclusive_record_group ' .
'with already started other workflow for this entity',
$workflow->getName()
);
if ($this->logger) {
$this->logger->error($message, [
'workflow' => $workflow->getName(),
'transition' => ($transition instanceof Transition) ? $transition->getName() : $transition,
'entityClass' => ClassUtils::getClass($entity),
'entityId' => $this->doctrineHelper->getSingleEntityIdentifier($entity),
'data' => $data,
]);
}
throw new WorkflowRecordGroupException($message);
}
$this->unsetStartedWorkflowForEntity($workflow, $entity);
return $workflow->start($entity, $data, $transition, $errors);
}
/**
* Start several workflows
*
* @param array|WorkflowStartArguments[] $startArgumentsList instances of WorkflowStartArguments
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function massStartWorkflow(array $startArgumentsList)
{
$startArgumentsList = array_filter($startArgumentsList, function ($item) {
return $item instanceof WorkflowStartArguments;
});
if (!$startArgumentsList) {
return;
}
$startArgumentsChunks = array_chunk($startArgumentsList, self::MASS_START_BATCH_SIZE);
$em = $this->doctrineHelper->getEntityManagerForClass(WorkflowItem::class);
foreach ($startArgumentsChunks as $key => $chunk) {
$workflowItems = [];
$em->beginTransaction();
try {
/** @var WorkflowStartArguments $startArguments */
foreach ($chunk as $startArguments) {
$entity = $startArguments->getEntity();
$hash = spl_object_hash($entity);
if (!array_key_exists($hash, $workflowItems)) {
$workflowItems[$hash] = [];
}
try {
$workflowItem = $this->doStartWorkflow(
$startArguments->getWorkflowName(),
$entity,
$startArguments->getTransition(),
$startArguments->getData(),
$workflowItems[$hash]
);
} catch (WorkflowRecordGroupException $exception) {
continue;
}
if ($workflowItem) {
$em->persist($workflowItem);
$workflowItems[$hash][] = $workflowItem;
}
}
if ($workflowItems) {
$em->flush();
}
$em->commit();
} catch (\Exception $exception) {
$em->rollback();
if ($this->logger) {
$this->logger->critical('Workflow mass start transition exception', ['exception' => $exception]);
}
} finally {
unset($startArgumentsChunks[$key]);
}
}
}
/**
* Perform workflow item transition.
*
* @param WorkflowItem $workflowItem
* @param string|Transition $transition
* @param Collection|null $errors
* @throws ForbiddenTransitionException
* @throws InvalidTransitionException
* @throws WorkflowException
*/
public function transit(WorkflowItem $workflowItem, $transition, Collection $errors = null)
{
/** @var Workflow $workflow */
$workflow = $this->workflowRegistry->getWorkflow($workflowItem->getWorkflowName(), true);
$this->transitWorkflow($workflow, $workflowItem, $transition, $errors);
}
/**
* @param Workflow $workflow
* @param WorkflowItem $workflowItem
* @param string|Transition $transition
* @param Collection|null $errors
* @param boolean $checkIsAllowed
* @throws ForbiddenTransitionException
* @throws InvalidTransitionException
* @throws WorkflowException
* @throws \Exception
*/
private function transitWorkflow(
Workflow $workflow,
WorkflowItem $workflowItem,
$transition,
Collection $errors = null,
bool $checkIsAllowed = true
): void {
$this->inTransaction(
function (EntityManager $em) use ($workflow, $workflowItem, $transition, $errors, $checkIsAllowed) {
if ($checkIsAllowed) {
$workflow->transit($workflowItem, $transition, $errors);
} else {
$workflow->transitUnconditionally($workflowItem, $transition);
}
$workflowItem->setUpdated(); // transition might not change workflow item
$em->flush();
if ($this->logger) {
$this->logger->info(
'Workflow transition is complete',
[
'workflow' => $workflow,
'workflowItem' => $workflowItem,
'transition' => $transition
]
);
}
},
WorkflowItem::class
);
}
/**
* Tries to transit workflow and checks whether the given transition is allowed.
* Returns true on success - false otherwise.
*
* @param WorkflowItem $workflowItem
* @param string|Transition $transition
* @return bool
* @throws \Exception
*/
public function transitIfAllowed(WorkflowItem $workflowItem, $transition)
{
/** @var Workflow $workflow */
$workflow = $this->workflowRegistry->getWorkflow($workflowItem->getWorkflowName(), true);
if (!$workflow->isTransitionAllowed($workflowItem, $transition)) {
return false;
}
$this->transitWorkflow($workflow, $workflowItem, $transition, null, false);
return true;
}
/**
* Transits a workflow item without checking for preconditions and conditions.
* Returns true on success - false otherwise.
*
* @param WorkflowItem $workflowItem
* @param string|Transition $transition
* @return bool
* @throws \Exception
*/
public function transitUnconditionally(WorkflowItem $workflowItem, $transition): bool
{
/** @var Workflow $workflow */
$workflow = $this->workflowRegistry->getWorkflow($workflowItem->getWorkflowName(), true);
try {
$this->transitWorkflow($workflow, $workflowItem, $transition, null, false);
return true;
} catch (InvalidTransitionException $exception) {
// Transition is not valid, do nothing.
return false;
}
}
/**
* Transit several workflow items in one transaction
*
* Input data format:
* array(
* array(
* 'workflowItem' => <workflow item entity: WorkflowItem>,
* 'transition' => <transition name: string|Transition>
* ),
* ...
* )
*
* @throws \Exception
*/
public function massTransit(array $data)
{
$this->inTransaction(
function (EntityManager $em) use (&$data) {
foreach ($data as $row) {
if (empty($row['workflowItem']) || !$row['workflowItem'] instanceof WorkflowItem
|| empty($row['transition'])
) {
continue;
}
/** @var WorkflowItem $workflowItem */
$workflowItem = $row['workflowItem'];
$workflow = $this->workflowRegistry->getWorkflow($workflowItem->getWorkflowName());
$transition = $row['transition'];
$workflow->transit($workflowItem, $transition);
$workflowItem->setUpdated(); // transition might not change workflow item
}
$em->flush();
},
WorkflowItem::class
);
}
/**
* @param callable $callable
* @param string $entityClass
* @return mixed
* @throws \Exception
*/
private function inTransaction(callable $callable, $entityClass)
{
$em = $this->doctrineHelper->getEntityManagerForClass($entityClass);
$em->beginTransaction();
try {
$result = $callable($em);
$em->commit();
return $result;
} catch (\Exception $exception) {
$em->rollback();
throw $exception;
}
}
/**
* @param object|string $entity
* @return Workflow[]|array
* @throws \InvalidArgumentException
*/
public function getApplicableWorkflows($entity)
{
if (!$this->entityConnector->isApplicableEntity($entity)) {
return [];
}
$workflows = $this->workflowRegistry->getActiveWorkflowsByEntityClass(
$this->doctrineHelper->getEntityClass($entity)
);
if (is_object($entity)) {
$recordContext = new WorkflowRecordContext($entity);
foreach ($this->applicabilityFilters as $applicabilityFilter) {
$workflows = $applicabilityFilter->filter($workflows, $recordContext);
}
}
return $workflows->toArray();
}
/**
* @param object|string $entity
* @return bool
*/
public function hasApplicableWorkflows($entity)
{
return count($this->getApplicableWorkflows($entity)) !== 0;
}
/**
* @param object $entity
* @param string $workflowName
* @return null|WorkflowItem
*/
public function getWorkflowItem($entity, $workflowName)
{
if (!$this->entityConnector->isApplicableEntity($entity)) {
return null;
}
return $this->getWorkflowItemRepository()->findOneByEntityMetadata(
$this->doctrineHelper->getEntityClass($entity),
$this->doctrineHelper->getSingleEntityIdentifier($entity),
$workflowName
);
}
/**
* @param object $entity
* @return bool
*/
public function hasWorkflowItemsByEntity($entity)
{
return count($this->getWorkflowItemsByEntity($entity)) > 0;
}
/**
* @param object $entity
* @return WorkflowItem[]
*/
public function getWorkflowItemsByEntity($entity)
{
if (!$this->entityConnector->isApplicableEntity($entity)) {
return [];
}
return $this->getWorkflowItemRepository()->findAllByEntityMetadata(
$this->doctrineHelper->getEntityClass($entity),
$this->doctrineHelper->getSingleEntityIdentifier($entity)
);
}
/**
* @param $entity
* @return false|WorkflowItem
*/
public function getFirstWorkflowItemByEntity($entity)
{
$items = $this->getWorkflowItemsByEntity($entity);
return \reset($items);
}
/**
* Ensures that workflow is currently active
* @param string $workflowName
* @return bool weather workflow was changed his state
*/
public function activateWorkflow($workflowName)
{
return $this->setWorkflowStatus($workflowName, true);
}
/**
* Ensures that workflow is currently inactive
* @param string $workflowName
* @return bool weather workflow was changed his state
*/
public function deactivateWorkflow($workflowName)
{
$result = $this->setWorkflowStatus($workflowName, false);
if ($result) {
$this->startedWorkflowsBag->removeWorkflow($workflowName);
}
return $result;
}
/**
* @param string $workflowName
* @param bool $isActive
* @return bool weather workflow was changed his state
*/
private function setWorkflowStatus($workflowName, $isActive)
{
$definition = $this->workflowRegistry->getWorkflow($workflowName)->getDefinition();
if ((bool) $isActive !== $definition->isActive()) {
$this->eventDispatcher->dispatch(
new WorkflowChangesEvent($definition),
$isActive ? WorkflowEvents::WORKFLOW_BEFORE_ACTIVATION : WorkflowEvents::WORKFLOW_BEFORE_DEACTIVATION
);
$definition->setActive($isActive);
$this->doctrineHelper->getEntityManager(WorkflowDefinition::class)->flush($definition);
$this->eventDispatcher->dispatch(
new WorkflowChangesEvent($definition),
$isActive ? WorkflowEvents::WORKFLOW_ACTIVATED : WorkflowEvents::WORKFLOW_DEACTIVATED
);
return true;
}
return false;
}
/**
* Checks weather workflow with such name is active in refreshed instance.
* @param string $workflowName
* @return bool
*/
public function isActiveWorkflow($workflowName)
{
return $this->workflowRegistry->getWorkflow($workflowName)->isActive();
}
/**
* @param string $workflowName
*/
public function resetWorkflowData($workflowName)
{
$this->getWorkflowItemRepository()->resetWorkflowData($workflowName);
$this->startedWorkflowsBag->removeWorkflow($workflowName);
}
/**
* @return WorkflowItemRepository
*/
protected function getWorkflowItemRepository()
{
return $this->doctrineHelper->getEntityRepository(WorkflowItem::class);
}
/**
* @param object $entity
* @param Workflow $workflow
* @param array $workflowItems
*
* @return bool
*/
protected function isStartAllowedByRecordGroups($entity, Workflow $workflow, array $workflowItems = [])
{
//Allow to start for new entities
if (null === $this->doctrineHelper->getSingleEntityIdentifier($entity)) {
return true;
}
foreach ($workflowItems as $workflowItem) {
$result = array_intersect(
$workflow->getDefinition()->getExclusiveRecordGroups(),
$workflowItem->getDefinition()->getExclusiveRecordGroups()
);
if ($result) {
return false;
}
}
return true;
}
/**
* Return false if the Workflow already started for the Entity
*
* @param Workflow $workflow
* @param object $entity
*
* @return bool
*/
protected function isStartAllowedForEntity(Workflow $workflow, $entity)
{
$startedWorkflowsBag = $this->startedWorkflowsBag;
$entityId = $this->doctrineHelper->getSingleEntityIdentifier($entity);
$workflowName = $workflow->getName();
if ($entityId && $startedWorkflowsBag->hasWorkflowEntity($workflowName)) {
foreach ($startedWorkflowsBag->getWorkflowEntities($workflowName) as $startedEntity) {
$startedEntityId = $this->doctrineHelper->getSingleEntityIdentifier($startedEntity);
if ($startedEntityId && ($startedEntityId === $entityId)) {
return false;
}
}
}
$startedWorkflowsBag->addWorkflowEntity($workflowName, $entity);
return true;
}
/**
* Unset started workflow for entity
*
* @param Workflow $workflow
* @param object $entity
*/
protected function unsetStartedWorkflowForEntity(Workflow $workflow, $entity)
{
$startedWorkflowsBag = $this->startedWorkflowsBag;
$entityId = $this->doctrineHelper->getSingleEntityIdentifier($entity);
$workflowName = $workflow->getName();
if ($entityId === null || !$startedWorkflowsBag->hasWorkflowEntity($workflowName)) {
return;
}
foreach ($startedWorkflowsBag->getWorkflowEntities($workflowName) as $startedEntity) {
if ($this->doctrineHelper->getSingleEntityIdentifier($startedEntity) === $entityId) {
$startedWorkflowsBag->removeWorkflowEntity($workflowName, $startedEntity);
break;
}
}
}
public function addApplicabilityFilter(WorkflowApplicabilityFilterInterface $applicabilityFilter)
{
$this->applicabilityFilters[] = $applicabilityFilter;
}
}