Completed
Push — symfony3-fqcn-sylius-2 ( 026c63 )
by Kamil
18:19
created

RequestConfiguration::getFormConfiguration()   D

Complexity

Conditions 9
Paths 10

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 4.909
c 0
b 0
f 0
cc 9
eloc 15
nc 10
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Bundle\ResourceBundle\Controller;
13
14
use Sylius\Component\Resource\Metadata\MetadataInterface;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\PropertyAccess\PropertyAccess;
17
18
/**
19
 * @author Paweł Jędrzejewski <[email protected]>
20
 * @author Saša Stamenković <[email protected]>
21
 * @author Gustavo Perdomo <[email protected]>
22
 */
23
class RequestConfiguration
24
{
25
    /**
26
     * @var Request
27
     */
28
    private $request;
29
30
    /**
31
     * @var MetadataInterface
32
     */
33
    private $metadata;
34
35
    /**
36
     * @var Parameters
37
     */
38
    private $parameters;
39
40
    /**
41
     * @param MetadataInterface $metadata
42
     * @param Request $request
43
     * @param Parameters $parameters
44
     */
45
    public function __construct(MetadataInterface $metadata, Request $request, Parameters $parameters)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
46
    {
47
        $this->metadata = $metadata;
48
        $this->request = $request;
49
        $this->parameters = $parameters;
50
    }
51
52
    /**
53
     * @return Request
54
     */
55
    public function getRequest()
56
    {
57
        return $this->request;
58
    }
59
60
    /**
61
     * @return MetadataInterface
62
     */
63
    public function getMetadata()
64
    {
65
        return $this->metadata;
66
    }
67
68
    /**
69
     * @return Parameters
70
     */
71
    public function getParameters()
72
    {
73
        return $this->parameters;
74
    }
75
76
    /**
77
     * @return string|null
78
     */
79
    public function getSection()
80
    {
81
        return $this->parameters->get('section');
82
    }
83
84
    /**
85
     * @return bool
86
     */
87
    public function isHtmlRequest()
88
    {
89
        return 'html' === $this->request->getRequestFormat();
90
    }
91
92
    /**
93
     * @param $name
94
     *
95
     * @return null|string
96
     */
97
    public function getDefaultTemplate($name)
98
    {
99
        $templatesNamespace = $this->metadata->getTemplatesNamespace();
100
101
        if (false !== strpos($templatesNamespace, ':')) {
102
            return sprintf('%s:%s.%s', $templatesNamespace ?: ':', $name, 'twig');
103
        }
104
105
        return sprintf('%s/%s.%s', $templatesNamespace, $name, 'twig');
106
    }
107
108
    /**
109
     * @param $name
110
     *
111
     * @return mixed|null
112
     */
113
    public function getTemplate($name)
114
    {
115
        $template = $this->parameters->get('template', $this->getDefaultTemplate($name));
116
117
        if (null === $template) {
118
            throw new \RuntimeException(sprintf('Could not resolve template for resource "%s".', $this->metadata->getAlias()));
119
        }
120
121
        return $template;
122
    }
123
124
    /**
125
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null|string? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
126
     */
127
    public function getFormType()
128
    {
129
        return $this->getFormConfiguration('type');
130
    }
131
132
    /**
133
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null|string? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
134
     */
135
    public function getFormOptions()
136
    {
137
        return $this->getFormConfiguration('options');
138
    }
139
140
    /**
141
     * @param $name
142
     *
143
     * @return string
144
     */
145
    public function getRouteName($name)
146
    {
147
        $sectionPrefix = $this->getSection() ? $this->getSection().'_' : '';
148
149
        return sprintf('%s_%s%s_%s', $this->metadata->getApplicationName(), $sectionPrefix, $this->metadata->getName(), $name);
150
    }
151
152
    /**
153
     * @param $name
154
     *
155
     * @return mixed|null|string
156
     */
157
    public function getRedirectRoute($name)
158
    {
159
        $redirect = $this->parameters->get('redirect');
160
161
        if (null === $redirect) {
162
            return $this->getRouteName($name);
163
        }
164
165
        if (is_array($redirect)) {
166
            if (!empty($redirect['referer'])) {
167
                return 'referer';
168
            }
169
170
            return $redirect['route'];
171
        }
172
173
        return $redirect;
174
    }
175
176
    /**
177
     * Get url hash fragment (#text) which is you configured.
178
     *
179
     * @return null|string
180
     */
181
    public function getRedirectHash()
182
    {
183
        $redirect = $this->parameters->get('redirect');
184
185
        if (!is_array($redirect) || empty($redirect['hash'])) {
186
            return null;
187
        }
188
189
        return '#'.$redirect['hash'];
190
    }
191
192
    /**
193
     * Get redirect referer, This will detected by configuration
194
     * If not exists, The `referrer` from headers will be used.
195
     *
196
     * @return null|string
197
     */
198
    public function getRedirectReferer()
199
    {
200
        $redirect = $this->parameters->get('redirect');
201
        $referer = $this->request->headers->get('referer');
202
203
        if (!is_array($redirect) || empty($redirect['referer'])) {
204
            return $referer;
205
        }
206
207
        if ($redirect['referer'] === true) {
208
            return $referer;
209
        }
210
211
        return $redirect['referer'];
212
    }
213
214
    /**
215
     * @param object|null $resource
216
     *
217
     * @return array
218
     */
219
    public function getRedirectParameters($resource = null)
220
    {
221
        $redirect = $this->parameters->get('redirect');
222
223
        if ($this->areParametersIntentionallyEmptyArray($redirect)) {
224
            return [];
225
        }
226
227
        if (!is_array($redirect)) {
228
            $redirect = ['parameters' => []];
229
        }
230
231
        $parameters = isset($redirect['parameters']) ? $redirect['parameters'] : [];
232
233
        if (null !== $resource) {
234
            $parameters = $this->parseResourceValues($parameters, $resource);
235
        }
236
237
        return $parameters;
238
    }
239
240
    /**
241
     * @return bool
242
     */
243
    public function isLimited()
244
    {
245
        return (bool) $this->parameters->get('limit', false);
246
    }
247
248
    /**
249
     * @return int|null
250
     */
251
    public function getLimit()
252
    {
253
        $limit = null;
254
255
        if ($this->isLimited()) {
256
            $limit = (int) $this->parameters->get('limit', 10);
257
        }
258
259
        return $limit;
260
    }
261
262
    /**
263
     * @return bool
264
     */
265
    public function isPaginated()
266
    {
267
        return (bool) $this->parameters->get('paginate', true);
268
    }
269
270
    /**
271
     * @return int
272
     */
273
    public function getPaginationMaxPerPage()
274
    {
275
        return (int) $this->parameters->get('paginate', 10);
276
    }
277
278
    /**
279
     * @return bool
280
     */
281
    public function isFilterable()
282
    {
283
        return (bool) $this->parameters->get('filterable', false);
284
    }
285
286
    /**
287
     * @param array $criteria
288
     *
289
     * @return array
290
     */
291
    public function getCriteria(array $criteria = [])
292
    {
293
        $defaultCriteria = array_merge($this->parameters->get('criteria', []), $criteria);
294
295
        if ($this->isFilterable()) {
296
            return $this->getRequestParameter('criteria', $defaultCriteria);
297
        }
298
299
        return $defaultCriteria;
300
    }
301
302
    /**
303
     * @return bool
304
     */
305
    public function isSortable()
306
    {
307
        return (bool) $this->parameters->get('sortable', false);
308
    }
309
310
    /**
311
     * @param array $sorting
312
     *
313
     * @return array
314
     */
315
    public function getSorting(array $sorting = [])
316
    {
317
        $defaultSorting = array_merge($this->parameters->get('sorting', []), $sorting);
318
319
        if ($this->isSortable()) {
320
            $sorting = $this->getRequestParameter('sorting');
321
            foreach ($defaultSorting as $key => $value) {
322
                if (!isset($sorting[$key])) {
323
                    $sorting[$key] = $value;
324
                }
325
            }
326
327
            return $sorting;
328
        }
329
330
        return $defaultSorting;
331
    }
332
333
    /**
334
     * @param $parameter
335
     * @param array $defaults
336
     *
337
     * @return array
338
     */
339
    public function getRequestParameter($parameter, $defaults = [])
340
    {
341
        return array_replace_recursive(
342
            $defaults,
343
            $this->request->get($parameter, [])
344
        );
345
    }
346
347
    /**
348
     * @return string|null
349
     */
350
    public function getRepositoryMethod()
351
    {
352
        if (!$this->parameters->has('repository')) {
353
            return null;
354
        }
355
356
        $repository = $this->parameters->get('repository');
357
358
        return is_array($repository) ? $repository['method'] : $repository;
359
    }
360
361
    /**
362
     * @return array
363
     */
364
    public function getRepositoryArguments()
365
    {
366
        if (!$this->parameters->has('repository')) {
367
            return [];
368
        }
369
370
        $repository = $this->parameters->get('repository');
371
372
        if (!isset($repository['arguments'])) {
373
            return [];
374
        }
375
376
        return is_array($repository['arguments']) ? $repository['arguments'] : [$repository['arguments']];
377
    }
378
379
    /**
380
     * @return string|null
381
     */
382
    public function getFactoryMethod()
383
    {
384
        if (!$this->parameters->has('factory')) {
385
            return null;
386
        }
387
388
        $factory = $this->parameters->get('factory');
389
390
        return is_array($factory) ? $factory['method'] : $factory;
391
    }
392
393
    /**
394
     * @return array
395
     */
396
    public function getFactoryArguments()
397
    {
398
        if (!$this->parameters->has('factory')) {
399
            return [];
400
        }
401
402
        $factory = $this->parameters->get('factory');
403
404
        if (!isset($factory['arguments'])) {
405
            return [];
406
        }
407
408
        return is_array($factory['arguments']) ? $factory['arguments'] : [$factory['arguments']];
409
    }
410
411
    /**
412
     * @param null $message
413
     *
414
     * @return mixed|null
415
     */
416
    public function getFlashMessage($message)
417
    {
418
        return $this->parameters->get('flash', sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $message));
419
    }
