Completed
Pull Request — master (#1)
by Alexander
03:03
created

TaskCompilerPass::process()   C

Complexity

Conditions 7
Paths 11

Size

Total Lines 38
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 38
rs 6.7273
cc 7
eloc 21
nc 11
nop 1
1
<?php
2
3
namespace Task\TaskBundle\DependencyInjection;
4
5
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
6
use Symfony\Component\DependencyInjection\ContainerBuilder;
7
use Symfony\Component\DependencyInjection\Reference;
8
9
/**
10
 * Compiler pass which collects worker services.
11
 *
12
 * @author @wachterjohannes <[email protected]>
13
 */
14
class TaskCompilerPass implements CompilerPassInterface
15
{
16
    const SCHEDULER_ID = 'task.scheduler';
17
    const INTERVAL_TAG = 'task.interval';
18
    const KEY_ATTRIBUTE = 'key';
19
    const INTERVAL_ATTRIBUTE = 'interval';
20
    const WORKLOAD_ATTRIBUTE = 'workload';
21
    const CREATE_FUNCTION_NAME = 'createTaskAndSchedule';
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function process(ContainerBuilder $container)
27
    {
28
        if (!$container->has(self::SCHEDULER_ID)) {
29
            return;
30
        }
31
32
        $schedulerDefinition = $container->getDefinition(self::SCHEDULER_ID);
33
34
        $taggedServices = $container->findTaggedServiceIds(self::INTERVAL_TAG);
35
        foreach ($taggedServices as $id => $tags) {
36
            $handlerDefinition = $container->getDefinition($id);
37
            $tag = $handlerDefinition->getTag(HandlerCompilerPass::HANDLER_TAG);
38
39
            $handler = $tag[0][HandlerCompilerPass::HANDLER_NAME_ATTRIBUTE];
40
41
            // remove all tasks with $id and not completed
42
            foreach ($tags as $attributes) {
43
                $interval = $attributes[self::INTERVAL_ATTRIBUTE];
44
                $workload = isset($attributes[self::WORKLOAD_ATTRIBUTE]) ? $attributes[self::WORKLOAD_ATTRIBUTE] : null;
45
                $key = isset($attributes[self::KEY_ATTRIBUTE]) ? $attributes[self::KEY_ATTRIBUTE] : null;
46
47
                if (!$key) {
48
                    $key = $handler . '_' . $interval . '_' . serialize($workload);
49
                }
50
51
52
                $schedulerDefinition->addMethodCall(
53
                    self::CREATE_FUNCTION_NAME,
54
                    [
55
                        $handler,
56
                        $interval,
57
                        $workload,
58
                        $key,
59
                    ]
60
                );
61
            }
62
        }
63
    }
64
}
65