Completed
Push — refonte ( 01d054...fceb40 )
by Arnaud
18:53 queued 16:45
created

ActionCollectionField   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 172
Duplicated Lines 21.51 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 13
dl 37
loc 172
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B configureOptions() 0 44 6
A isSortable() 0 4 1
A render() 6 16 3
C resolveActionLinkConfiguration() 31 100 11

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace LAG\AdminBundle\Field;
4
5
use LAG\AdminBundle\Configuration\ActionConfiguration;
6
use LAG\AdminBundle\Field\Traits\EntityAwareTrait;
7
use LAG\AdminBundle\Field\Traits\TwigAwareTrait;
8
use LAG\AdminBundle\Routing\RoutingLoader;
9
use LAG\AdminBundle\Utils\StringUtils;
10
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
11
use Symfony\Component\OptionsResolver\Options;
12
use Symfony\Component\OptionsResolver\OptionsResolver;
13
use Symfony\Component\PropertyAccess\PropertyAccess;
14
15
class ActionCollectionField extends CollectionField implements TwigAwareFieldInterface, EntityAwareFieldInterface
16
{
17
    use TwigAwareTrait, EntityAwareTrait;
18
19
    public function configureOptions(OptionsResolver $resolver, ActionConfiguration $actionConfiguration)
20
    {
21
        parent::configureOptions($resolver, $actionConfiguration);
22
23
        $actions = $actionConfiguration
24
            ->getAdminConfiguration()
25
            ->getParameter('actions')
26
        ;
27
        $defaultActions = [];
28
29
        if (key_exists('edit', $actions)) {
30
            $defaultActions['edit'] = $actions['edit'];
31
        }
32
33
        if (key_exists('delete', $actions)) {
34
            $defaultActions['delete'] = $actions['delete'];
35
        }
36
37
        $resolver
38
            ->setDefaults([
39
                'template' => '@LAGAdmin/Field/actionCollection.html.twig',
40
                'actions' => [],
41
            ])
42
            ->setNormalizer('actions', function (Options $options, $value) use ($actionConfiguration, $defaultActions) {
43
                if (!is_array($value) || 0 === count($value)) {
44
                    $value = [
45
                        'edit' => [],
46
                        'delete' => [],
47
                    ];
48
                }
49
                $data = [];
50
51
                foreach ($value as $name => $actionLinkConfiguration) {
52
                    $data[$name] = $this->resolveActionLinkConfiguration(
53
                        $actionConfiguration,
54
                        $name,
55
                        $actionLinkConfiguration
56
                    );
57
                }
58
59
                return $data;
60
            })
61
        ;
62
    }
63
64
    public function isSortable(): bool
65
    {
66
        return false;
67
    }
68
69
    public function render($value = null): string
70
    {
71
        $accessor = PropertyAccess::createPropertyAccessor();
72
73 View Code Duplication
        if (key_exists('edit', $this->options['actions'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
74
            $this->options['actions']['edit']['parameters']['id'] = $accessor->getValue($this->entity, 'id');
75
        }
76
77 View Code Duplication
        if (key_exists('delete', $this->options['actions'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
78
            $this->options['actions']['delete']['parameters']['id'] = $accessor->getValue($this->entity, 'id');
79
        }
80
81
        return $this->twig->render($this->options['template'], [
82
            'actions' => $this->options['actions'],
83
        ]);
84
    }
85
86
    protected function resolveActionLinkConfiguration(
87
        ActionConfiguration $actionConfiguration,
88
        string $actionName,
89
        array $actionLinkConfiguration = []
90
    ): array {
91
        $translationPattern = $actionConfiguration
92
            ->getAdminConfiguration()
93
            ->getParameter('translation_pattern')
94
        ;
95
96
        $icon = '';
97
        $cssClass = '';
98
        $routeParameters = [];
99
100
        if ('delete' === $actionName) {
101
            $icon = 'remove';
102
            $cssClass = 'btn btn-danger btn-sm';
103
            $routeParameters = [
104
                'id' => ''
105
            ];
106
        }
107
        if ('edit' === $actionName) {
108
            $icon = 'pencil';
109
            $cssClass = 'btn btn-secondary btn-sm';
110
        }
111
112
        $resolver = new OptionsResolver();
113
        $resolver
114
            ->setDefaults([
115
                'title' => StringUtils::getTranslationKey(
116
                    $translationPattern,
117
                    $actionConfiguration->getAdminName(),
118
                    $actionName
119
                ),
120
                'icon' => $icon,
121
                'target' => '_self',
122
                'route' => '',
123
                'parameters' => $routeParameters,
124
                'url' => '',
125
                'text' => StringUtils::getTranslationKey(
126
                    $translationPattern,
127
                    $actionConfiguration->getAdminName(),
128
                    $actionName
129
                ),
130
                'admin' => $actionConfiguration->getAdminName(),
131
                'action' => $actionConfiguration->getActionName(),
132
                'class' => $cssClass,
133
            ])
134
            ->setAllowedTypes('route', 'string')
135
            ->setAllowedTypes('parameters', 'array')
136
            ->setAllowedTypes('url', 'string')
137
            ->setAllowedValues('target', [
138
                '_self',
139
                '_blank',
140
            ])
141 View Code Duplication
            ->setNormalizer('route', function (Options $options, $value) use ($actionConfiguration) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
142
                // route or url should be defined
143
                if (!$value && !$options->offsetGet('url') && !$options->offsetGet('admin')) {
144
                    throw new InvalidOptionsException(
145
                        'You must set either an url or a route for the property'
146
                    );
147
                }
148
149
                if ($options->offsetGet('admin')) {
150
                    $value = RoutingLoader::generateRouteName(
151
                        $options->offsetGet('admin'),
152
                        $options->offsetGet('action'),
153
                        $actionConfiguration->getAdminConfiguration()->getParameter('routing_name_pattern')
154
                    );
155
                }
156
157
                return $value;
158
            })
159
            ->setNormalizer('admin', function (Options $options, $value) {
160
                // if a Admin is defined, an Action should be defined too
161
                if ($value && !$options->offsetGet('action')) {
162
                    throw new InvalidOptionsException(
163
                        'An Action should be provided if an Admin is provided'
164
                    );
165
                }
166
167
                return $value;
168
            })
169 View Code Duplication
            ->setNormalizer('parameters', function (Options $options, $values) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
                $cleanedValues = [];
171
172
                foreach ($values as $name => $method) {
173
                    if (null === $method) {
174
                        $method = $name;
175
                    }
176
                    $cleanedValues[$name] = $method;
177
                }
178
179
180
                return $cleanedValues;
181
            })
182
        ;
183
184
        return $resolver->resolve($actionLinkConfiguration);
185
    }
186
}
187