Completed
Push — 1.0-coding-standard-2-header ( 51fb9c...ba11a9 )
by Kamil
20:46
created

RequestConfiguration::getRedirectParameters()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
c 0
b 0
f 0
rs 9.0534
cc 4
eloc 11
nc 5
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
declare(strict_types=1);
13
14
namespace Sylius\Bundle\ResourceBundle\Controller;
15
16
use Sylius\Component\Resource\Metadata\MetadataInterface;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\PropertyAccess\PropertyAccess;
19
20
/**
21
 * @author Paweł Jędrzejewski <[email protected]>
22
 * @author Saša Stamenković <[email protected]>
23
 * @author Gustavo Perdomo <[email protected]>
24
 */
25
class RequestConfiguration
26
{
27
    /**
28
     * @var Request
29
     */
30
    private $request;
31
32
    /**
33
     * @var MetadataInterface
34
     */
35
    private $metadata;
36
37
    /**
38
     * @var Parameters
39
     */
40
    private $parameters;
41
42
    /**
43
     * @param MetadataInterface $metadata
44
     * @param Request $request
45
     * @param Parameters $parameters
46
     */
47
    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...
48
    {
49
        $this->metadata = $metadata;
50
        $this->request = $request;
51
        $this->parameters = $parameters;
52
    }
53
54
    /**
55
     * @return Request
56
     */
57
    public function getRequest()
58
    {
59
        return $this->request;
60
    }
61
62
    /**
63
     * @return MetadataInterface
64
     */
65
    public function getMetadata()
66
    {
67
        return $this->metadata;
68
    }
69
70
    /**
71
     * @return Parameters
72
     */
73
    public function getParameters()
74
    {
75
        return $this->parameters;
76
    }
77
78
    /**
79
     * @return string|null
80
     */
81
    public function getSection()
82
    {
83
        return $this->parameters->get('section');
84
    }
85
86
    /**
87
     * @return bool
88
     */
89
    public function isHtmlRequest()
90
    {
91
        return 'html' === $this->request->getRequestFormat();
92
    }
93
94
    /**
95
     * @param $name
96
     *
97
     * @return string|null
98
     */
99
    public function getDefaultTemplate($name)
100
    {
101
        $templatesNamespace = (string) $this->metadata->getTemplatesNamespace();
102
103
        if (false !== strpos($templatesNamespace, ':')) {
104
            return sprintf('%s:%s.%s', $templatesNamespace ?: ':', $name, 'twig');
105
        }
106
107
        return sprintf('%s/%s.%s', $templatesNamespace, $name, 'twig');
108
    }
109
110
    /**
111
     * @param $name
112
     *
113
     * @return mixed|null
114
     */
115
    public function getTemplate($name)
116
    {
117
        $template = $this->parameters->get('template', $this->getDefaultTemplate($name));
118
119
        if (null === $template) {
120
            throw new \RuntimeException(sprintf('Could not resolve template for resource "%s".', $this->metadata->getAlias()));
121
        }
122
123
        return $template;
124
    }
125
126
    /**
127
     * @return string|null
128
     */
129
    public function getFormType()
130
    {
131
        $form = $this->parameters->get('form');
132
        if (isset($form['type'])) {
133
            return $form['type'];
134
        }
135
136
        if (is_string($form)) {
137
            return $form;
138
        }
139
140
        $form = $this->metadata->getClass('form');
141
        if (is_string($form)) {
142
            return $form;
143
        }
144
145
        return sprintf('%s_%s', $this->metadata->getApplicationName(), $this->metadata->getName());
146
    }
147
148
    /**
149
     * @return array
150
     */
151
    public function getFormOptions()
152
    {
153
        $form = $this->parameters->get('form');
154
        if (isset($form['options'])) {
155
            return $form['options'];
156
        }
157
158
        return [];
159
    }
160
161
    /**
162
     * @param $name
163
     *
164
     * @return string
165
     */
166
    public function getRouteName($name)
167
    {
168
        $sectionPrefix = $this->getSection() ? $this->getSection() . '_' : '';
169
170
        return sprintf('%s_%s%s_%s', $this->metadata->getApplicationName(), $sectionPrefix, $this->metadata->getName(), $name);
171
    }
172
173
    /**
174
     * @param $name
175
     *
176
     * @return mixed|string|null
177
     */
178
    public function getRedirectRoute($name)
179
    {
180
        $redirect = $this->parameters->get('redirect');
181
182
        if (null === $redirect) {
183
            return $this->getRouteName($name);
184
        }
185
186
        if (is_array($redirect)) {
187
            if (!empty($redirect['referer'])) {
188
                return 'referer';
189
            }
190
191
            return $redirect['route'];
192
        }
193
194
        return $redirect;
195
    }
196
197
    /**
198
     * Get url hash fragment (#text) which is you configured.
199
     *
200
     * @return string
201
     */
202
    public function getRedirectHash()
203
    {
204
        $redirect = $this->parameters->get('redirect');
205
206
        if (!is_array($redirect) || empty($redirect['hash'])) {
207
            return '';
208
        }
209
210
        return '#' . $redirect['hash'];
211
    }
212
213
    /**
214
     * Get redirect referer, This will detected by configuration
215
     * If not exists, The `referrer` from headers will be used.
216
     *
217
     * @return string
218
     */
219
    public function getRedirectReferer()
220
    {
221
        $redirect = $this->parameters->get('redirect');
222
        $referer = $this->request->headers->get('referer');
223
224
        if (!is_array($redirect) || empty($redirect['referer'])) {
225
            return $referer;
226
        }
227
228
        if ($redirect['referer'] === true) {
229
            return $referer;
230
        }
231
232
        return $redirect['referer'];
233
    }
234
235
    /**
236
     * @param object|null $resource
237
     *
238
     * @return array
239
     */
240
    public function getRedirectParameters($resource = null)
241
    {
242
        $redirect = $this->parameters->get('redirect');
243
244
        if ($this->areParametersIntentionallyEmptyArray($redirect)) {
245
            return [];
246
        }
247
248
        if (!is_array($redirect)) {
249
            $redirect = ['parameters' => []];
250
        }
251
252
        $parameters = $redirect['parameters'] ?? [];
253
        $parameters = $this->addExtraRedirectParameters($parameters);
254
255
        if (null !== $resource) {
256
            $parameters = $this->parseResourceValues($parameters, $resource);
257
        }
258
259
        return $parameters;
260
    }
261
262
    /**
263
     * @param array $parameters
264
     *
265
     * @return array
266
     */
267
    private function addExtraRedirectParameters($parameters)
268
    {
269
        $vars = $this->getVars();
270
        $accessor = PropertyAccess::createPropertyAccessor();
271
272
        if ($accessor->isReadable($vars, '[redirect][parameters]')) {
273
            $extraParameters = $accessor->getValue($vars, '[redirect][parameters]');
274
275
            if (is_array($extraParameters)) {
276
                $parameters = array_merge($parameters, $extraParameters);
277
            }
278
        }
279
280
        return $parameters;
281
    }
282
283
    /**
284
     * @return bool
285
     */
286
    public function isLimited()
287
    {
288
        return (bool) $this->parameters->get('limit', false);
289
    }
290
291
    /**
292
     * @return int|null
293
     */
294
    public function getLimit()
295
    {
296
        $limit = null;
297
298
        if ($this->isLimited()) {
299
            $limit = (int) $this->parameters->get('limit', 10);
300
        }
301
302
        return $limit;
303
    }
304
305
    /**
306
     * @return bool
307
     */
308
    public function isPaginated()
309
    {
310
        $pagination = $this->parameters->get('paginate', true);
311
312
        return $pagination !== false && $pagination !== null;
313
    }
314
315
    /**
316
     * @return int
317
     */
318
    public function getPaginationMaxPerPage()
319
    {
320
        return (int) $this->parameters->get('paginate', 10);
321
    }
322
323
    /**
324
     * @return bool
325
     */
326
    public function isFilterable()
327
    {
328
        return (bool) $this->parameters->get('filterable', false);
329
    }
330
331
    /**
332
     * @param array $criteria
333
     *
334
     * @return array
335
     */
336
    public function getCriteria(array $criteria = [])
337
    {
338
        $defaultCriteria = array_merge($this->parameters->get('criteria', []), $criteria);
339
340
        if ($this->isFilterable()) {
341
            return $this->getRequestParameter('criteria', $defaultCriteria);
342
        }
343
344
        return $defaultCriteria;
345
    }
346
347
    /**
348
     * @return bool
349
     */
350
    public function isSortable()
351
    {
352
        return (bool) $this->parameters->get('sortable', false);
353
    }
354
355
    /**
356
     * @param array $sorting
357
     *
358
     * @return array
359
     */
360
    public function getSorting(array $sorting = [])
361
    {
362
        $defaultSorting = array_merge($this->parameters->get('sorting', []), $sorting);
363
364
        if ($this->isSortable()) {
365
            $sorting = $this->getRequestParameter('sorting');
366
            foreach ($defaultSorting as $key => $value) {
367
                if (!isset($sorting[$key])) {
368
                    $sorting[$key] = $value;
369
                }
370
            }
371
372
            return $sorting;
373
        }
374
375
        return $defaultSorting;
376
    }
377
378
    /**
379
     * @param $parameter
380
     * @param array $defaults
381
     *
382
     * @return array
383
     */
384
    public function getRequestParameter($parameter, $defaults = [])
385
    {
386
        return array_replace_recursive(
387
            $defaults,
388
            $this->request->get($parameter, [])
389
        );
390
    }
391
392
    /**
393
     * @return string|null
394
     */
395
    public function getRepositoryMethod()
396
    {
397
        if (!$this->parameters->has('repository')) {
398
            return null;
399
        }
400
401
        $repository = $this->parameters->get('repository');
402
403
        return is_array($repository) ? $repository['method'] : $repository;
404
    }
405
406
    /**
407
     * @return array
408
     */
409
    public function getRepositoryArguments()
410
    {
411
        if (!$this->parameters->has('repository')) {
412
            return [];
413
        }
414
415
        $repository = $this->parameters->get('repository');
416
417
        if (!isset($repository['arguments'])) {
418
            return [];
419
        }
420
421
        return is_array($repository['arguments']) ? $repository['arguments'] : [$repository['arguments']];
422
    }
423
424
    /**
425
     * @return string|null
426
     */
427
    public function getFactoryMethod()
428
    {
429
        if (!$this->parameters->has('factory')) {
430
            return null;
431
        }
432
433
        $factory = $this->parameters->get('factory');
434
435
        return is_array($factory) ? $factory['method'] : $factory;
436
    }
437
438
    /**
439
     * @return array
440
     */
441
    public function getFactoryArguments()
442
    {
443
        if (!$this->parameters->has('factory')) {
444
            return [];
445
        }
446
447
        $factory = $this->parameters->get('factory');
448
449
        if (!isset($factory['arguments'])) {
450
            return [];
451
        }
452
453
        return is_array($factory['arguments']) ? $factory['arguments'] : [$factory['arguments']];
454
    }
455
456
    /**
457
     * @param null $message
458
     *
459
     * @return mixed|null
460
     */
461
    public function getFlashMessage($message)
462
    {
463
        return $this->parameters->get('flash', sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $message));
464
    }
