Completed
Push — symfony3-fqcn-sylius ( 26083b...02605f )
by Kamil
20:07
created

RequestConfiguration::getFormConfiguration()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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