Completed
Push — master ( 0726a8...336a87 )
by Emil
02:19
created

RegisterSchedulesPass   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 69
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 8 2
A isTaskImplementation() 0 9 2
A validateClass() 0 10 4
A add() 0 9 1
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