465
466
    /**
467
     * @return mixed|null
468
     */
469
    public function getSortablePosition()
470
    {
471
        return $this->parameters->get('sortable_position', 'position');
472
    }
473
474
    /**
475
     * @return mixed|null
476
     */
477
    public function getSerializationGroups()
478
    {
479
        return $this->parameters->get('serialization_groups', []);
480
    }
481
482
    /**
483
     * @return mixed|null
484
     */
485
    public function getSerializationVersion()
486
    {
487
        return $this->parameters->get('serialization_version');
488
    }
489
490
    /**
491
     * @return string|null
492
     */
493
    public function getEvent()
494
    {
495
        return $this->parameters->get('event');
496
    }
497
498
    /**
499
     * @return bool
500
     */
501
    public function hasPermission()
502
    {
503
        return false !== $this->parameters->get('permission', false);
504
    }
505
506
    /**
507
     * @param string $name
508
     *
509
     * @return string
510
     *
511
     * @throws \LogicException
512
     */
513
    public function getPermission($name)
514
    {
515
        $permission = $this->parameters->get('permission');
516
517
        if (null === $permission) {
518
            throw new \LogicException('Current action does not require any authorization.');
519
        }
520
521
        if (true === $permission) {
522
            return sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $name);
523
        }
524
525
        return $permission;
