Completed
Pull Request — master (#41)
by Wachter
20:46
created

TaskExtension::loadDoctrineAdapter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
rs 9.4285
ccs 12
cts 12
cp 1
cc 2
eloc 9
nc 2
nop 2
crap 2
1
<?php
2
3
/*
4
 * This file is part of php-task library.
5
 *
6
 * (c) php-task
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Task\TaskBundle\DependencyInjection;
13
14
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
15
use Symfony\Component\Config\FileLocator;
16
use Symfony\Component\Config\Loader\LoaderInterface;
17
use Symfony\Component\DependencyInjection\ContainerBuilder;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19
use Symfony\Component\DependencyInjection\Definition;
20
use Symfony\Component\DependencyInjection\Loader;
21
use Symfony\Component\DependencyInjection\Reference;
22
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
23
use Task\Event\Events;
24
use Task\TaskBundle\EventListener\DoctrineTaskExecutionListener;
25
26
/**
27
 * Container extension for php-task library.
28
 */
29
class TaskExtension extends Extension
30
{
31
    /**
32
     * {@inheritdoc}
33 30
     */
34
    public function load(array $configs, ContainerBuilder $container)
35 30
    {
36 30
        $configuration = $this->getConfiguration($configs, $container);
37
        $config = $this->processConfiguration($configuration, $configs);
0 ignored issues
show
Bug introduced by
It seems like $configuration defined by $this->getConfiguration($configs, $container) on line 36 can be null; however, Symfony\Component\Depend...:processConfiguration() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
38 30
39
        $container->setParameter('task.system_tasks', $config['system_tasks']);
40 30
41 30
        $container->setAlias('task.lock.storage', $configuration->getLockingStorageId($config['locking']['storage']));
42 30
        foreach (array_keys($config['locking']['storages']) as $key) {
43 30
            $container->setParameter('task.lock.storages.' . $key, $config['locking']['storages'][$key]);
44
        }
45 30
46 30
        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
47 30
        $loader->load(sprintf('storage/%s.xml', $config['storage']));
48 30
        $loader->load('task_event_listener.xml');
49 30
        $loader->load('scheduler.xml');
50 30
        $loader->load('command.xml');
51
        $loader->load('locking/services.xml');
52 30
53
        if ($config['run']['mode'] === 'listener') {
54
            $loader->load('listener.xml');
55
        }
56 30
57 30
        $this->loadDoctrineAdapter($config['adapters']['doctrine'], $container);
58 30
        $this->loadLockingComponent($config['locking'], $container, $loader);
59
        $this->loadExecutorComponent($config['executor'], $container, $loader);
60
    }
61
62
    /**
63
     * Load doctrine adapter.
64
     *
65
     * @param array $config
66 30
     * @param ContainerBuilder $container
67
     */
68 30
    private function loadDoctrineAdapter(array $config, ContainerBuilder $container)
69 30
    {
70 30
        if ($config['clear']) {
71 30
            $definition = new Definition(
72 30
                DoctrineTaskExecutionListener::class,
73 30
                [new Reference('doctrine.orm.entity_manager', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]
74 30
            );
75 30
            $definition->addTag(
76 30
                'kernel.event_listener',
77 30
                ['event' => Events::TASK_AFTER, 'method' => 'clearEntityManagerAfterTask']
78 30
            );
79 30
            $container->setDefinition('task.adapter.doctrine.execution_listener', $definition);
80
        }
81
    }
82
83
    /**
84
     * Load services for locking component.
85
     *
86
     * @param array $config
87
     * @param LoaderInterface $loader
88 30
     * @param ContainerBuilder $container
89
     */
90 30
    private function loadLockingComponent(array $config, ContainerBuilder $container, LoaderInterface $loader)
91
    {
92
        if (!$config['enabled']) {
93
            return $loader->load('locking/null.xml');
94 30
        }
95 30
96 30
        $loader->load('locking/services.xml');
97
        $container->setParameter('task.lock.ttl', $config['ttl']);
98
    }
99
100
    /**
101
     * Load services for executor component.
102
     *
103
     * @param array $config
104
     * @param LoaderInterface $loader
105 30
     * @param ContainerBuilder $container
106
     */
107 30
    private function loadExecutorComponent(array $config, ContainerBuilder $container, LoaderInterface $loader)
108
    {
109 30
        $loader->load('executor/' . $config['type'] . '.xml');
110 30
        $container->setAlias('task.executor', 'task.executor.' . $config['type']);
111 30
112 30
        if (!array_key_exists($config['type'], $config)) {
113 30
            return;
114 30
        }
115
116 30
        foreach ($config[$config['type']] as $key => $value) {
117
            $container->setParameter('task.executor.' . $key, $value);
118
        }
119
120
        if (!file_exists($container->getParameter('task.executor.console_path'))) {
121
            throw new InvalidConfigurationException(
122 30
                'Console file does not exists! Given in "task.executor.seperate.console".'
123
            );
124 30
        }
125 30
    }
126
127 30
    /**
128
     * Find storage aliases and related ids.
129
     *
130
     * @param ContainerBuilder $container
131
     *
132
     * @return array
133
     */
134
    private function getLockingStorageAliases(ContainerBuilder $container)
135
    {
136
        $taggedServices = $container->findTaggedServiceIds('task.lock.storage');
137
138
        $result = [];
139
        foreach ($taggedServices as $id => $tags) {
140
            foreach ($tags as $tag) {
141
                $result[$tag['alias']] = $id;
142
            }
143
        }
144
145
        return $result;
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function getConfiguration(array $config, ContainerBuilder $container)
152
    {
153
        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
154
        $loader->load('locking/storages.xml');
155
156
        return new Configuration($this->getLockingStorageAliases($container));
157
    }
158
}
159