Completed
Push — master ( 994ba8...dbff07 )
by Kamil
19:19
created

RequestConfiguration::getEvent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
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
 * Resource controller configuration.
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
    protected $request;
31
32
    /**
33
     * @var MetadataInterface
34
     */
35
    protected $metadata;
36
37
    /**
38
     * @var Parameters
39
     */
40
    protected $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
        return sprintf('%s:%s.%s', $this->metadata->getTemplatesNamespace() ?: ':', $name, 'twig');
102
    }
103
104
    /**
105
     * @param $name
106
     *
107
     * @return mixed|null
108
     */
109
    public function getTemplate($name)
110
    {
111
        $template = $this->parameters->get('template', $this->getDefaultTemplate($name));
112
113
        if (null === $template) {
114
            throw new \RuntimeException(sprintf('Could not resolve template for resource "%s".', $this->metadata->getAlias()));
115
        }
116
117
        return $template;
118
    }
119
120
    /**
121
     * @return mixed|null
122
     */
123
    public function getFormType()
124
    {
125
        $form = $this->parameters->get('form', sprintf('%s_%s', $this->metadata->getApplicationName(), $this->metadata->getName()));
126
127
        if (is_array($form) && array_key_exists('type', $form)) {
128
            return $form['type'];
129
        }
130
131
        return $form;
132
    }
133
134
    /**
135
     * @return mixed|null
136
     */
137
    public function getFormOptions()
138
    {
139
        $form = $this->parameters->get('form', sprintf('%s_%s', $this->metadata->getApplicationName(), $this->metadata->getName()));
140
141
        if (is_array($form) && array_key_exists('options', $form)) {
142
            return $form['options'];
143
        }
144
145
        return [];
146
    }
147
148
    /**
149
     * @param $name
150
     *
151
     * @return string
152
     */
153
    public function getRouteName($name)
154
    {
155
        $sectionPrefix = $this->getSection() ? $this->getSection().'_' : '';
156
157
        return sprintf('%s_%s%s_%s', $this->metadata->getApplicationName(), $sectionPrefix, $this->metadata->getName(), $name);
158
    }
159
160
    /**
161
     * @param $name
162
     *
163
     * @return mixed|null|string
164
     */
165
    public function getRedirectRoute($name)
166
    {
167
        $redirect = $this->parameters->get('redirect');
168
169
        if (null === $redirect) {
170
            return $this->getRouteName($name);
171
        }
172
173
        if (is_array($redirect)) {
174
            if (!empty($redirect['referer'])) {
175
                return 'referer';
176
            }
177
178
            return $redirect['route'];
179
        }
180
181
        return $redirect;
182
    }
183
184
    /**
185
     * Get url hash fragment (#text) which is you configured.
186
     *
187
     * @return null|string
188
     */
189
    public function getRedirectHash()
190
    {
191
        $redirect = $this->parameters->get('redirect');
192
193
        if (!is_array($redirect) || empty($redirect['hash'])) {
194
            return null;
195
        }
196
197
        return '#'.$redirect['hash'];
198
    }
199
200
    /**
201
     * Get redirect referer, This will detected by configuration
202
     * If not exists, The `referrer` from headers will be used.
203
     *
204
     * @return null|string
205
     */
206
    public function getRedirectReferer()
207
    {
208
        $redirect = $this->parameters->get('redirect');
209
        $referer = $this->request->headers->get('referer');
210
211
        if (!is_array($redirect) || empty($redirect['referer'])) {
212
            return $referer;
213
        }
214
215
        if ($redirect['referer'] === true) {
216
            return $referer;
217
        }
218
219
        return $redirect['referer'];
220
    }
221
222
    /**
223
     * @param object|null $resource
224
     *
225
     * @return array
226
     */
227
    public function getRedirectParameters($resource = null)
228
    {
229
        $redirect = $this->parameters->get('redirect');
230
231
        if (!is_array($redirect) || empty($redirect['parameters'])) {
232
            $redirect = ['parameters' => []];
233
        }
234
235
        $parameters = $redirect['parameters'];
236
237
        if (null !== $resource) {
238
            $parameters = $this->parseResourceValues($parameters, $resource);
239
        }
240
241
        return $parameters;
242
    }
243
244
    /**
245
     * @return bool
246
     */
247
    public function isLimited()
248
    {
249
        return (bool) $this->parameters->get('limit', false);
250
    }
251
252
    /**
253
     * @return int|null
254
     */
255
    public function getLimit()
256
    {
257
        $limit = null;
258
259
        if ($this->isLimited()) {
260
            $limit = (int) $this->parameters->get('limit', 10);
261
        }
262
263
        return $limit;
264
    }
265
266
    /**
267
     * @return bool
268
     */
269
    public function isPaginated()
270
    {
271
        return (bool) $this->parameters->get('paginate', true);
272
    }
273
274
    /**
275
     * @return int
276
     */
277
    public function getPaginationMaxPerPage()
278
    {
279
        return (int) $this->parameters->get('paginate', 10);
280
    }
281
282
    /**
283
     * @return bool
284
     */
285
    public function isFilterable()
286
    {
287
        return (bool) $this->parameters->get('filterable', false);
288
    }
289
290
    /**
291
     * @param array $criteria
292
     *
293
     * @return array
294
     */
295
    public function getCriteria(array $criteria = [])
296
    {
297
        $defaultCriteria = array_merge($this->parameters->get('criteria', []), $criteria);
298
299
        if ($this->isFilterable()) {
300
            return $this->getRequestParameter('criteria', $defaultCriteria);
301
        }
302
303
        return $defaultCriteria;
304
    }
