Failed Conditions
Push — feature/moar-test-optimizing ( 091eca...fb462a )
by Lucas
24:29 queued 14:31
created

RestController::patchAction()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 54
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42
Metric Value
dl 0
loc 54
ccs 0
cts 28
cp 0
rs 8.7449
cc 6
eloc 31
nc 10
nop 2
crap 42

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 2
    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 2
        $this->response = $response;
144 2
        $this->restUtils = $restUtils;
145 2
        $this->router = $router;
146 2
        $this->validator = $validator;
147 2
        $this->templating = $templating;
148 2
        $this->formFactory = $formFactory;
149 2
        $this->formType = $formType;
150 2
        $this->container = $container;
151 2
        $this->schemaUtils = $schemaUtils;
152 2
    }
153
154
    /**
155
     * Setter for the tokenStorage
156
     *
157
     * @param TokenStorage $tokenStorage The token storage
158
     * @return void
159
     */
160 2
    public function setTokenStorage(TokenStorage $tokenStorage)
161
    {
162 2
        $this->tokenStorage = $tokenStorage;
163 2
    }
164
165
    /**
166
     * Set form data mapper
167
     *
168
     * @param FormDataMapperInterface $formDataMapper Form data mapper
169
     * @return void
170
     */
171 2
    public function setFormDataMapper(FormDataMapperInterface $formDataMapper)
172
    {
173 2
        $this->formDataMapper = $formDataMapper;
174 2
    }
175
176
    /**
177
     * @param JsonPatchValidator $jsonPatchValidator Service for validation json patch
178
     * @return void
179
     */
180 2
    public function setJsonPatchValidator(JsonPatchValidator $jsonPatchValidator)
181
    {
182 2
        $this->jsonPatchValidator = $jsonPatchValidator;
183 2
    }
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 2
    public function setFormValidator(Form $validator)
193
    {
194 2
        $this->formValidator = $validator;
195 2
    }
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 1
    public function getAction(Request $request, $id)
