Passed
Pull Request — master (#300)
by Arnaud
14:15 queued 08:05
created

AdminConfiguration::getActionNormalizer()   A

Complexity

Conditions 6
Paths 1

Size

Total Lines 33
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 33
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LAG\AdminBundle\Admin\Configuration;
6
7
use Closure;
8
use JK\Configuration\Configuration;
9
use LAG\AdminBundle\Admin\Action;
10
use LAG\AdminBundle\Admin\Admin;
11
use LAG\AdminBundle\Admin\Configuration\Normalizer\LinkNormalizer;
12
use LAG\AdminBundle\Controller\AdminAction;
13
use LAG\AdminBundle\Exception\Exception;
14
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
15
use Symfony\Component\OptionsResolver\Options;
16
use Symfony\Component\OptionsResolver\OptionsResolver;
17
use function Symfony\Component\String\u;
18
19
/**
20
 * Ease Admin configuration manipulation.
21
 */
22
class AdminConfiguration extends Configuration
23
{
24
    protected function configureOptions(OptionsResolver $resolver): void
25
    {
26
        $resolver
27
            ->setRequired('entity')
28
            ->setAllowedTypes('entity', 'string')
29
            ->setRequired('name')
30
            ->setAllowedTypes('name', 'string')
31
            ->setDefault('title', null)
32
            ->setAllowedTypes('title', ['string', 'null'])
33
            ->addNormalizer('title', function (Options $options, $value) {
34
                if ($value === null) {
35
                    $value = u($options->offsetGet('name'))->title()->toString();
36
                }
37
38
                return $value;
39
            })
40
41
            ->setDefault('actions', [
42
                'list' => [],
43
                'create' => [],
44
                'edit' => [],
45
                'delete' => [],
46
            ])
47
            ->setAllowedTypes('actions', 'array')
48
            ->setNormalizer('actions', $this->getActionNormalizer())
49
50
            ->setDefault('list_actions', [
51
                'edit' => [],
52
                'delete' => [],
53
            ])
54
            ->setAllowedTypes('list_actions', 'array')
55
            ->setNormalizer('list_actions', function (Options $options, $value) {
56
                foreach ($value as $actionName => $actionConfiguration) {
57
                    $value[$actionName] = LinkNormalizer::normalize(
58
                        $actionConfiguration,
59
                        $options->offsetGet('name'),
60
                        $actionName
61
                    );
62
                }
63
64
                return $value;
65
            })
66
67
            ->setDefault('item_actions', [
68
                'create' => [],
69
            ])
70
            ->setAllowedTypes('item_actions', 'array')
71
            ->setNormalizer('item_actions', function (Options $options, $value) {
72
                foreach ($value as $actionName => $actionConfiguration) {
73
                    $value[$actionName] = LinkNormalizer::normalize(
74
                        $actionConfiguration,
75
                        $options->offsetGet('name'),
76
                        $actionName
77
                    );
78
                }
79
80
                return $value;
81
            })
82
83
            ->setDefault('controller', AdminAction::class)
84
            ->setAllowedTypes('controller', 'string')
85
86
            ->setDefault('batch', [])
87
            ->setAllowedTypes('batch', 'array')
88
89
            ->setDefault('admin_class', Admin::class)
90
            ->setAllowedTypes('admin_class', 'string')
91
            ->setDefault('action_class', Action::class)
92
            ->setAllowedTypes('action_class', 'string')
93
94
            ->setDefault('routes_pattern', 'lag_admin.{admin}.{action}')
95
            ->setAllowedTypes('routes_pattern', 'string')
96
            ->setNormalizer('routes_pattern', $this->getRoutesPatternNormalizer())
97
98
            ->setDefault('pager', 'pagerfanta')
99
            ->setAllowedValues('pager', ['pagerfanta', false])
100
            ->setDefault('max_per_page', 25)
101
            ->setAllowedTypes('max_per_page', 'integer')
102
            ->setDefault('page_parameter', 'page')
103
            ->setAllowedTypes('page_parameter', 'string')
104
105
            ->setDefault('permissions', 'ROLE_ADMIN')
106
            ->setAllowedTypes('permissions', 'string')
107
108
            ->setDefault('date_format', 'Y-m-d')
109
            ->setAllowedTypes('date_format', 'string')
110
111
            ->setDefault('data_provider', 'doctrine')
112
            ->setAllowedTypes('data_provider', 'string')
113
            ->setDefault('data_persister', 'doctrine')
114
            ->setAllowedTypes('data_persister', 'string')
115
116
            ->setDefault('create_template', '@LAGAdmin/crud/create.html.twig')
117
            ->setAllowedTypes('create_template', 'string')
118
            ->setDefault('edit_template', '@LAGAdmin/crud/edit.html.twig')
119
            ->setAllowedTypes('edit_template', 'string')
120
            ->setDefault('list_template', '@LAGAdmin/crud/list.html.twig')
121
            ->setAllowedTypes('list_template', 'string')
122
            ->setDefault('delete_template', '@LAGAdmin/crud/delete.html.twig')
123
            ->setAllowedTypes('delete_template', 'string')
124
        ;
125
    }
126
127
    public function getName(): string
128
    {
129
        return $this->getString('name');
130
    }
131
132
    public function getAdminClass(): string
133
    {
134
        return $this->getString('admin_class');
135
    }
136
137
    public function getActionClass(): string
138
    {
139
        return $this->getString('action_class');
140
    }
141
142
    public function getTitle(): string
143
    {
144
        return $this->getString('title');
145
    }
146
147
    public function getActions(): array
148
    {
149
        return $this->get('actions');
150
    }
151
152
    public function hasAction(string $actionName): bool
153
    {
154
        return \array_key_exists($actionName, $this->getActions());
155
    }
156
157
    public function getAction(string $actionName): array
158
    {
159
        return $this->getActions()[$actionName];
160
    }
161
162
    public function getListActions(): array
163
    {
164
        return $this->get('list_actions');
165
    }
166
167
    public function getItemActions(): array
168
    {
169
        return $this->get('item_actions');
170
    }
171
172
    public function getEntityClass(): string
173
    {
174
        return $this->getString('entity');
175
    }
176
177
    public function getController(): string
178
    {
179
        return $this->getString('controller');
180
    }
181
182
    public function getBatch(): array
183
    {
184
        return $this->get('batch');
185
    }
186
187
    public function getRoutesPattern(): string
188
    {
189
        return $this->getString('routes_pattern');
190
    }
191
192
    public function isPaginationEnabled(): bool
193
    {
194
        $pager = $this->get('pager');
195
196
        return !($pager === false);
197
    }
198
199
    public function getPager(): string
200
    {
201
        if (!$this->isPaginationEnabled()) {
202
            throw new Exception(sprintf('The pagination is not enabled for the admin "%s"', $this->getString('name')));
203
        }
204
205
        return $this->get('pager');
206
    }
207
208
    public function getMaxPerPage(): int
209
    {
210
        return $this->getInt('max_per_page');
211
    }
212
213
    public function getPageParameter(): string
214
    {
215
        return $this->get('page_parameter');
216
    }
217
218
    public function getPermissions(): array
219
    {
220
        $roles = explode(',', $this->get('permissions'));
221
222
        foreach ($roles as $index => $role) {
223
            $roles[$index] = trim($role);
224
        }
225
226
        return $roles;
227
    }
228
229
    public function getDateFormat(): string
230
    {
231
        return $this->getString('date_format');
232
    }
233
234
    public function getActionRouteParameters(string $actionName): array
235
    {
236
        $actionConfiguration = $this->getAction($actionName);
237
238
        if (empty($actionConfiguration['route_parameters'])) {
239
            return [];
240
        }
241
242
        return $actionConfiguration['route_parameters'];
243
    }
244
245
    public function getDataProvider(): string
246
    {
247
        return $this->getString('data_provider');
248
    }
249
250
    public function getDataPersister(): string
251
    {
252
        return $this->getString('data_persister');
253
    }
254
255
    public function getCreateTemplate(): string
256
    {
257
        return $this->getString('create_template');
258
    }
259
260
    public function getEditTemplate(): string
261
    {
262
        return $this->getString('edit_template');
263
    }
264
265
    public function getListTemplate(): string
266
    {
267
        return $this->getString('list_template');
268
    }
269
270
    public function getDeleteTemplate(): string
271
    {
272
        return $this->getString('delete_template');
273
    }
274
275
    private function getActionNormalizer(): Closure
276
    {
277
        return function (Options $options, $actions) {
278
            $normalizedActions = [];
279
//            $addBatchAction = false;
280
281
            foreach ($actions as $name => $action) {
282
                // action configuration is an array by default
283
                if (null === $action) {
284
                    $action = [];
285
                }
286
287
                if (!\array_key_exists('route_parameters', $action)) {
288
                    if ($name === 'edit' || $name === 'delete') {
289
                        $action['route_parameters'] = ['id' => null];
290
                    }
291
                }
292
                $action['admin_name'] = $options->offsetGet('name');
293
                $normalizedActions[$name] = $action;
294
295
                // in list action, if no batch was configured or disabled, we add a batch action
296
//                if ('list' == $name && (!\array_key_exists('batch', $action) || null === $action['batch'])) {
297
//                    $addBatchAction = true;
298
//                }
299
            }
300
301
            // add empty default batch action
302
//            if ($addBatchAction) {
303
//             TODO enable mass action
304
//            $normalizedActions['batch'] = [];
305
//            }
306
307
            return $normalizedActions;
308
        };
309
    }
310
311
    private function getRoutesPatternNormalizer(): Closure
312
    {
313
        return function (Options $options, $value) {
314
            if (!u($value)->containsAny('{action}')) {
315
                throw new InvalidOptionsException(sprintf('The "%s" parameters in admin "%s" should contains the "%s" parameters', 'routes_pattern', $options->offsetGet('name'), '{action}'));
316
            }
317
318
            if (!u($value)->containsAny('{admin}')) {
319
                throw new InvalidOptionsException(sprintf('The "%s" parameters in admin "%s" should contains the "%s" parameters', 'routes_pattern', $options->offsetGet('name'), '{admin}'));
320
            }
321
322
            return $value;
323
        };
324
    }
325
}
326