526
    }
527
528
    /**
529
     * @return bool
530
     */
531
    public function isHeaderRedirection()
532
    {
533
        $redirect = $this->parameters->get('redirect');
534
535
        if (!is_array($redirect) || !isset($redirect['header'])) {
536
            return false;
537
        }
538
539
        if ('xhr' === $redirect['header']) {
540
            return $this->getRequest()->isXmlHttpRequest();
541
        }
542
543
        return (bool) $redirect['header'];
544
    }
545
546
    public function getVars()
547
    {
548
        return $this->parameters->get('vars', []);
549
    }
550
551
    /**
552
     * @param array  $parameters
553
     * @param object $resource
554
     *
555
     * @return array
556
     */
557
    private function parseResourceValues(array $parameters, $resource)
558
    {
559
        $accessor = PropertyAccess::createPropertyAccessor();
560
561
        if (empty($parameters)) {
562
            return ['id' => $accessor->getValue($resource, 'id')];
563
        }
564
565
        foreach ($parameters as $key => $value) {
566
            if (is_array($value)) {
567
                $parameters[$key] = $this->parseResourceValues($value, $resource);
568
            }
569
570
            if (is_string($value) && 0 === strpos($value, 'resource.')) {
571
                $parameters[$key] = $accessor->getValue($resource, substr($value, 9));
572
            }
573
        }
574
575
        return $parameters;
576
    }