218
    {
219 1
        $response = $this->getResponse()
220 1
            ->setStatusCode(Response::HTTP_OK);
221
222 1
        $record = $this->findRecord($id);
223
224 1
        return $this->render(
225 1
            'GravitonRestBundle:Main:index.json.twig',
226 1
            ['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 2
    public function getResponse()
237
    {
238 2
        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 1
    protected function findRecord($id)
251
    {
252 1
        $response = $this->getResponse();
253
254 1
        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 1
        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 2
    public function getModel()
271
    {
272 2
        if (!$this->model) {
273
            throw new \Exception('No model is set for this controller');
274
        }
275
276 2
        return $this->model;
277
    }
278
279
    /**
280
     * Set the model class
281
     *
282
     * @param DocumentModel $model Model class
283
     *
284
     * @return self
285
     */
286 2
    public function setModel(DocumentModel $model)
287
    {
288 2
        $this->model = $model;
289
290 2
        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 2
    protected function serialize($result)
303
    {
304 2
        $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 2
            if (is_array($result) && array_keys($result) === range(0, count($result) - 1)) {
310 1
                $result = array_map(
311 1
                    function ($item) {
312 1
                        return $this->getRestUtils()->serializeContent($item);
313 1
                    },
314
                    $result
315 1
                );
316 1
                return '['.implode(',', $result).']';
317
            }
318
319 1
            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...
320
        } catch (\Exception $e) {
321
            $exception = new SerializationException($e);
322
            $exception->setResponse($response);
323
            throw $exception;
324
        }
325
    }
326
327
    /**
328
     * Get RestUtils service
329
     *
330
     * @return \Graviton\RestBundle\Service\RestUtils
331
     */
332 2
    public function getRestUtils()
333
    {
334 2
        return $this->restUtils;
335
    }
336
337
    /**
338
     * Returns all records
339
     *
340
     * @param Request $request Current http request
341
     *
342
     * @return \Symfony\Component\HttpFoundation\Response $response Response with result or error
343
     */
344 1
    public function allAction(Request $request)
345
    {
346 1
        $model = $this->getModel();
347
348
        list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
349
350
        $schema = $this->schemaUtils->getModelSchema($modelName, $model);
351 1
352 1
        // Security is optional configured in Parameters
353
        try {
354
            /** @var SecurityUser $securityUser */
355
            $securityUser = $this->getSecurityUser();
356 1
        } catch (PreconditionRequiredHttpException $e) {
357
            $securityUser = null;
358
        }
359
360
        if ($model instanceof PaginatorAwareInterface && !$model->hasPaginator()) {
361 1
            $paginator = new Paginator();
362 1
            $model->setPaginator($paginator);
363
        }
364 1
365 1
        $response = $this->getResponse()
366 1
            ->setStatusCode(Response::HTTP_OK);
367
368 1
        return $this->render(
369
            'GravitonRestBundle:Main:index.json.twig',
370
            ['response' => $this->serialize($model->findAll($request, $securityUser, $schema))],
371
            $response
372
        );
373
    }
374
375
    /**
376
     * Writes a new Entry to the database
377
     *
378
     * @param Request $request Current http request
379
     *
380
     * @return \Symfony\Component\HttpFoundation\Response $response Result of action with data (if successful)
381
     */
382
    public function postAction(Request $request)
383
    {
384
        // Get the response object from container
385
        $response = $this->getResponse();
386
        $model = $this->getModel();
387
388
        $this->formValidator->checkJsonRequest($request, $response);
389
        $record = $this->formValidator->checkForm(
390
            $this->formValidator->getForm($request, $model),
391
            $model,
392
            $this->formDataMapper,
393
            $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...
394
        );
395
396
        // Insert the new record
397
        $record = $this->getModel()->insertRecord($record);
398
399
        // store id of new record so we dont need to reparse body later when needed
400
        $request->attributes->set('id', $record->getId());
401
402
        // Set status code
403
        $response->setStatusCode(Response::HTTP_CREATED);
404
405
        $response->headers->set(
406
            'Location',
407
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
408
        );
409
410
        return $response;
411
    }
412
413
    /**
414
     * Deserialize the given content throw an exception if something went wrong
415
     *
416
     * @param string $content       Request content
417
     * @param string $documentClass Document class
418
     *
419
     * @throws DeserializationException
420
     *
421
     * @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...
422
     */
423
    protected function deserialize($content, $documentClass)
424
    {
425
        $response = $this->getResponse();
426
427
        try {
428
            $record = $this->getRestUtils()->deserializeContent(
429
                $content,
430
                $documentClass
431
            );
432
        } catch (\Exception $e) {
433
            // pass the previous exception in this case to get the error message in the handler
434
            // http://php.net/manual/de/exception.getprevious.php
435
            $exception = new DeserializationException("Deserialization failed", $e);
436
437
            // at the moment, the response has to be set on the exception object.
438
            // try to refactor this and return the graviton.rest.response if none is set...
439
            $exception->setResponse($response);
440
            throw $exception;
441
        }
442
443
        return $record;
444
    }
445
446
    /**
447 1
     * Get the router from the dic
448
     *
449 1
     * @return Router
450
     */
451
    public function getRouter()
452
    {
453
        return $this->router;
454
    }
455
456
    /**
457
     * Update a record
458
     *
459
     * @param Number  $id      ID of record
460
     * @param Request $request Current http request
461
     *
462
     * @throws MalformedInputException
463
     *
464
     * @return Response $response Result of action with data (if successful)
465
     */
466
    public function putAction($id, Request $request)
467
    {
468
        $response = $this->getResponse();
469
        $model = $this->getModel();
470
471
        $this->formValidator->checkJsonRequest($request, $response);
472
473
        $record = $this->formValidator->checkForm(
474
            $this->formValidator->getForm($request, $model),
475
            $model,
476
            $this->formDataMapper,
477
            $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...
478
        );
479
480
        // does it really exist??
481
        $upsert = false;
482
        try {
483
            $this->findRecord($id);
484
        } catch (NotFoundException $e) {
485
            // who cares, we'll upsert it
486
            $upsert = true;
487
        }
488
489
        // handle missing 'id' field in input to a PUT operation
490
        // if it is settable on the document, let's set it and move on.. if not, inform the user..
491
        if ($record->getId() != $id) {
492
            // try to set it..
493
            if (is_callable(array($record, 'setId'))) {
494
                $record->setId($id);
495
            } else {
496
                throw new MalformedInputException('No ID was supplied in the request payload.');
497
            }
498
        }
499
500
        // And update the record, if everything is ok
501
        if ($upsert) {
502
            $this->getModel()->insertRecord($record);
503
        } else {
504
            $this->getModel()->updateRecord($id, $record);
505
        }
506
507
        // Set status code
508
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
509
510
        // store id of new record so we dont need to reparse body later when needed
511
        $request->attributes->set('id', $record->getId());
512
513
        return $response;
514
    }
515
516
    /**
517
     * Patch a record
518
     *
519
     * @param Number  $id      ID of record
520
     * @param Request $request Current http request
521
     *
522
     * @throws MalformedInputException
523
     *
524
     * @return Response $response Result of action with data (if successful)
525
     */
526
    public function patchAction($id, Request $request)
527
    {
528
        $response = $this->getResponse();
529
        $this->formValidator->checkJsonRequest($request, $response);
530
531
        // Check JSON Patch request
532
        $this->formValidator->checkJsonPatchRequest(json_decode($request->getContent(), 1));
533
534
        // Find record && apply $ref converter
535
        $record = $this->findRecord($id);
536
        $jsonDocument = $this->serialize($record);
537
538
        // Check/validate JSON Patch
539
        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...
540
            throw new InvalidJsonPatchException($this->jsonPatchValidator->getException()->getMessage());
541
        }
542
543
        try {
544
            // Apply JSON patches
545
            $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...
546
            $patchedDocument = $patch->apply();
547
        } catch (InvalidPatchDocumentJsonException $e) {
548
            throw new InvalidJsonPatchException($e->getMessage());
549
        } catch (InvalidTargetDocumentJsonException $e) {
550
            throw new InvalidJsonPatchException($e->getMessage());
551
        } catch (InvalidOperationException $e) {
552
            throw new InvalidJsonPatchException($e->getMessage());
553
        } catch (FailedTestException $e) {
554
            throw new InvalidJsonPatchException($e->getMessage());
555
        }
556
557
        // Validate result object
558
        $model = $this->getModel();
559
        $record = $this->formValidator->checkForm(
560
            $this->formValidator->getForm($request, $model),
561
            $model,
562
            $this->formDataMapper,
563
            $patchedDocument
564
        );
565
566
        // Update object
567
        $this->getModel()->updateRecord($id, $record);
568
569
        // Set status code
570
        $response->setStatusCode(Response::HTTP_OK);
571
572
        // Set Content-Location header
573
        $response->headers->set(
574
            'Content-Location',
575
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
576
        );
577
578
        return $response;
579
    }
580
581
    /**
582
     * Deletes a record
583
     *
584 1
     * @param Number $id ID of record
585
     *
586 1
     * @return Response $response Result of the action
587
     */
588
    public function deleteAction($id)
589 1
    {
590
        $response = $this->getResponse();
591 1
592 1
        // does this record exist?
593
        $this->findRecord($id);
594 1
595
        $this->getModel()->deleteRecord($id);
596
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
597
598
        return $response;
599
    }
600
601
    /**
602
     * Return OPTIONS results.
603
     *
604
     * @param Request $request Current http request
605
     *
606
     * @throws SerializationException
607
     * @return \Symfony\Component\HttpFoundation\Response $response Result of the action
608
     */
609
    public function optionsAction(Request $request)
610
    {
611
        list($app, $module, , $modelName) = explode('.', $request->attributes->get('_route'));
612
613
        $response = $this->response;
614
        $response->setStatusCode(Response::HTTP_OK);
615
616
        // enabled methods for CorsListener
617
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
618
        try {
619
            $router = $this->getRouter();
620
            // if post route is available we assume everything is readable
621
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
622
        } catch (RouteNotFoundException $exception) {
623
            // only allow read methods
624
            $corsMethods = 'GET, OPTIONS';
625
        }
626
        $request->attributes->set('corsMethods', $corsMethods);
627
628
        return $response;
629
    }
630
631
632
    /**
633
     * Return schema GET results.
634
     *
635
     * @param Request $request Current http request
636
     * @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...
637
     *
638
     * @throws SerializationException
639
     * @return \Symfony\Component\HttpFoundation\Response $response Result of the action
640
     */
641
    public function schemaAction(Request $request, $id = null)
642
    {
643
        $request->attributes->set('schemaRequest', true);
644
645
        list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
646
647
        $response = $this->response;
648
        $response->setStatusCode(Response::HTTP_OK);
649
        $response->setPublic();
650
651
        if (!$id && $schemaType != 'canonicalIdSchema') {
652
            $schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
653
        } else {
654
            $schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
655
        }
656
657
        // enabled methods for CorsListener
658
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
659
        try {
660
            $router = $this->getRouter();
661
            // if post route is available we assume everything is readable
662
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
663
        } catch (RouteNotFoundException $exception) {
664
            // only allow read methods
665
            $corsMethods = 'GET, OPTIONS';
666
        }
667
        $request->attributes->set('corsMethods', $corsMethods);
668
669
670
        return $this->render(
671
            'GravitonRestBundle:Main:index.json.twig',
672
            ['response' => $this->serialize($schema)],
673
            $response
674
        );
675
    }
676
677
    /**
678
     * Get the validator
679
     *
680
     * @return ValidatorInterface
681
     */
682
    public function getValidator()
683
    {
684
        return $this->validator;
685
    }
686
687
    /**
688
     * Renders a view.
689
     *
690
     * @param string   $view       The view name
691 2
     * @param array    $parameters An array of parameters to pass to the view
692
     * @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...
693 2
     *
694
     * @return Response A Response instance
695
     */
696
    public function render($view, array $parameters = array(), Response $response = null)
697
    {
698
        return $this->templating->renderResponse($view, $parameters, $response);
699
    }
700
701
    /**
702
     * @param Request $request request
703
     * @return string
704
     */
705
    private function getRouteName(Request $request)
706
    {
707
        $routeName = $request->get('_route');
708
        $routeParts = explode('.', $routeName);
709
        $routeType = end($routeParts);
710
711
        if ($routeType == 'post') {
712
            $routeName = substr($routeName, 0, -4) . 'get';
713
        }
714
715
        return $routeName;
716
    }
717
718
    /**
719 1
     * Security needs to be enabled to get Object.
720
     *
721
     * @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...
722 1
     * @throws PreconditionRequiredHttpException
723 1
     */
724 1
    public function getSecurityUser()
725
    {
726
        /** @var PreAuthenticatedToken $token */
727
        if (($token = $this->tokenStorage->getToken())
728
            && ($user = $token->getUser()) instanceof UserInterface ) {
729
            return $user;
730
        }
731
732
        throw new PreconditionRequiredHttpException('Not allowed');
733
    }
734
}
735