Passed
Branch master (046a17)
by Mathieu
02:22
created

AddChildCompilerPass::process()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 29
rs 9.1111
cc 6
nc 12
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Neimheadh\SonataAnnotationBundle\DependencyInjection\Compiler;
6
7
use InvalidArgumentException;
8
use Neimheadh\SonataAnnotationBundle\Reader\AddChildReader;
9
use ReflectionClass;
10
use ReflectionException;
11
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
12
use Symfony\Component\DependencyInjection\ContainerBuilder;
13
14
/**
15
 * Add admin annotated @Neimheadh\SonataAnnotationBundle\Annotation\AddChild as
16
 * admin children.
17
 *
18
 * @author Marko Kunic <[email protected]>
19
 * @author Mathieu Wambre <[email protected]>
20
 */
21
final class AddChildCompilerPass implements CompilerPassInterface
22
{
23
    use FindClassTrait;
24
25
    /**
26
     * {@inheritDoc}
27
     *
28
     * @throws ReflectionException
29
     */
30
    public function process(ContainerBuilder $container): void
31
    {
32
        /** @var AddChildReader $annotationReader */
33
        $annotationReader = $container->get('sonata.annotation.reader.add_child');
34
        /** @var string[] $admins */
35
        $admins = [];
36
        /** @var array[] $adminChildren */
37
        $adminChildren = [];
38
39
        foreach ($container->findTaggedServiceIds('sonata.admin') as $id => $tag) {
40
            $class = $this->getClass($container, $id);
41
            $admins[$class] = $id;
42
43
            if ($children = $annotationReader->getChildren(new ReflectionClass($class))) {
44
                $adminChildren[$id] = $children;
45
            }
46
        }
47
48
        foreach ($adminChildren as $id => $children) {
49
            foreach ($children as $class => $field) {
50
                if (!isset($admins[$class])) {
51
                    throw new InvalidArgumentException(sprintf(
52
                        '%s is missing Admin Class.',
53
                        $class
54
                    ));
55
                }
56
57
                $definition = $container->getDefinition($id);
58
                $definition->addMethodCall('addChild', [$container->getDefinition($admins[$class]), $field]);
59
            }
60
        }
61
    }
62
}
63