Git Repository Public Repository

namibia

URLs

Copy to Clipboard
 
1074a2d61ec9d93a0ac7e0181875a2202b1225c4
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
<?php
namespace Workspace;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;



/**
 * Abstract workflow to provide global functionality to all workspace workflows.
 * @author andre.fourie
 */
abstract class Workflow implements ServiceLocatorAwareInterface
{

	/**
	 * @var string
	 */
	protected $namespace;
	/**
	 * @var string
	 */
	protected $parentFeature;
	/**
	 * @var string
	 */
	protected $rootEntity;
	/**
	 * @var string
	 */
	protected $rootIdField;
	/**
	 * @var string
	 */
	protected $initState;
	/**
	 * @var string
	 */
	protected $initTrigger;
	/**
	 * @var string
	 */
	protected $primaryEntity;
	/**
	 * @var object
	 */
	protected $jobRecord;
	/**
	 * @var array
	 */
	protected $entityMap;
	/**
	 * @var array
	 */
	protected $linkMap;
	/**
	 * @var array
	 */
	protected $listen;
	/**
	 * @var array
	 */
	protected $reclaim;
	/**
	 * @var array
	 */
	protected $stateLabel = array();
	/**
	 * @var array
	 */
	protected $stateMap;

	/**
	 * @var ServiceLocatorInterface
	 */
	protected $services;


	/**
	 * Setup some essentials.
	 */
	public function __construct()
	{
		if ($this->initTrigger && $this->initState)
		{
			\Utility\Event::listen($this->initTrigger, $this, 'initEvent');
		}
		$this->services = \Utility\Registry::getServiceManager();
	}

	/**
	 * Event fired for initTrigger.
	 * @param string $eventName
	 * @param object $data
	 */
	public function initEvent($eventName, $data)
	{
		$this->jobRecord = $data;
		$this->em->merge($this->jobRecord);
		$this->changeState($this->initState);
	}

	/**
	 * @see \Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator()
	 */
	public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
	{
		$this->services = $serviceLocator;
	}

	/**
	 * @see \Zend\ServiceManager\ServiceLocatorAwareInterface::getServiceLocator()
	 */
	public function getServiceLocator()
	{
		return $this->services;
	}

	/**
	 * Retrieve Doctrine Entity Manager.
	 * @return \Doctrine\ORM\EntityManager
	 */
	public function getEntityManager()
	{
		$this->em = $this->services->get('doctrine.entitymanager.orm_default');
		return $this->em;
	}

	/**
	 * List all available workflow states.
	 * @return array
	 */
	public function listStates()
	{
		return array_keys($this->stateMap);
	}

	/**
	 * List available global tasks.
	 * @param string $state
	 * @return array
	 */
	public function listStateTasks($state = 'Global')
	{
		if (!isset($this->stateMap[$state]))
		{
			return 'No such workflow state.';
		}
		return $this->filterTasks(
				isset($this->stateMap[$state]['Actions'])
					? $this->stateMap[$state]['Actions']
					: array(),
				isset($this->stateMap[$state]['Routes'])
					? $this->stateMap[$state]['Routes']
					: array()
		);
	}

	/**
	 * Filter state specific tasks according to specified restrictions.
	 * @param array $tasks
	 * @param array $routes
	 * @return array
	 */
	protected function filterTasks(array $tasks, array $routes)
	{
		#-> Shortcut.
		if (empty($tasks))
		{
			return $tasks;
		}

		#-> Retrieve available tasks.
		$result   = array();
		$filtered = array();
		foreach ($tasks as $task => $meta)
		{
			if (isset($meta['ApplicationRestriction']))
			{
				is_array($meta['ApplicationRestriction'])
					|| $meta['ApplicationRestriction'] = array($meta['ApplicationRestriction']);
				if (in_array(APPLICATION, $meta['ApplicationRestriction']))
				{
					$filtered[$task] = true;
				}
			}
			else
			{
				$filtered[$task] = true;
			}
		}
		$result['Actions'] = array_keys($filtered);

		#-> Retrieve available routes.
		$filtered = array(
				'Direct'   => array(),
				'Contract' => array()

		);
		foreach ($routes as $task => $meta)
		{
			isset($meta['ContractRequired'])
				? $filtered['Contract'][$task] = true
				: $filtered['Direct'][$task] = true;
		}
		$result['Routes']['Direct']   = array_keys($filtered['Direct']);
		$result['Routes']['Contract'] = array_keys($filtered['Contract']);

		#-> Done.
		return $result;
	}