305
306
    /**
307
     * @return bool
308
     */
309
    public function isSortable()
310
    {
311
        return (bool) $this->parameters->get('sortable', false);
312
    }
313
314
    /**
315
     * @param array $sorting
316
     *
317
     * @return array
318
     */
319
    public function getSorting(array $sorting = [])
320
    {
321
        $defaultSorting = array_merge($this->parameters->get('sorting', []), $sorting);
322
323
        if ($this->isSortable()) {
324
            $sorting = $this->getRequestParameter('sorting');
325
            foreach ($defaultSorting as $key => $value) {
326
                if (!isset($sorting[$key])) {
327
                    $sorting[$key] = $value;
328
                }
329
            }
330
331
            return $sorting;
332
        }
333
334
        return $defaultSorting;
335
    }
336
337
    /**
338
     * @param $parameter
339
     * @param array $defaults
340
     *
341
     * @return array
342
     */
343
    public function getRequestParameter($parameter, $defaults = [])
344
    {
345
        return array_replace_recursive(
346
            $defaults,
347
            $this->request->get($parameter, [])
348
        );
349
    }
350
351
    /**
352
     * @return string|null
353
     */
354
    public function getRepositoryMethod()
355
    {
356
        if (!$this->parameters->has('repository')) {
357
            return null;
358
        }
359
360
        $repository = $this->parameters->get('repository');
361
362
        return is_array($repository) ? $repository['method'] : $repository;
363
    }
364
365
    /**
366
     * @return array
367
     */
368
    public function getRepositoryArguments()
369
    {
370
        if (!$this->parameters->has('repository')) {
371
            return [];
372
        }
373
374
        $repository = $this->parameters->get('repository');
375
376
        if (!isset($repository['arguments'])) {
377
            return [];
378
        }
379
380
        return is_array($repository['arguments']) ? $repository['arguments'] : [$repository['arguments']];
381
    }
382
383
    /**
384
     * @return string|null
385
     */
386
    public function getFactoryMethod()
387
    {
388
        if (!$this->parameters->has('factory')) {
389
            return null;
390
        }
391
392
        $factory = $this->parameters->get('factory');
393
394
        return is_array($factory) ? $factory['method'] : $factory;
395
    }
396
397
    /**
398
     * @return array
399
     */
400
    public function getFactoryArguments()
401
    {
402
        if (!$this->parameters->has('factory')) {
403
            return [];
404
        }
405
406
        $factory = $this->parameters->get('factory');
407
408
        if (!isset($factory['arguments'])) {
409
            return [];
410
        }
411
412
        return is_array($factory['arguments']) ? $factory['arguments'] : [$factory['arguments']];
413
    }
414
415
    /**
416
     * @param null $message
417
     *
418
     * @return mixed|null
419
     */
420
    public function getFlashMessage($message)
421
    {
422
        return $this->parameters->get('flash', sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $message));
423
    }
424
425
    /**
426
     * @return mixed|null
427
     */
428
    public function getSortablePosition()
429
    {
430
        return $this->parameters->get('sortable_position', 'position');
431
    }
432
433
    /**
434
     * @return mixed|null
435
     */
436
    public function getSerializationGroups()
437
    {
438
        return $this->parameters->get('serialization_groups', []);
439
    }
440
441
    /**
442
     * @return mixed|null
443
     */
444
    public function getSerializationVersion()
445
    {
446
        return $this->parameters->get('serialization_version');
447
    }
448
449
    /**
450
     * @return string|null
451
     */
452
    public function getEvent()
453
    {
454
        return $this->parameters->get('event');
455
    }
456
457
    /**
458
     * @return bool
459
     */
460
    public function hasPermission()
461
    {
462
        if (!$this->parameters->has('permission')) {
463
            return true;
464
        }
465
466
        return false !== $this->parameters->get('permission');
467
    }
468
469
    /**
470
     * @param string $name
471
     *
472
     * @return string
473
     *
474
     * @throws \LogicException
475
     */
476
    public function getPermission($name)
477
    {
478
        if (!$this->hasPermission()) {
479
            throw new \LogicException('Current action does not require any authorization.');
480
        }
481
482
        if (!$this->parameters->has('permission')) {
483
            return sprintf('%s.%s.%s', $this->metadata->getApplicationName(), $this->metadata->getName(), $name);
484
        }
485
486
        return $this->parameters->get('permission');
487
    }
488
489
    /**
490
     * @return bool
491
     */
492
    public function isHeaderRedirection()
493
    {
494
        $redirect = $this->parameters->get('redirect');
495
496
        if (!is_array($redirect) || !isset($redirect['header'])) {
497
            return false;
498
        }
499
500
        if ('xhr' === $redirect['header']) {
501
            return $this->getRequest()->isXmlHttpRequest();
502
        }
503
504
        return (bool) $redirect['header'];
505
    }
506
507
    /**
508
     * @param array  $parameters
509
     * @param object $resource
510
     *
511
     * @return array
512
     */
513
    private function parseResourceValues(array $parameters, $resource)
514
    {
515
        $accessor = PropertyAccess::createPropertyAccessor();
516
517
        if (empty($parameters)) {
518
            return ['id' => $accessor->getValue($resource, 'id')];
519
        }
520
521
        foreach ($parameters as $key => $value) {
522
            if (is_array($value)) {
523
                $parameters[$key] = $this->parseResourceValues($value, $resource);
524
            }
525
526
            if (is_string($value) && 0 === strpos($value, 'resource.')) {
527
                $parameters[$key] = $accessor->getValue($resource, substr($value, 9));
528
            }
529
        }
530
531
        return $parameters;
532
    }
533
}
534