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

ListReader   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 18
c 1
b 0
f 0
dl 0
loc 59
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getListActions() 0 21 4
A configureFields() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Neimheadh\SonataAnnotationBundle\Reader;
6
7
use Doctrine\Common\Annotations\Reader;
8
use Neimheadh\SonataAnnotationBundle\Annotation\ListAction;
9
use Neimheadh\SonataAnnotationBundle\Annotation\ListField;
10
use Neimheadh\SonataAnnotationBundle\Exception\MissingAnnotationArgumentException;
11
use ReflectionClass;
12
use Sonata\AdminBundle\Datagrid\ListMapper;
13
use Sonata\AdminBundle\Mapper\MapperInterface;
14
15
/**
16
 * List configuration reader.
17
 *
18
 * @author Marko Kunic <[email protected]>
19
 * @author Mathieu Wambre <[email protected]>
20
 */
21
final class ListReader extends AbstractFieldConfigurationReader
22
{
23
24
    /**
25
     * {@inheritDoc}
26
     */
27
    public function __construct(Reader $annotationReader)
28
    {
29
        parent::__construct($annotationReader, ListField::class);
30
    }
31
32
    /**
33
     * {@inheritDoc}
34
     *
35
     * @param ListMapper $mapper Admin list mapper.
36
     */
37
    public function configureFields(
38
        ReflectionClass $class,
39
        MapperInterface $mapper
40
    ): void {
41
        parent::configureFields($class, $mapper);
42
43
        if ($mapper instanceof ListMapper) {
44
            if ($actions = $this->getListActions($class)) {
45
                $mapper->add('_action', null, [
46
                    'actions' => $actions,
47
                ]);
48
            }
49
        }
50
    }
51
52
    /**
53
     * Get list of actions.
54
     *
55
     * @param ReflectionClass $class Entity class.
56
     *
57
     * @return array
58
     */
59
    private function getListActions(ReflectionClass $class): array
60
    {
61
        $actions = [];
62
        /** @var array<object|ListAction> $annotations */
63
        $annotations = $this->annotationReader->getClassAnnotations($class);
64
65
        foreach ($annotations as $annotation) {
66
            if ($annotation instanceof ListAction) {
67
                if (!isset($annotation->name)) {
68
                    throw new MissingAnnotationArgumentException(
69
                        $annotation,
70
                        'name',
71
                        $class
72
                    );
73
                }
74
75
                $actions[$annotation->name] = $annotation->options;
76
            }
77
        }
78
79
        return $actions;
80
    }
81
82
}
83