	/**
	 * Validate unique value for a specified field.
	 * @param \Workspace\Utility\ServiceInputParams $contract
	 * @return multitype:string unknown NULL
	 */
	public function fieldIsUnique(\Workspace\Utility\ServiceInputParams $contract)
	{
		if (!isset($this->entityMap[$contract->Group]))
		{
			return $contract->error(
					'Invalid `Group` specified.',
					'System Error.'
			);
		}
		/*$entityName = $this->entityMap[$contract->Group];
		$entry = $this->getEntityManager()
			->getRepository($entityName)
			->findOneBy(array($contract->Field => $contract->Value));
		return is_null($entry)
			? $contract->success()
			: $contract->error('Value already used.', 'Value already used.');*/
		$entityName = $this->entityMap[$contract->Group];
		$where 	= array();
		$params = array();
		$fields = is_array($contract->Field)
			? $contract->Field
			: array($contract->Field);
		$values = is_array($contract->Value)
			? $contract->Value
			: array($contract->Value);
		if ($entityName::ARCHIVE)
		{
			$where[] = 'c.archived = :archived';
			$params['archived'] = 0;
		}
		for ($i = 0; $i < count($fields); $i++)
		{
			if (false === strpos($fields[$i], ':'))
			{
				$where[] = 'LOWER(c.' . $fields[$i] . ') = :' . $fields[$i];
				$params[$fields[$i]] = strtolower($values[$i]);
			}
			else
			{
				list($function, $fieldName) = explode(':', $fields[$i]);
				$where[] = $function . '(c.' . $fieldName . ') = :' . $fieldName;
				$params[$fieldName] = strtolower($values[$i]);
			}
		}
		$query = $this->getEntityManager()
					  ->createQuery('SELECT c FROM ' . $entityName . ' c WHERE ' . implode(' AND ', $where))
					  ->setParameters($params);
		$entry = $query->getOneOrNullResult();
		return !is_null($entry) && $contract->Id != $entry->id
			? $contract->error('Value already used.', 'Value already used.')
			: $contract->success();
	}

	/**
	 * Load job item into internal container.
	 * @param integer $jobId
	 * @param integer|null $rootId
	 * @throws \Exception
	 */
	public function loadJob($jobId, $rootId = null)
	{
		if (!is_null($this->jobRecord) && $jobId == $this->jobRecord->id)
		{
			return;
		}
		if (!is_null($jobId))
		{
			$this->jobRecord = $this->getEntityManager()
				->getRepository($this->entityMap[$this->primaryEntity])
				->find($jobId);
		}
		else
		{
			$em = $this->getEntityManager();
			$this->jobRecord = $em
				->getRepository($this->entityMap[$this->primaryEntity])
				->findOneBy(array(
						$this->rootIdField => $em->getReference(
								$this->entityMap[$this->rootEntity],
								$rootId
								)
				));
		}
		if (is_null($this->jobRecord))
		{
			throw new \Exception('Job Item could not be found.');
		}
	}

	/**
	 * Set job item in local container.
	 * @param object $jobRecord
	 */
	public function setJob($jobRecord)
	{
		$this->jobRecord = $jobRecord;
	}