420
421
    /**
422
     * @return mixed|null
423
     */
424
    public function getSortablePosition()
425
    {
426
        return $this->parameters->get('sortable_position', 'position');
427
    }
428
429
    /**
430
     * @return mixed|null
431
     */
432
    public function getSerializationGroups()
433
    {
434
        return $this->parameters->get('serialization_groups', []);
435
    }
436
437
    /**
438
     * @return mixed|null
439
     */
440
    public function getSerializationVersion()
441
    {
442
        return $this->parameters->get('serialization_version');
443
    }
444
445
    /**
446
     * @return string|null
447
     */
448
    public function getEvent()
449
    {
450
        return $this->parameters->get('event');
451
    }
452
453
    /**
454
     * @return bool
455
     */
456
    public function hasPermission()
457
    {
458
        return false !== $this->parameters->get('permission', false);
459
    }
460
461
    /**
462
     * @param string $name
463
     *
464
     * @return string
465
     *
466
     * @throws \LogicException
467
     */
468
    public function getPermission($name)
469
    {
470
        $permission = $this->parameters->get('permission');
471
472
        if (null === $permission) {
473
            throw new \LogicException('Current action does not require any authorization.');
474
        }
475
476
        if (true === $permission) {
477
            return sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $name);
478
        }
479
480
        return $permission;
