Completed
Push — master ( 91e054...12ace7 )
by Kamil
31:08 queued 26:39
created

RequestConfiguration::parseResourceValues()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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