	/**
	 * Job item reclaimed by owning workflow.
	 * @param string $namespace
	 * @param object $rootRecord
	 * @throws \Exception
	 * @return string
	 */
	public function reclaim($namespace, $rootRecord)
	{
		$this->loadJob(null, $rootRecord->id);
		if (!isset($this->reclaim['Destination']))
		{
			throw new \Exception('No Reclaim state provided.');
		}
		return $this->changeState(
				$this->reclaim['Destination'],
				$this->jobRecord->jobState
				);
	}

	/**
	 * Job item handed back from foreign workflow.
	 * @param string $namespace
	 * @param integer $jobId
	 * @throws \Exception
	 * @return string
	 */
	public function handover($namespace, $jobId, array $data = array())
	{
		$this->loadJob($jobId);
		if (!isset($this->stateMap[$this->jobRecord->jobState]['RouteBack']))
		{
			throw new \Exception('No RouteBack provided for state ' . $this->jobRecord->jobState);
		}
		if (isset($this->stateMap[$this->jobRecord->jobState]['RouteBack']['State']))
		{
			$newState = $this->stateMap[$this->jobRecord->jobState]['RouteBack']['State'];
		}
		elseif ($this->stateMap[$this->jobRecord->jobState]['RouteBack']['Action'])
		{
			list($handler, $action) = explode('.', $this->stateMap[$this->jobRecord->jobState]['RouteBack']['Action']);
			$service = $this->services->get($this->namespace . '.Service.' . $handler);
			$service->setWorkflow($this);
			$newState = $service->$action($this->jobRecord, $this->jobRecord->jobState, $data);
		}
		else
		{
			throw new \Exception('No RouteBack provided for state ' . $this->jobRecord->jobState);
		}
		return $this->changeState(
				$newState,
				$this->jobRecord->jobState
				);
	}

	/**
	 * Get the state for a specified item.
	 * @param integer $jobId
	 * @return string
	 * @throws \Exception
	 */
	protected function getState($jobId)
	{
		$this->loadJob($jobId);
		return $this->jobRecord->jobState;
	}

	/**
	 * Change the state for the current item.
	 * @param string|array $state
	 * @param string|null $previousState
	 */
	public function changeState($state, $previousState = null)
	{
		#-> Establish next state and routing data if provided.
		$routingData = array();
		if (is_array($state))
		{
			isset($state['Data'])
				&& $routingData = $state['Data'];
			$state = $state['Destination'];
		}
		if (!strpos($state, '.'))
		{
			throw new \Exception("New state `$state` should be in format `Workflow.State` ($this->namespace)");
		}
		list($workflow, $state) = explode('.', $state);
		$previousState = is_null($previousState) && !is_null($this->jobRecord)
			? $this->jobRecord->jobState
			: null;
		$newState = ('This' == $workflow)
			? $state
			: $workflow;

		#-> Direct reroute on initialization of new state.
		if (isset($this->stateMap[$newState]['InitRoute']))
		{
			list($handler, $action) = explode('.', $this->stateMap[$newState]['InitRoute']);
			$service = $this->services->get($this->namespace . '.Service.' . $handler);
			$service->setWorkflow($this);
			$newState = $service->$action($this->jobRecord, $previousState, $routingData);
			return $this->changeState($newState, $state);
		}

		#-> Initialization for new state.
		if (isset($this->stateMap[$newState]['Init']))
		{
			list($handler, $action) = explode('.', $this->stateMap[$newState]['Init']);
			$service = $this->services->get($this->namespace . '.Service.' . $handler);
			$service->setWorkflow($this);
			$service->$action($this->jobRecord, $previousState, $routingData);
		}

		#-> Are we passing control over to another workflow?
		if ('This' != $workflow)
		{
			$wf = $this->services->get($workflow);
			if ('Handover' == $state)
			{
				$rootIdField = $this->rootIdField;
				$wf->handover($this->namespace, $this->jobRecord->$rootIdField->id, $routingData);
			}
			else
			{
				$service = $this->services->get($workflow . '.Service.' . $workflow);
				$service->setWorkflow($wf);
				$action = 'init' . $state;
				$service->$action(
						$this->jobRecord,
						$this->namespace . '.' . $previousState,
						$routingData
						);
			}
		}
		!is_null($previousState)
			&& $this->jobRecord->previousState = $previousState;
		$this->jobRecord->jobState = isset($this->stateLabel[$newState])
			? $this->stateLabel[$newState]
			: $newState;
		$this->em->flush();
		return $this->jobRecord->jobState;
	}

