Completed
Push — scalar-types/currency ( d4a290...08e1db )
by Kamil
25:05 queued 02:52
created

RequestConfiguration::getSorting()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.2
c 0
b 0
f 0
nc 4
cc 4
eloc 9
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 null|string
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|null|string
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 = isset($redirect['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
        return (bool) $this->parameters->get('paginate', true);
311
    }
312
313
    /**
314
     * @return int
315
     */
316
    public function getPaginationMaxPerPage()
317
    {
318
        return (int) $this->parameters->get('paginate', 10);
319
    }
320
321
    /**
322
     * @return bool
323
     */
324
    public function isFilterable()
325
    {
326
        return (bool) $this->parameters->get('filterable', false);
327
    }
328
329
    /**
330
     * @param array $criteria
331
     *
332
     * @return array
333
     */
334
    public function getCriteria(array $criteria = [])
335
    {
336
        $defaultCriteria = array_merge($this->parameters->get('criteria', []), $criteria);
337
338
        if ($this->isFilterable()) {
339
            return $this->getRequestParameter('criteria', $defaultCriteria);
340
        }
341
342
        return $defaultCriteria;
343
    }
344
345
    /**
346
     * @return bool
347
     */
348
    public function isSortable()
349
    {
350
        return (bool) $this->parameters->get('sortable', false);
351
    }
352
353
    /**
354
     * @param array $sorting
355
     *
356
     * @return array
357
     */
358
    public function getSorting(array $sorting = [])
359
    {
360
        $defaultSorting = array_merge($this->parameters->get('sorting', []), $sorting);
361
362
        if ($this->isSortable()) {
363
            $sorting = $this->getRequestParameter('sorting');
364
            foreach ($defaultSorting as $key => $value) {
365
                if (!isset($sorting[$key])) {
366
                    $sorting[$key] = $value;
367
                }
368
            }
369
370
            return $sorting;
371
        }
372
373
        return $defaultSorting;
374
    }
375
376
    /**
377
     * @param $parameter
378
     * @param array $defaults
379
     *
380
     * @return array
381
     */
382
    public function getRequestParameter($parameter, $defaults = [])
383
    {
384
        return array_replace_recursive(
385
            $defaults,
386
            $this->request->get($parameter, [])
387
        );
388
    }
389
390
    /**
391
     * @return string|null
392
     */
393
    public function getRepositoryMethod()
394
    {
395
        if (!$this->parameters->has('repository')) {
396
            return null;
397
        }
398
399
        $repository = $this->parameters->get('repository');
400
401
        return is_array($repository) ? $repository['method'] : $repository;
402
    }
403
404
    /**
405
     * @return array
406
     */
407
    public function getRepositoryArguments()
408
    {
409
        if (!$this->parameters->has('repository')) {
410
            return [];
411
        }
412
413
        $repository = $this->parameters->get('repository');
414
415
        if (!isset($repository['arguments'])) {
416
            return [];
417
        }
418
419
        return is_array($repository['arguments']) ? $repository['arguments'] : [$repository['arguments']];
420
    }
421
422
    /**
423
     * @return string|null
424
     */
425
    public function getFactoryMethod()
426
    {
427
        if (!$this->parameters->has('factory')) {
428
            return null;
429
        }
430
431
        $factory = $this->parameters->get('factory');
432
433
        return is_array($factory) ? $factory['method'] : $factory;
434
    }
435
436
    /**
437
     * @return array
438
     */
439
    public function getFactoryArguments()
440
    {
441
        if (!$this->parameters->has('factory')) {
442
            return [];
443
        }
444
445
        $factory = $this->parameters->get('factory');
446
447
        if (!isset($factory['arguments'])) {
448
            return [];
449
        }
450
451
        return is_array($factory['arguments']) ? $factory['arguments'] : [$factory['arguments']];
452
    }
453
454
    /**
455
     * @param null $message
456
     *
457
     * @return mixed|null
458
     */
459
    public function getFlashMessage($message)
460
    {
461
        return $this->parameters->get('flash', sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $message));
462
    }
463
464
    /**
465
     * @return mixed|null
466
     */
467
    public function getSortablePosition()
