Completed
Push — feature/EVO-4597-rabbitmq-hand... ( 6e503b...616297 )
by
unknown
52:22 queued 46:35
created

RestController::setFormDataMapper()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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 190
    public function __construct(
133
        Response $response,
134
        RestUtilsInterface $restUtils,
135
        Router $router,
136
        ValidatorInterface $validator,
137
        EngineInterface $templating,
138 1
        FormFactory $formFactory,
139
        DocumentType $formType,
140
        ContainerInterface $container,
141
        SchemaUtils $schemaUtils
142
    ) {
143 190
        $this->response = $response;
144 190
        $this->restUtils = $restUtils;
145 190
        $this->router = $router;
146 190
        $this->validator = $validator;
147 190
        $this->templating = $templating;
148 190
        $this->formFactory = $formFactory;
149 190
        $this->formType = $formType;
150 190
        $this->container = $container;
151 190
        $this->schemaUtils = $schemaUtils;
152 190
    }
153
154
    /**
155
     * Setter for the tokenStorage
156
     *
157
     * @param TokenStorage $tokenStorage The token storage
158
     * @return void
159
     */
160 190
    public function setTokenStorage(TokenStorage $tokenStorage)
161
    {
162 190
        $this->tokenStorage = $tokenStorage;
163 190
    }
164
165
    /**
166
     * Set form data mapper
167
     *
168
     * @param FormDataMapperInterface $formDataMapper Form data mapper
169
     * @return void
170
     */
171 190
    public function setFormDataMapper(FormDataMapperInterface $formDataMapper)
172
    {
173 190
        $this->formDataMapper = $formDataMapper;
174 190
    }
175
176
    /**
177
     * @param JsonPatchValidator $jsonPatchValidator Service for validation json patch
178
     * @return void
179
     */
180 190
    public function setJsonPatchValidator(JsonPatchValidator $jsonPatchValidator)
181
    {
182 190
        $this->jsonPatchValidator = $jsonPatchValidator;
183 190
    }
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 190
    public function setFormValidator(Form $validator)
193
    {
194 190
        $this->formValidator = $validator;
195 190
    }
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 55
    public function getAction(Request $request, $id)
218
    {
219 55
        $response = $this->getResponse()
220 55
            ->setStatusCode(Response::HTTP_OK);
221
222 55
        $record = $this->findRecord($id);
223
224 53
        return $this->render(
225 53
            'GravitonRestBundle:Main:index.json.twig',
226 53
            ['response' => $this->serialize($record)],
227
            $response
228 1
        );
229
    }
230
231
    /**
232
     * Get the response object
233
     *
234
     * @return \Symfony\Component\HttpFoundation\Response $response Response object
235
     */
236 186
    public function getResponse()