	/**
	 * Check if a task is valid for provided context.
	 * @param string $type
	 * @param string $state
	 * @param string $task
	 * @param integer|null $jobId
	 * @return boolean
	 */
	protected function validTask($type, $state, $task, $jobId = null)
	{
		if (!isset($this->stateMap[$state][$type][$task]))
		{
			return false;
		}
		$meta = $this->stateMap[$state][$type][$task];
		if (isset($meta['ApplicationRestriction']))
		{
			is_array($meta['ApplicationRestriction'])
				|| $meta['ApplicationRestriction'] = array($meta['ApplicationRestriction']);
			if (!in_array(APPLICATION, $meta['ApplicationRestriction']))
			{
				return false;
			}
		}
		return true;
	}

	/**
	 * Retrieve a task contract.
	 * @param string $task
	 * @param integer|null $jobId
	 * @param array $input
	 * @return \Workspace\Contract\AbstractBase
	 * @throws \Exception
	 */
	public function contractTask($task, $jobId = null, array $input = array())
	{
		!is_null($jobId)
			&& !isset($input['id'])
			&& $input['id'] = $jobId;
		$state = is_null($jobId)
			? 'Global'
			: $this->getState($jobId);
		if (!$this->validTask('Actions', $state, $task, $jobId))
		{
			throw new \Exception('Not a valid task for specified job item. (Id: ' . $jobId . '; State: ' . $state . ')');
		}
		list($handler, $action) = explode('.', $task);
		$service = $this->services->get($this->namespace . '.Service.' . $handler);
		$service->setWorkflow($this);
		$action = 'contract' . $action;
		return $service->$action($this->jobRecord, $input);
	}

	/**
	 * Execute a contracted task.
	 * @param string $task
	 * @param integer|null $jobId
	 * @param \Workspace\Utility\ServiceInputParams $contract
	 * @return array
	 */
	public function executeTask($task, $jobId = null, \Workspace\Utility\ServiceInputParams $contract)
	{
		$state = is_null($jobId)
			? 'Global'
			: $this->getState($jobId);
		list($handler, $action) = explode('.', $task);
		$service = $this->services->get($this->namespace . '.Service.' . $handler);
		$service->setWorkflow($this);
		$action = 'execute' . $action;
		return $service->$action($this->jobRecord, $contract);
	}

	/**
	 * Retrieve a route contract.
	 * @param string $route
	 * @param integer|null $jobId
	 * @param array $input
	 * @return \Workspace\Contract\AbstractBase
	 * @throws \Exception
	 */
	public function contractRoute($route, $jobId, array $input = array())
	{
		!is_null($jobId)
			&& $input['id'] = $jobId;
		$state = is_null($jobId)
			? 'Global'
			: $this->getState($jobId);
		//$contract = new \Workspace\Utility\ServiceInputParams();
		if (!$this->validTask('Routes', $state, $route, $jobId))
		{
			throw new \Exception('Not a valid task for specified job item. (Id: ' . $jobId . '; State: ' . $state . ')');
		}
		list($handler, $action) = explode('.', $route);
		$service = $this->services->get($this->namespace . '.Service.' . $handler);
		$service->setWorkflow($this);
		$action = 'contractRoute' . $action;
		return $service->$action($this->jobRecord, $input);
	}