468
    {
469
        return $this->parameters->get('sortable_position', 'position');
470
    }
471
472
    /**
473
     * @return mixed|null
474
     */
475
    public function getSerializationGroups()
476
    {
477
        return $this->parameters->get('serialization_groups', []);
478
    }
479
480
    /**
481
     * @return mixed|null
482
     */
483
    public function getSerializationVersion()
484
    {
485
        return $this->parameters->get('serialization_version');
486
    }
487
488
    /**
489
     * @return string|null
490
     */
491
    public function getEvent()
492
    {
493
        return $this->parameters->get('event');
494
    }
495
496
    /**
497
     * @return bool
498
     */
499
    public function hasPermission()
500
    {
501
        return false !== $this->parameters->get('permission', false);
502
    }
503
504
    /**
505
     * @param string $name
506
     *
507
     * @return string
508
     *
509
     * @throws \LogicException
510
     */
511
    public function getPermission($name)
512
    {
513
        $permission = $this->parameters->get('permission');
514
515
        if (null === $permission) {
516
            throw new \LogicException('Current action does not require any authorization.');
517
        }
518
519
        if (true === $permission) {
520
            return sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $name);
521
        }
522
523
        return $permission;
524
    }
525
526
    /**
527
     * @return bool
528
     */
529
    public function isHeaderRedirection()
530
    {
531
        $redirect = $this->parameters->get('redirect');
532
533
        if (!is_array($redirect) || !isset($redirect['header'])) {
534
            return false;
535
        }
536
537
        if ('xhr' === $redirect['header']) {
538
            return $this->getRequest()->isXmlHttpRequest();
539
        }
540
541
        return (bool) $redirect['header'];
542
    }
543
544
    public function getVars()
545
    {
546
        return $this->parameters->get('vars', []);
547
    }
548
549
    /**
550
     * @param array  $parameters
551
     * @param object $resource
552
     *
553
     * @return array
554
     */
555
    private function parseResourceValues(array $parameters, $resource)
556
    {
557
        $accessor = PropertyAccess::createPropertyAccessor();
558
559
        if (empty($parameters)) {
560
            return ['id' => $accessor->getValue($resource, 'id')];
561
        }
562
563
        foreach ($parameters as $key => $value) {
564
            if (is_array($value)) {
565
                $parameters[$key] = $this->parseResourceValues($value, $resource);
566
            }
567
568
            if (is_string($value) && 0 === strpos($value, 'resource.')) {
569
                $parameters[$key] = $accessor->getValue($resource, substr($value, 9));
570
            }
571
        }
572
573
        return $parameters;
574
    }
575
576
    /**
577
     * @return bool
578
     */
579
    public function hasGrid()
580
    {
581
        return $this->parameters->has('grid');
582
    }
583
584
    /**
585
     * @return string
586
     *
587
     * @throws \LogicException
588
     */
589
    public function getGrid()
590
    {
591
        if (!$this->hasGrid()) {
592
            throw new \LogicException('Current action does not use grid.');
593
        }
594
595
        return $this->parameters->get('grid');
596
    }
597
598
    /**
599
     * @return bool
600
     */
601
    public function hasStateMachine()
602
    {
603
        return $this->parameters->has('state_machine');
604
    }
605
606
    /**
607
     * @return string
608
     */
609
    public function getStateMachineGraph()
610
    {
611
        $options = $this->parameters->get('state_machine');
612
613
        return isset($options['graph']) ? $options['graph'] : null;
614
    }
615
616
    /**
617
     * @return string
618
     */
619
    public function getStateMachineTransition()
620
    {
621
        $options = $this->parameters->get('state_machine');
622
623
        return isset($options['transition']) ? $options['transition'] : null;
624
    }
625
626
    /**
627
     * @return bool
628
     */
629
    public function isCsrfProtectionEnabled()
630
    {
631
        return $this->parameters->get('csrf_protection', true);
632
    }
633
634
    /**
635
     * @param mixed $redirect
636
     *
637
     * @return bool
638
     */
639
    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...
640
    {
641
        return isset($redirect['parameters']) && is_array($redirect['parameters']) && empty($redirect['parameters']);
642
    }
643
}
644