Completed
Push — master ( 11b317...37df4d )
by Lucas
09:27
created

RestController::setModel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * basic rest controller
4
 */
5
6
namespace Graviton\RestBundle\Controller;
7
8
use Graviton\DocumentBundle\Service\FormDataMapperInterface;
9
use Graviton\ExceptionBundle\Exception\DeserializationException;
10
use Graviton\ExceptionBundle\Exception\InvalidJsonPatchException;
11
use Graviton\ExceptionBundle\Exception\MalformedInputException;
12
use Graviton\ExceptionBundle\Exception\NotFoundException;
13
use Graviton\ExceptionBundle\Exception\SerializationException;
14
use Graviton\RestBundle\Validator\Form;
15
use Graviton\RestBundle\Model\DocumentModel;
16
use Graviton\RestBundle\Model\PaginatorAwareInterface;
17
use Graviton\SchemaBundle\SchemaUtils;
18
use Graviton\DocumentBundle\Form\Type\DocumentType;
19
use Graviton\RestBundle\Service\RestUtilsInterface;
20
use Symfony\Component\Security\Core\User\UserInterface;
21
use Knp\Component\Pager\Paginator;
22
use Symfony\Component\DependencyInjection\ContainerInterface;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25
use Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException;
26
use Symfony\Component\Routing\Exception\RouteNotFoundException;
27
use Symfony\Component\Form\FormFactory;
28
use Symfony\Bundle\FrameworkBundle\Routing\Router;
29
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
30
use Symfony\Component\Validator\Validator\ValidatorInterface;
31
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
32
use Rs\Json\Patch;
33
use Rs\Json\Patch\InvalidPatchDocumentJsonException;
34
use Rs\Json\Patch\InvalidTargetDocumentJsonException;
35
use Rs\Json\Patch\InvalidOperationException;
36
use Rs\Json\Patch\FailedTestException;
37
use Graviton\RestBundle\Service\JsonPatchValidator;
38
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
39
40
/**
41
 * This is a basic rest controller. It should fit the most needs but if you need to add some
42
 * extra functionality you can extend it and overwrite single/all actions.
43
 * You can also extend the model class to add some extra logic before save
44
 *
45
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
46
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
47
 * @link     http://swisscom.ch
48
 */
