1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Glooby\TaskBundle\DependencyInjection\Compiler; |
4
|
|
|
|
5
|
|
|
use Glooby\TaskBundle\Task\TaskInterface; |
6
|
|
|
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
7
|
|
|
use Symfony\Component\DependencyInjection\ContainerBuilder; |
8
|
|
|
use Symfony\Component\DependencyInjection\Definition; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @author Emil Kilhage |
12
|
|
|
*/ |
13
|
|
|
class RegisterSchedulesPass implements CompilerPassInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Mapping of class names to booleans indicating whether the class |
17
|
|
|
* implements TaskInterface. |
18
|
|
|
* |
19
|
|
|
* @var array |
20
|
|
|
*/ |
21
|
|
|
private $implementations = array(); |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
|
|
public function process(ContainerBuilder $container) |
27
|
|
|
{ |
28
|
|
|
$registry = $container->getDefinition('glooby_task.schedule_registry'); |
29
|
|
|
|
30
|
|
|
foreach ($container->findTaggedServiceIds('glooby.scheduled_task') as $taskId => $tags) { |
31
|
|
|
$this->add($container, $taskId, $registry); |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Returns whether the class implements TaskInterface. |
37
|
|
|
* |
38
|
|
|
* @param string $class |
39
|
|
|
* |
40
|
|
|
* @return bool |
41
|
|
|
*/ |
42
|
|
|
private function isTaskImplementation($class) |
43
|
|
|
{ |
44
|
|
|
if (!isset($this->implementations[$class])) { |
45
|
|
|
$reflectionClass = new \ReflectionClass($class); |
46
|
|
|
$this->implementations[$class] = $reflectionClass->implementsInterface(TaskInterface::class); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $this->implementations[$class]; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param string $class |
54
|
|
|
* @param string $taskId |
55
|
|
|
*/ |
56
|
|
|
protected function validateClass($class, $taskId) |
57
|
|
|
{ |
58
|
|
|
if (!class_exists($class)) { |
59
|
|
|
throw new \InvalidArgumentException('Invalid class: ' . $class); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
if ($class && !$this->isTaskImplementation($class)) { |
63
|
|
|
throw new \InvalidArgumentException(sprintf('schedule "%s" with class "%s" must implement TaskInterface.', $taskId, $class)); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param ContainerBuilder $container |
69
|
|
|
* @param string $taskId |
70
|
|
|
* @param Definition $registry |
71
|
|
|
*/ |
72
|
|
|
protected function add(ContainerBuilder $container, $taskId, Definition $registry) |
73
|
|
|
{ |
74
|
|
|
$definition = $container->getDefinition($taskId); |
75
|
|
|
$class = $definition->getClass(); |
76
|
|
|
|
77
|
|
|
$this->validateClass($class, $taskId); |
78
|
|
|
|
79
|
|
|
$registry->addMethodCall('addTask', [$taskId]); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|