481
    }
482
483
    /**
484
     * @return bool
485
     */
486
    public function isHeaderRedirection()
487
    {
488
        $redirect = $this->parameters->get('redirect');
489
490
        if (!is_array($redirect) || !isset($redirect['header'])) {
491
            return false;
492
        }
493
494
        if ('xhr' === $redirect['header']) {
495
            return $this->getRequest()->isXmlHttpRequest();
496
        }
497
498
        return (bool) $redirect['header'];
499
    }
500
501
    public function getVars()
502
    {
503
        return $this->parameters->get('vars', []);
504
    }
505
506
    /**
507
     * @param array  $parameters
508
     * @param object $resource
509
     *
510
     * @return array
511
     */
512
    private function parseResourceValues(array $parameters, $resource)
513
    {
514
        $accessor = PropertyAccess::createPropertyAccessor();
515
516
        if (empty($parameters)) {
517
            return ['id' => $accessor->getValue($resource, 'id')];
518
        }
519
520
        foreach ($parameters as $key => $value) {
521
            if (is_array($value)) {
522
                $parameters[$key] = $this->parseResourceValues($value, $resource);
523
            }
524
525
            if (is_string($value) && 0 === strpos($value, 'resource.')) {
526
                $parameters[$key] = $accessor->getValue($resource, substr($value, 9));
527
            }
528
        }
529
530
        return $parameters;
531
    }
532
533
    /**
534
     * @return bool
535
     */
536
    public function hasGrid()
537
    {
538
        return $this->parameters->has('grid');
539
    }
540
541
    /**
542
     * @return string
543
     *
544
     * @throws \LogicException
545
     */
546
    public function getGrid()
547
    {
548
        if (!$this->hasGrid()) {
549
            throw new \LogicException('Current action does not use grid.');
550
        }
551
552
        return $this->parameters->get('grid');
553
    }
554
555
    /**
556
     * @return bool
557
     */
558
    public function hasStateMachine()
559
    {
560
        return $this->parameters->has('state_machine');
561
    }
562
563
    /**
564
     * @return string
565
     */
566
    public function getStateMachineGraph()
567
    {
568
        $options = $this->parameters->get('state_machine');
569
570
        return isset($options['graph']) ? $options['graph'] : null;
571
    }
572
573
    /**
574
     * @return string
575
     */
576
    public function getStateMachineTransition()
577
    {
578
        $options = $this->parameters->get('state_machine');
579
580
        return isset($options['transition']) ? $options['transition'] : null;
581
    }
582
583
    /**
584
     * @param mixed $redirect
585
     *
586
     * @return bool
587
     */
588
    private function areParametersIntentionallyEmptyArray($redirect)
0 ignored issues
show
Coding Style introduced by
function areParametersIntentionallyEmptyArray() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
589
    {
590
        return isset($redirect['parameters']) && is_array($redirect['parameters']) && empty($redirect['parameters']);
591
    }
592
593
    /**
594
     * @param string $option
595
     *
596
     * @return array|null|string
597
     */
598
    private function getFormConfiguration($option)
599
    {
600
        $form = $this->parameters->get('form');
601
        if (null !== $form) {
602
            if (is_array($form) && isset($form[$option])) {
603
                return $form[$option];
604
            }
605
606
            if (is_string($form) && 'type' === $option) {
607
                return $form;
608
            }
609
        }
610
611
        if ('type' === $option) {
612
            $form = $this->metadata->getClass('form');
613
            if (is_string($form)) {
614
                return $form;
615
            }
616
617
            return sprintf('%s_%s', $this->metadata->getApplicationName(), $this->metadata->getName());
618
        } elseif ('options' === $option) {
619
            return [];
620
        }
621
622
        return null;
623
    }
624
}
625