	/**
	 * Execute a contracted route.
	 * @param string $route
	 * @param integer|null $jobId
	 * @param \Workspace\Utility\ServiceInputParams $contract
	 * @return array
	 */
	public function executeRoute($route, $jobId, \Workspace\Utility\ServiceInputParams $contract)
	{
		#-> Establish next state for routing.
		$state = is_null($jobId)
			? 'Global'
			: $this->getState($jobId);
		list($handler, $action) = explode('.', $route);
		$service = $this->services->get($this->namespace . '.Service.' . $handler);
		$service->setWorkflow($this);
		$action = 'executeRoute' . $action;
		$nextState = $service->$action(
						$this->jobRecord, $state, $contract
						);

		#-> Resolve destination.
		(is_null($nextState) || is_bool($nextState)
		 || (is_array($nextState) && !isset($nextState['Destination'])))
			&& isset($this->stateMap[$state]['Routes'][$route]['Destination'])
			&& $nextState = $this->stateMap[$state]['Routes'][$route]['Destination'];
		if (is_null($nextState) || is_bool($nextState)
			|| (is_array($nextState) && !isset($nextState['Destination'])))
		{
			throw new \Exception('No destination state provided by workflow or contracted routing method.');
		}

		#-> Set new state.
		$newState = $this->changeState($nextState);
		return $contract->success('State changed.', array('State' => $newState));
	}

	/**
	 * Execute a direct route.
	 * @param string $route
	 * @param integer|null $jobId
	 * @return array
	 * @throws \Exception
	 */
	public function directRoute($route, $jobId)
	{
		#-> Check we have a valid request since we don't have a contract.
		$state = is_null($jobId)
			? 'Global'
			: $this->getState($jobId);
		if (!$this->validTask('Routes', $state, $route, $jobId))
		{
			throw new \Exception('Not a valid task for specified job item. (Id: ' . $jobId . '; State: ' . $state . ')');
		}
		list($handler, $action) = explode('.', $route);
		$contract = new \Workspace\Utility\ServiceInput('Contract');
		$contract = $contract->pack();

		#-> Are we reclaiming an item from another workflow?
		/* if (isset($this->stateMap[$state]['Routes'][$route]['ReclaimFrom']))
		{
			$service = $this->services->get(
					$this->stateMap[$state]['Routes'][$route]['ReclaimFrom']
					);
			$service->setServiceLocator($this->services);
			$service->reclaim($this->namespace, $this->jobRecord);
		} */

		#-> Shortcut.
		if ('Workflow' == $handler)
		{
			$newState = $this->changeState($this->stateMap[$state]['Routes'][$route]);
			return $contract->success('State changed.', array('State' => $newState));
		}

		#-> Check if we have a routing method.
		$service = $this->services->get($this->namespace . '.Service.' . $handler);
		$service->setWorkflow($this);
		$action = 'directRoute' . $action;
		$nextState = null;
		method_exists($service, $action)
			&& $nextState = $service->$action($this->jobRecord, $state);

		#-> Resolve destination.
		(is_null($nextState) || is_bool($nextState)
		 || (is_array($nextState) && !isset($nextState['Destination'])))
			&& isset($this->stateMap[$state]['Routes'][$route]['Destination'])
			&& $nextState = $this->stateMap[$state]['Routes'][$route]['Destination'];
		if (is_null($nextState) || is_bool($nextState)
			|| (is_array($nextState) && !isset($nextState['Destination'])))
		{
			throw new \Exception('No destination state provided by workflow or routing method.');
		}

		#-> Set new state.
		$newState = $this->changeState($nextState);
		return $contract->success('State changed.', array('State' => $newState));
	}



}

Commits for namibia/module/Workspace/src/Workspace/Workflow.php

Diff revisions: vs.
Revision Author Commited Message
df0489 ... Mark Fri 14 Oct, 2016 10:01:00 +0000

initial commit