577
578
    /**
579
     * @return bool
580
     */
581
    public function hasGrid()
582
    {
583
        return $this->parameters->has('grid');
584
    }
585
586
    /**
587
     * @return string
588
     *
589
     * @throws \LogicException
590
     */
591
    public function getGrid()
592
    {
593
        if (!$this->hasGrid()) {
594
            throw new \LogicException('Current action does not use grid.');
595
        }
596
597
        return $this->parameters->get('grid');
598
    }
599
600
    /**
601
     * @return bool
602
     */
603
    public function hasStateMachine()
604
    {
605
        return $this->parameters->has('state_machine');
606
    }
607
608
    /**
609
     * @return string
610
     */
611
    public function getStateMachineGraph()
612
    {
613
        $options = $this->parameters->get('state_machine');
614
615
        return $options['graph'] ?? null;
616
    }
617
618
    /**
619
     * @return string
620
     */
621
    public function getStateMachineTransition()
622
    {
623
        $options = $this->parameters->get('state_machine');
624
625
        return $options['transition'] ?? null;
626
    }
627
628
    /**
629
     * @return bool
630
     */
631
    public function isCsrfProtectionEnabled()
632
    {
633
        return $this->parameters->get('csrf_protection', true);
634
    }
635
636
    /**
637
     * @param mixed $redirect
638
     *
639
     * @return bool
640
     */
641
    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...
642
    {
643
        return isset($redirect['parameters']) && is_array($redirect['parameters']) && empty($redirect['parameters']);
644
    }
645
}
646