Completed
Push — symfony3-core ( 6ddaba...73f033 )
by Kamil
60:25 queued 41:49
created

RequestConfiguration::isCsrfProtectionEnabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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