49
class RestController
50
{
51
    /**
52
     * @var DocumentModel
53
     */
54
    private $model;
55
56
    /**
57
     * @var ContainerInterface service_container
58
     */
59
    private $container;
60
61
    /**
62
     * @var Response
63
     */
64
    private $response;
65
66
    /**
67
     * @var FormFactory
68
     */
69
    private $formFactory;
70
71
    /**
72
     * @var DocumentType
73
     */
74
    private $formType;
75
76
    /**
77
     * @var RestUtilsInterface
78
     */
79
    private $restUtils;
80
81
    /**
82
     * @var SchemaUtils
83
     */
84
    private $schemaUtils;
85
86
    /**
87
     * @var FormDataMapperInterface
88
     */
89
    protected $formDataMapper;
90
91
    /**
92
     * @var Router
93
     */
94
    private $router;
95
96
    /**
97
     * @var ValidatorInterface
98
     */
99
    private $validator;
100
101
    /**
102
     * @var EngineInterface
103
     */
104
    private $templating;
105
106
    /**
107
     * @var JsonPatchValidator
108
     */
109
    private $jsonPatchValidator;
110
111
    /**
112
     * @var Form
113
     */
114
    protected $formValidator;
115
116
    /**
117
     * @var TokenStorage
118
     */
119
    protected $tokenStorage;
120
121
    /**
122
     * @param Response           $response    Response
123
     * @param RestUtilsInterface $restUtils   Rest utils
124
     * @param Router             $router      Router
125
     * @param ValidatorInterface $validator   Validator
126
     * @param EngineInterface    $templating  Templating
127
     * @param FormFactory        $formFactory form factory
128
     * @param DocumentType       $formType    generic form
129
     * @param ContainerInterface $container   Container
130
     * @param SchemaUtils        $schemaUtils Schema utils
131
     */
132
    public function __construct(
133
        Response $response,
134
        RestUtilsInterface $restUtils,
135
        Router $router,
136
        ValidatorInterface $validator,
137
        EngineInterface $templating,
138
        FormFactory $formFactory,
139
        DocumentType $formType,
140
        ContainerInterface $container,
141
        SchemaUtils $schemaUtils
142
    ) {
143
        $this->response = $response;
144
        $this->restUtils = $restUtils;
145
        $this->router = $router;
146
        $this->validator = $validator;
147
        $this->templating = $templating;
148
        $this->formFactory = $formFactory;
149
        $this->formType = $formType;
150
        $this->container = $container;
151
        $this->schemaUtils = $schemaUtils;
152
    }
153
154
    /**
155
     * Setter for the tokenStorage
156
     *
157
     * @param TokenStorage $tokenStorage The token storage
158
     * @return void
159
     */
160
    public function setTokenStorage(TokenStorage $tokenStorage)
161
    {
162
        $this->tokenStorage = $tokenStorage;
163
    }
164
165
    /**
166
     * Set form data mapper
167
     *
168
     * @param FormDataMapperInterface $formDataMapper Form data mapper
169
     * @return void
170
     */
171
    public function setFormDataMapper(FormDataMapperInterface $formDataMapper)
172
    {
173
        $this->formDataMapper = $formDataMapper;
174
    }
175
176
    /**
177
     * @param JsonPatchValidator $jsonPatchValidator Service for validation json patch
178
     * @return void
179
     */
180
    public function setJsonPatchValidator(JsonPatchValidator $jsonPatchValidator)
181
    {
182
        $this->jsonPatchValidator = $jsonPatchValidator;
183
    }
184
185
    /**
186
     * Defines the Form validator to be used.
187
     *
188
     * @param Form $validator Validator to be used
189
     *
190
     * @return void
191
     */
192
    public function setFormValidator(Form $validator)
193
    {
194
        $this->formValidator = $validator;
195
    }
196
197
    /**
198
     * Get the container object
199
     *
200
     * @return \Symfony\Component\DependencyInjection\ContainerInterface
201
     *
202
     * @obsolete
203
     */
204
    public function getContainer()
205
    {
206
        return $this->container;
207
    }
208
209
    /**
210
     * Returns a single record
211
     *
212
     * @param Request $request Current http request
213
     * @param string  $id      ID of record
214
     *
215
     * @return \Symfony\Component\HttpFoundation\Response $response Response with result or error
216
     */
217
    public function getAction(Request $request, $id)
218
    {
219
        $response = $this->getResponse()
220
            ->setStatusCode(Response::HTTP_OK);
221
222
        $record = $this->findRecord($id);
223
224
        return $this->render(
225
            'GravitonRestBundle:Main:index.json.twig',
226
            ['response' => $this->serialize($record)],
227
            $response
228
        );
229
    }
230
231
    /**
232
     * Get the response object
233
     *
234
     * @return \Symfony\Component\HttpFoundation\Response $response Response object
235
     */
236
    public function getResponse()
237
    {
238
        return $this->response;
239
    }
240
241
    /**
242
     * Get a single record from database or throw an exception if it doesn't exist
243
     *
244
     * @param mixed $id Record id
245
     *
246
     * @throws \Graviton\ExceptionBundle\Exception\NotFoundException
247
     *
248
     * @return object $record Document object
249
     */
250
    protected function findRecord($id)
251
    {
252
        $response = $this->getResponse();
253
254
        if (!($record = $this->getModel()->find($id))) {
255
            $e = new NotFoundException("Entry with id " . $id . " not found!");
256
            $e->setResponse($response);
257
            throw $e;
258
        }
259
260
        return $record;
261
    }
262
263
    /**
264
     * Return the model
265
     *
266
     * @throws \Exception in case no model was defined.
267
     *
268
     * @return DocumentModel $model Model
269
     */
270
    public function getModel()
271
    {
272
        if (!$this->model) {
273
            throw new \Exception('No model is set for this controller');
274
        }
275
276
        return $this->model;
277
    }
278
279
    /**
280
     * Set the model class
281
     *
282
     * @param DocumentModel $model Model class
283
     *
284
     * @return self
285
     */
286
    public function setModel(DocumentModel $model)
287
    {
288
        $this->model = $model;
289
290
        return $this;
291
    }
292
293
    /**
294
     * Serialize the given record and throw an exception if something went wrong
295
     *
296
     * @param object|object[] $result Record(s)
297
     *
298
     * @throws \Graviton\ExceptionBundle\Exception\SerializationException
299
     *
300
     * @return string $content Json content
301
     */
302
    protected function serialize($result)
303
    {
304
        $response = $this->getResponse();
305
306
        try {
307
            // array is serialized as an object {"0":{...},"1":{...},...} when data contains an empty objects
308
            // we serialize each item because we can assume this bug affects only root array element
309
            if (is_array($result) && array_keys($result) === range(0, count($result) - 1)) {
310
                $result = array_map(
311
                    function ($item) {
312
                        return $this->getRestUtils()->serializeContent($item);
313
                    },
314
                    $result
315
                );
316
317
                /*
318
                 * clean up:
319
                 *
320
                 * - remove empty entries
321
                 */
322
                $result = array_filter($result);
323
324
                return '['.implode(',', $result).']';
325
            }
326
327
            return $this->getRestUtils()->serializeContent($result);
0 ignored issues
show
Bug introduced by
It seems like $result defined by parameter $result on line 302 can also be of type array; however, Graviton\RestBundle\Serv...ils::serializeContent() does only seem to accept object, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
328
        } catch (\Exception $e) {
329
            $exception = new SerializationException($e);
330
            $exception->setResponse($response);
331
            throw $exception;
332
        }
333
    }
334
335
    /**
336
     * Get RestUtils service
337
     *
338
     * @return \Graviton\RestBundle\Service\RestUtils
339
     */
340
    public function getRestUtils()
341
    {
342
        return $this->restUtils;
343
    }
344
345
    /**
346
     * Returns all records
347
     *
348
     * @param Request $request Current http request
349
     *
350
     * @return \Symfony\Component\HttpFoundation\Response $response Response with result or error
351
     */
352
    public function allAction(Request $request)
353
    {
354
        $model = $this->getModel();
355
356
        list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
357
358
        $schema = $this->schemaUtils->getModelSchema($modelName, $model);
359
360
        // Security is optional configured in Parameters
361
        try {
362
            /** @var SecurityUser $securityUser */
363
            $securityUser = $this->getSecurityUser();
364
        } catch (PreconditionRequiredHttpException $e) {
365
            $securityUser = null;
366
        }
367
368
        if ($model instanceof PaginatorAwareInterface && !$model->hasPaginator()) {
369
            $paginator = new Paginator();
370
            $model->setPaginator($paginator);
371
        }
372
373
        $response = $this->getResponse()
374
            ->setStatusCode(Response::HTTP_OK);
375
376
        return $this->render(
377
            'GravitonRestBundle:Main:index.json.twig',
378
            ['response' => $this->serialize($model->findAll($request, $securityUser, $schema))],
379
            $response
380
        );
381
    }
382
383
    /**
384
     * Writes a new Entry to the database
385
     *
386
     * @param Request $request Current http request
387
     *
388
     * @return \Symfony\Component\HttpFoundation\Response $response Result of action with data (if successful)
389
     */
390
    public function postAction(Request $request)
391
    {
392
        // Get the response object from container
393
        $response = $this->getResponse();
394
        $model = $this->getModel();
395
396
        $this->formValidator->checkJsonRequest($request, $response);
397
        $record = $this->formValidator->checkForm(
398
            $this->formValidator->getForm($request, $model),
399
            $model,
400
            $this->formDataMapper,
401
            $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, Graviton\RestBundle\Validator\Form::checkForm() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
402
        );
403
404
        // Insert the new record
405
        $record = $this->getModel()->insertRecord($record);
406
407
        // store id of new record so we dont need to reparse body later when needed
408
        $request->attributes->set('id', $record->getId());
409
410
        // Set status code
411
        $response->setStatusCode(Response::HTTP_CREATED);
412
413
        $response->headers->set(
414
            'Location',
415
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
416
        );
417
418
        return $response;
419
    }
420
421
    /**
422
     * Deserialize the given content throw an exception if something went wrong
423
     *
424
     * @param string $content       Request content
425
     * @param string $documentClass Document class
426
     *
427
     * @throws DeserializationException
428
     *
429
     * @return object $record Document
0 ignored issues
show
Documentation introduced by
Should the return type not be object|array|integer|double|string|boolean? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
430
     */
431
    protected function deserialize($content, $documentClass)
432
    {
433
        $response = $this->getResponse();
434
435
        try {
436
            $record = $this->getRestUtils()->deserializeContent(
437
                $content,
438
                $documentClass
439
            );
440
        } catch (\Exception $e) {
441
            // pass the previous exception in this case to get the error message in the handler
442
            // http://php.net/manual/de/exception.getprevious.php
443
            $exception = new DeserializationException("Deserialization failed", $e);
444
445
            // at the moment, the response has to be set on the exception object.
446
            // try to refactor this and return the graviton.rest.response if none is set...
447
            $exception->setResponse($response);
448
            throw $exception;
449
        }
450
451
        return $record;
452
    }
453
454
    /**
455
     * Get the router from the dic
456
     *
457
     * @return Router
458
     */
459
    public function getRouter()
460
    {
461
        return $this->router;
462
    }
463
464
    /**
465
     * Update a record
466
     *
467
     * @param Number  $id      ID of record
468
     * @param Request $request Current http request
469
     *
470
     * @throws MalformedInputException
471
     *
472
     * @return Response $response Result of action with data (if successful)
473
     */
474
    public function putAction($id, Request $request)
475
    {
476
        $response = $this->getResponse();
477
        $model = $this->getModel();
478
479
        $this->formValidator->checkJsonRequest($request, $response);
480
481
        $record = $this->formValidator->checkForm(
482
            $this->formValidator->getForm($request, $model),
483
            $model,
484
            $this->formDataMapper,
485
            $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, Graviton\RestBundle\Validator\Form::checkForm() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
486
        );
487
488
        // does it really exist??
489
        $upsert = false;
490
        try {
491
            $this->findRecord($id);
492
        } catch (NotFoundException $e) {
493
            // who cares, we'll upsert it
494
            $upsert = true;
495
        }
496
497
        // handle missing 'id' field in input to a PUT operation
498
        // if it is settable on the document, let's set it and move on.. if not, inform the user..
499
        if ($record->getId() != $id) {
500
            // try to set it..
501
            if (is_callable(array($record, 'setId'))) {
502
                $record->setId($id);
503
            } else {
504
                throw new MalformedInputException('No ID was supplied in the request payload.');
505
            }
506
        }
507
508
        // And update the record, if everything is ok
509
        if ($upsert) {
510
            $this->getModel()->insertRecord($record);
511
        } else {
512
            $this->getModel()->updateRecord($id, $record);
513
        }
514
515
        // Set status code
516
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
517
518
        // store id of new record so we dont need to reparse body later when needed
519
        $request->attributes->set('id', $record->getId());
520
521
        return $response;
522
    }
523
524
    /**
525
     * Patch a record
526
     *
527
     * @param Number  $id      ID of record
528
     * @param Request $request Current http request
529
     *
530
     * @throws MalformedInputException
531
     *
532
     * @return Response $response Result of action with data (if successful)
533
     */
534
    public function patchAction($id, Request $request)
535
    {
536
        $response = $this->getResponse();
537
        $this->formValidator->checkJsonRequest($request, $response);
538
539
        // Check JSON Patch request
540
        $this->formValidator->checkJsonPatchRequest(json_decode($request->getContent(), 1));
541
542
        // Find record && apply $ref converter
543
        $record = $this->findRecord($id);
544
        $jsonDocument = $this->serialize($record);
545
546
        // Check/validate JSON Patch
547
        if (!$this->jsonPatchValidator->validate($jsonDocument, $request->getContent())) {
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, Graviton\RestBundle\Serv...chValidator::validate() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
548
            throw new InvalidJsonPatchException($this->jsonPatchValidator->getException()->getMessage());
549
        }
550
551
        try {
552
            // Apply JSON patches
553
            $patch = new Patch($jsonDocument, $request->getContent());
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, Rs\Json\Patch::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
554
            $patchedDocument = $patch->apply();
555
        } catch (InvalidPatchDocumentJsonException $e) {
556
            throw new InvalidJsonPatchException($e->getMessage());
557
        } catch (InvalidTargetDocumentJsonException $e) {
558
            throw new InvalidJsonPatchException($e->getMessage());
559
        } catch (InvalidOperationException $e) {
560
            throw new InvalidJsonPatchException($e->getMessage());
561
        } catch (FailedTestException $e) {
562
            throw new InvalidJsonPatchException($e->getMessage());
563
        }
564
565
        // Validate result object
566
        $model = $this->getModel();
567
        $record = $this->formValidator->checkForm(
568
            $this->formValidator->getForm($request, $model),
569
            $model,
570
            $this->formDataMapper,
571
            $patchedDocument
572
        );
573
574
        // Update object
575
        $this->getModel()->updateRecord($id, $record);
576
577
        // Set status code
578
        $response->setStatusCode(Response::HTTP_OK);
579
580
        // Set Content-Location header
581
        $response->headers->set(
582
            'Content-Location',
583
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
584
        );
585
586
        return $response;
587
    }
588
589
    /**
590
     * Deletes a record
591
     *
592
     * @param Number $id ID of record
593
     *
594
     * @return Response $response Result of the action
595
     */
596
    public function deleteAction($id)
597
    {
598
        $response = $this->getResponse();
599
600
        // does this record exist?
601
        $this->findRecord($id);
602
603
        $this->getModel()->deleteRecord($id);
604
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
605
606
        return $response;
607
    }
608
609
    /**
610
     * Return OPTIONS results.
611
     *
612
     * @param Request $request Current http request
613
     *
614
     * @throws SerializationException
615
     * @return \Symfony\Component\HttpFoundation\Response $response Result of the action
616
     */
617
    public function optionsAction(Request $request)
618
    {
619
        list($app, $module, , $modelName) = explode('.', $request->attributes->get('_route'));
620
621
        $response = $this->response;
622
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
623
624
        // enabled methods for CorsListener
625
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
626
        try {
627
            $router = $this->getRouter();
628
            // if post route is available we assume everything is readable
629
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
630
        } catch (RouteNotFoundException $exception) {
631
            // only allow read methods
632
            $corsMethods = 'GET, OPTIONS';
633
        }
634
        $request->attributes->set('corsMethods', $corsMethods);
635
636
        return $response;
637
    }
638
639
640
    /**
641
     * Return schema GET results.
642
     *
643
     * @param Request $request Current http request
644
     * @param string  $id      ID of record
0 ignored issues
show
Documentation introduced by
Should the type for parameter $id not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
645
     *
646
     * @throws SerializationException
647
     * @return \Symfony\Component\HttpFoundation\Response $response Result of the action
648
     */
649
    public function schemaAction(Request $request, $id = null)
650
    {
651
        $request->attributes->set('schemaRequest', true);
652
653
        list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
654
655
        $response = $this->response;
656
        $response->setStatusCode(Response::HTTP_OK);
657
        $response->setPublic();
658
659
        if (!$id && $schemaType != 'canonicalIdSchema') {
660
            $schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
661
        } else {
662
            $schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
663
        }
664
665
        // enabled methods for CorsListener
666
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
667
        try {
668
            $router = $this->getRouter();
669
            // if post route is available we assume everything is readable
670
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
671
        } catch (RouteNotFoundException $exception) {
672
            // only allow read methods
673
            $corsMethods = 'GET, OPTIONS';
674
        }
675
        $request->attributes->set('corsMethods', $corsMethods);
676
677
678
        return $this->render(
679
            'GravitonRestBundle:Main:index.json.twig',
680
            ['response' => $this->serialize($schema)],
681
            $response
682
        );
683
    }
684
685
    /**
686
     * Get the validator
687
     *
688
     * @return ValidatorInterface
689
     */
690
    public function getValidator()
691
    {
692
        return $this->validator;
693
    }
694
695
    /**
696
     * Renders a view.
697
     *
698
     * @param string   $view       The view name
699
     * @param array    $parameters An array of parameters to pass to the view
700
     * @param Response $response   A response instance
0 ignored issues
show
Documentation introduced by
Should the type for parameter $response not be null|Response?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
701
     *
702
     * @return Response A Response instance
703
     */
704
    public function render($view, array $parameters = array(), Response $response = null)
705
    {
706
        return $this->templating->renderResponse($view, $parameters, $response);
707
    }
708
709
    /**
710
     * @param Request $request request
711
     * @return string
712
     */
713
    private function getRouteName(Request $request)
714
    {
715
        $routeName = $request->get('_route');
716
        $routeParts = explode('.', $routeName);
717
        $routeType = end($routeParts);
718
719
        if ($routeType == 'post') {
720
            $routeName = substr($routeName, 0, -4) . 'get';
721
        }
722
723
        return $routeName;
724
    }
725
726
    /**
727
     * Security needs to be enabled to get Object.
728
     *
729
     * @return SecurityUser
0 ignored issues
show
Documentation introduced by
Should the return type not be UserInterface?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
730
     * @throws PreconditionRequiredHttpException
731
     */
732
    public function getSecurityUser()
733
    {
734
        /** @var PreAuthenticatedToken $token */
735
        if (($token = $this->tokenStorage->getToken())
736
            && ($user = $token->getUser()) instanceof UserInterface ) {
737
            return $user;
738
        }
739
740
        throw new PreconditionRequiredHttpException('Not allowed');
741
    }
742
}
743