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

RegisterSchedulesPass::validateClass()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.2
c 0
b 0
f 0
cc 4
eloc 5
nc 3
nop 2
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