237
    {
238 186
        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 61
    protected function findRecord($id)
251
    {
252 61
        $response = $this->getResponse();
253
254 61
        if (!($record = $this->getModel()->find($id))) {
255 13
            $e = new NotFoundException("Entry with id " . $id . " not found!");
256 13
            $e->setResponse($response);
257 13
            throw $e;
258
        }
259
260 58
        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 183
    public function getModel()
271
    {
272 183
        if (!$this->model) {
273
            throw new \Exception('No model is set for this controller');
274
        }
275
276 183
        return $this->model;
277
    }
278
279
    /**
280
     * Set the model class
281
     *
282
     * @param DocumentModel $model Model class
283
     *
284
     * @return self
285
     */
286 190
    public function setModel(DocumentModel $model)
287
    {
288 190
        $this->model = $model;
289
290 190
        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 151
    protected function serialize($result)
303
    {
304 151
        $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 151
            if (is_array($result) && array_keys($result) === range(0, count($result) - 1)) {
310 65
                $result = array_map(
311 65
                    function ($item) {
312 65
                        return $this->getRestUtils()->serializeContent($item);
313 65
                    },
314
                    $result
315 2
                );
316
317
                /*
318
                 * clean up:
319
                 *
320
                 * - remove empty entries
321
                 */
322 65
                $result = array_filter($result);
323
324 65
                return '['.implode(',', $result).']';
325
            }
326
327 92
            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 151
    public function getRestUtils()
341
    {
342 151
        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 84
    public function allAction(Request $request)
353
    {
354 84
        $model = $this->getModel();
355
356 84
        list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
357
358 84
        $schema = $this->schemaUtils->getModelSchema($modelName, $model);
359
360
        // Security is optional configured in Parameters
361
        try {
362
            /** @var SecurityUser $securityUser */
363 84
            $securityUser = $this->getSecurityUser();
364 2
        } catch (PreconditionRequiredHttpException $e) {
365
            $securityUser = null;
366
        }
367
368 84
        if ($model instanceof PaginatorAwareInterface && !$model->hasPaginator()) {
369
            $paginator = new Paginator();
370
            $model->setPaginator($paginator);
371
        }
372
373 84
        $response = $this->getResponse()
374 84
            ->setStatusCode(Response::HTTP_OK);
375
376 84
        return $this->render(
377 84
            'GravitonRestBundle:Main:index.json.twig',
378 84
            ['response' => $this->serialize($model->findAll($request, $securityUser, $schema))],
379
            $response
380 2
        );
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 28
    public function postAction(Request $request)
391
    {
392
        // Get the response object from container
393 28
        $response = $this->getResponse();
394 28
        $model = $this->getModel();
395
396 28
        $this->formValidator->checkJsonRequest($request, $response);
397 25
        $record = $this->formValidator->checkForm(
398 25
            $this->formValidator->getForm($request, $model),
399
            $model,
400 25
            $this->formDataMapper,
401 25
            $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 15
        $record = $this->getModel()->insertRecord($record);
406
407
        // store id of new record so we dont need to reparse body later when needed
408 15
        $request->attributes->set('id', $record->getId());
409
410
        // Set status code
411 15
        $response->setStatusCode(Response::HTTP_CREATED);
412
413 15
        $response->headers->set(
414 15
            'Location',
415 15
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
416
        );
417
418 15
        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 44
    public function getRouter()
460
    {
461 44
        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 33
    public function putAction($id, Request $request)
475
    {
476 33
        $response = $this->getResponse();
477 33
        $model = $this->getModel();
478
479 33
        $this->formValidator->checkJsonRequest($request, $response);
480
481 32
        $record = $this->formValidator->checkForm(
482 32
            $this->formValidator->getForm($request, $model),
483
            $model,
484 32
            $this->formDataMapper,
485 32
            $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 24
        $upsert = false;
490
        try {
491 24
            $this->findRecord($id);
492 8
        } catch (NotFoundException $e) {
493
            // who cares, we'll upsert it
494 8
            $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 24
        if ($record->getId() != $id) {
500
            // try to set it..
501 3
            if (is_callable(array($record, 'setId'))) {
502 3
                $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 24
        if ($upsert) {
510 8
            $this->getModel()->insertRecord($record);
511
        } else {
512 16
            $this->getModel()->updateRecord($id, $record);
513
        }
514
515
        // Set status code
516 24
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
517
518
        // store id of new record so we dont need to reparse body later when needed
519 24
        $request->attributes->set('id', $record->getId());
520
521 24
        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 14
    public function patchAction($id, Request $request)
535
    {
536 14
        $response = $this->getResponse();
537 14
        $this->formValidator->checkJsonRequest($request, $response);
538
539
        // Check JSON Patch request
540 14
        $this->formValidator->checkJsonPatchRequest(json_decode($request->getContent(), 1));
541
542
        // Find record && apply $ref converter
543 12
        $record = $this->findRecord($id);
544 12
        $jsonDocument = $this->serialize($record);
545
546
        // Check/validate JSON Patch
547 12
        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 2
            throw new InvalidJsonPatchException($this->jsonPatchValidator->getException()->getMessage());
549
        }
550
551
        try {
552
            // Apply JSON patches
553 10
            $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 10
            $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 10
        $model = $this->getModel();
567 10
        $record = $this->formValidator->checkForm(
568 10
            $this->formValidator->getForm($request, $model),
569
            $model,
570 10
            $this->formDataMapper,
571
            $patchedDocument
572
        );
573
574
        // Update object
575 9
        $this->getModel()->updateRecord($id, $record);
576
577
        // Set status code
578 9
        $response->setStatusCode(Response::HTTP_OK);
579
580
        // Set Content-Location header
581 9
        $response->headers->set(
582 9
            'Content-Location',
583 9
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
584
        );
585
586 9
        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 5
    public function deleteAction($id)
597
    {
598 5
        $response = $this->getResponse();
599
600
        // does this record exist?
601 5
        $this->findRecord($id);
602
603 5
        $this->getModel()->deleteRecord($id);
604 5
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
605
606 5
        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 5
    public function optionsAction(Request $request)
618
    {
619 5
        list($app, $module, , $modelName) = explode('.', $request->attributes->get('_route'));
620
621 5
        $response = $this->response;
622 5
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
623
624
        // enabled methods for CorsListener
625 5
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
626
        try {
627 5
            $router = $this->getRouter();
628
            // if post route is available we assume everything is readable
629 5
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
630 1
        } catch (RouteNotFoundException $exception) {
631
            // only allow read methods
632 1
            $corsMethods = 'GET, OPTIONS';
633
        }
634 5
        $request->attributes->set('corsMethods', $corsMethods);
635
636 5
        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 12
    public function schemaAction(Request $request, $id = null)
650
    {
651 12
        $request->attributes->set('schemaRequest', true);
652
653 12
        list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
654
655 12
        $response = $this->response;
656 12
        $response->setStatusCode(Response::HTTP_OK);
657 12
        $response->setPublic();
658
659 12
        if (!$id && $schemaType != 'canonicalIdSchema') {
660 8
            $schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
661
        } else {
662 5
            $schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
663
        }
664
665
        // enabled methods for CorsListener
666 12
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
667
        try {
668 12
            $router = $this->getRouter();
669
            // if post route is available we assume everything is readable
670 12
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
671 1
        } catch (RouteNotFoundException $exception) {
672
            // only allow read methods
673 1
            $corsMethods = 'GET, OPTIONS';
674
        }
675 12
        $request->attributes->set('corsMethods', $corsMethods);
676
677
678 12
        return $this->render(
679 12
            'GravitonRestBundle:Main:index.json.twig',
680 12
            ['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 152
    public function render($view, array $parameters = array(), Response $response = null)
705
    {
706 152
        return $this->templating->renderResponse($view, $parameters, $response);
707
    }
708
709
    /**
710
     * @param Request $request request
711
     * @return string
712
     */
713 24
    private function getRouteName(Request $request)
714
    {
715 24
        $routeName = $request->get('_route');
716 24
        $routeParts = explode('.', $routeName);
717 24
        $routeType = end($routeParts);
718
719 24
        if ($routeType == 'post') {
720 15
            $routeName = substr($routeName, 0, -4) . 'get';
721
        }
722
723 24
        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 85
    public function getSecurityUser()
733
    {
734
        /** @var PreAuthenticatedToken $token */
735 85
        if (($token = $this->tokenStorage->getToken())
736 85
            && ($user = $token->getUser()) instanceof UserInterface ) {
737 85
            return $user;
738
        }
739
740
        throw new PreconditionRequiredHttpException('Not allowed');
741
    }
742
}
743