Completed
Push — feature/EVO-8323-configurable-... ( 7d025f...474bcc )
by
unknown
09:08
created

RestController::patchAction()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 52
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 52
ccs 0
cts 32
cp 0
rs 9.4929
cc 3
eloc 27
nc 4
nop 2
crap 12

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\CollectionCache;
9
use Graviton\ExceptionBundle\Exception\DeserializationException;
10
use Graviton\ExceptionBundle\Exception\InvalidJsonPatchException;
11
use Graviton\ExceptionBundle\Exception\MalformedInputException;
12
use Graviton\ExceptionBundle\Exception\SerializationException;
13
use Graviton\JsonSchemaBundle\Exception\ValidationException;
14
use Graviton\RestBundle\Model\DocumentModel;
15
use Graviton\SchemaBundle\SchemaUtils;
16
use Graviton\RestBundle\Service\RestUtilsInterface;
17
use Graviton\SecurityBundle\Service\SecurityUtils;
18
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\Routing\Exception\RouteNotFoundException;
23
use Symfony\Bundle\FrameworkBundle\Routing\Router;
24
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
25
use Rs\Json\Patch;
26
use Rs\Json\Patch\InvalidPatchDocumentJsonException;
27
use Rs\Json\Patch\InvalidTargetDocumentJsonException;
28
use Rs\Json\Patch\InvalidOperationException;
29
use Rs\Json\Patch\FailedTestException;
30
use Graviton\RestBundle\Service\JsonPatchValidator;
31
32
/**
33
 * This is a basic rest controller. It should fit the most needs but if you need to add some
34
 * extra functionality you can extend it and overwrite single/all actions.
35
 * You can also extend the model class to add some extra logic before save
36
 *
37
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
38
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
39
 * @link     http://swisscom.ch
40
 */
41
class RestController
42
{
43
    /**
44
     * @var DocumentModel
45
     */
46
    private $model;
47
48
    /**
49
     * @var ContainerInterface service_container
50
     */
51
    private $container;
52
53
    /**
54
     * @var Response
55
     */
56
    private $response;
57
58
    /**
59
     * @var RestUtilsInterface
60
     */
61
    private $restUtils;
62
63
    /**
64
     * @var SchemaUtils
65
     */
66
    private $schemaUtils;
67
68
    /**
69
     * @var Router
70
     */
71
    private $router;
72
73
    /**
74
     * @var EngineInterface
75
     */
76
    private $templating;
77
78
    /**
79
     * @var JsonPatchValidator
80
     */
81
    private $jsonPatchValidator;
82
83
    /**
84
     * @var SecurityUtils
85
     */
86
    protected $securityUtils;
87
88
    /** @var CollectionCache */
89
    protected $collectionCache;
90
91
    /**
92
     * @param Response           $response    Response
93
     * @param RestUtilsInterface $restUtils   Rest utils
94
     * @param Router             $router      Router
95
     * @param EngineInterface    $templating  Templating
96
     * @param ContainerInterface $container   Container
97
     * @param SchemaUtils        $schemaUtils Schema utils
98
     * @param CollectionCache    $cache       Cache service
99
     */
100
    public function __construct(
101
        Response $response,
102
        RestUtilsInterface $restUtils,
103
        Router $router,
104
        EngineInterface $templating,
105
        ContainerInterface $container,
106
        SchemaUtils $schemaUtils,
107
        CollectionCache $cache
108
    ) {
109
        $this->response = $response;
110
        $this->restUtils = $restUtils;
111
        $this->router = $router;
112
        $this->templating = $templating;
113
        $this->container = $container;
114
        $this->schemaUtils = $schemaUtils;
115
        $this->collectionCache = $cache;
116
    }
117
118
    /**
119
     * Setter for the SecurityUtils
120
     *
121
     * @param SecurityUtils $securityUtils The securityUtils service
122
     * @return void
123
     */
124
    public function setSecurityUtils(SecurityUtils $securityUtils)
125
    {
126
        $this->securityUtils = $securityUtils;
127
    }
128
129
    /**
130
     * @param JsonPatchValidator $jsonPatchValidator Service for validation json patch
131
     * @return void
132
     */
133
    public function setJsonPatchValidator(JsonPatchValidator $jsonPatchValidator)
134
    {
135
        $this->jsonPatchValidator = $jsonPatchValidator;
136
    }
137
138
    /**
139
     * Get the container object
140
     *
141
     * @return \Symfony\Component\DependencyInjection\ContainerInterface
142
     *
143
     * @obsolete
144
     */
145
    public function getContainer()
146
    {
147
        return $this->container;
148
    }
149
150
    /**
151
     * Returns a single record
152
     *
153
     * @param Request $request Current http request
154
     * @param string  $id      ID of record
155
     *
156
     * @return \Symfony\Component\HttpFoundation\Response $response Response with result or error
157
     */
158
    public function getAction(Request $request, $id)
159
    {
160
        $repository = $this->model->getRepository();
161
        if (!$document = $this->collectionCache->getByRepository($repository, $id)) {
162
            // Check and wait if another update is being processed
163
            // if there is no cache else we need to wait if there is a lock or possible 404
164
            $this->collectionCache->updateOperationCheck($repository, $id);
165
            $document = $this->serialize($this->findRecord($id, $request));
0 ignored issues
show
Bug introduced by
It seems like $this->findRecord($id, $request) targeting Graviton\RestBundle\Cont...ontroller::findRecord() can also be of type array; however, Graviton\RestBundle\Cont...Controller::serialize() does only seem to accept object|array<integer,object>, 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...
166
            $this->collectionCache->setByRepository($repository, $document, $id);
167
        }
168
169
        $response = $this->getResponse()
170
            ->setStatusCode(Response::HTTP_OK)
171
            ->setContent($document);
172
173
        return $response;
174
    }
175
176
    /**
177
     * Get the response object
178
     *
179
     * @return \Symfony\Component\HttpFoundation\Response $response Response object
180
     */
181
    public function getResponse()
182
    {
183
        return $this->response;
184
    }
185
186
    /**
187
     * Get a single record from database or throw an exception if it doesn't exist
188
     *
189
     * @param mixed   $id      Record id
190
     * @param Request $request request
0 ignored issues
show
Documentation introduced by
Should the type for parameter $request not be null|Request?

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...
191
     *
192
     * @return object $record Document object
0 ignored issues
show
Documentation introduced by
Should the return type not be array|object? 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...
193
     */
194
    protected function findRecord($id, Request $request = null)
195
    {
196
        return $this->getModel()->find($id, $request);
197
    }
198
199
    /**
200
     * Return the model
201
     *
202
     * @throws \Exception in case no model was defined.
203
     *
204
     * @return DocumentModel $model Model
205
     */
206
    public function getModel()
207
    {
208
        if (!$this->model) {
209
            throw new \Exception('No model is set for this controller');
210
        }
211
212
        return $this->model;
213
    }
214
215
    /**
216
     * Set the model class
217
     *
218
     * @param DocumentModel $model Model class
219
     *
220
     * @return self
221
     */
222
    public function setModel(DocumentModel $model)
223
    {
224
        $this->model = $model;
225
226
        return $this;
227
    }
228
229
    /**
230
     * Serialize the given record and throw an exception if something went wrong
231
     *
232
     * @param object|object[] $result Record(s)
233
     *
234
     * @throws \Graviton\ExceptionBundle\Exception\SerializationException
235
     *
236
     * @return string $content Json content
237
     */
238
    protected function serialize($result)
239
    {
240
        $response = $this->getResponse();
241
242
        try {
243
            // array is serialized as an object {"0":{...},"1":{...},...} when data contains an empty objects
244
            // we serialize each item because we can assume this bug affects only root array element
245
            if (is_array($result) && array_keys($result) === range(0, count($result) - 1)) {
246
                $result = array_map(
247
                    function ($item) {
248
                        return $this->getRestUtils()->serializeContent($item);
249
                    },
250
                    $result
251
                );
252
253
                return '['.implode(',', array_filter($result)).']';
254
            }
255
256
            return $this->getRestUtils()->serializeContent($result);
0 ignored issues
show
Bug introduced by
It seems like $result defined by parameter $result on line 238 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...
257
        } catch (\Exception $e) {
258
            $exception = new SerializationException($e);
259
            $exception->setResponse($response);
260
            throw $exception;
261
        }
262
    }
263
264
    /**
265
     * Get RestUtils service
266
     *
267
     * @return \Graviton\RestBundle\Service\RestUtils
268
     */
269
    public function getRestUtils()
270
    {
271
        return $this->restUtils;
272
    }
273
274
    /**
275
     * Returns all records
276
     *
277
     * @param Request $request Current http request
278
     *
279
     * @return \Symfony\Component\HttpFoundation\Response $response Response with result or error
280
     */
281
    public function allAction(Request $request)
282
    {
283
        $model = $this->getModel();
284
285
        $response = $this->getResponse()
286
            ->setStatusCode(Response::HTTP_OK)
287
            ->setContent($this->serialize($model->findAll($request)));
288
289
        return $response;
290
    }
291
292
    /**
293
     * Writes a new Entry to the database
294
     *
295
     * @param Request $request Current http request
296
     *
297
     * @return \Symfony\Component\HttpFoundation\Response $response Result of action with data (if successful)
298
     */
299
    public function postAction(Request $request)
300
    {
301
        // Get the response object from container
302
        $response = $this->getResponse();
303
        $model = $this->getModel();
304
305
        $this->restUtils->checkJsonRequest($request, $response, $this->getModel());
306
307
        $record = $this->validateRequest($request->getContent(), $model);
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\Cont...ller::validateRequest() does only seem to accept object|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...
308
309
        // Insert the new record
310
        $record = $this->getModel()->insertRecord($record);
311
312
        // store id of new record so we dont need to reparse body later when needed
313
        $request->attributes->set('id', $record->getId());
314
315
        // Set status code
316
        $response->setStatusCode(Response::HTTP_CREATED);
317
318
        $response->headers->set(
319
            'Location',
320
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
321
        );
322
323
        return $response;
324
    }
325
326
    /**
327
     * Validates the current request on schema violations. If there are errors,
328
     * the exception is thrown. If not, the deserialized record is returned.
329
     *
330
     * @param object|string $content \stdClass of the request content
331
     * @param DocumentModel $model   the model to check the schema for
332
     *
333
     * @return \Graviton\JsonSchemaBundle\Exception\ValidationExceptionError[]
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...
334
     * @throws \Exception
335
     */
336
    protected function validateRequest($content, DocumentModel $model)
337
    {
338
        $errors = $this->restUtils->validateContent($content, $model);
339
        if (!empty($errors)) {
340
            throw new ValidationException($errors);
341
        }
342
        return $this->deserialize($content, $model->getEntityClass());
0 ignored issues
show
Bug introduced by
It seems like $content defined by parameter $content on line 336 can also be of type object; however, Graviton\RestBundle\Cont...ntroller::deserialize() does only seem to accept string, 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...
343
    }
344
345
    /**
346
     * Deserialize the given content throw an exception if something went wrong
347
     *
348
     * @param string $content       Request content
349
     * @param string $documentClass Document class
350
     *
351
     * @throws DeserializationException
352
     *
353
     * @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...
354
     */
355
    protected function deserialize($content, $documentClass)
356
    {
357
        $response = $this->getResponse();
358
359
        try {
360
            $record = $this->getRestUtils()->deserializeContent(
361
                $content,
362
                $documentClass
363
            );
364
        } catch (\Exception $e) {
365
            // pass the previous exception in this case to get the error message in the handler
366
            // http://php.net/manual/de/exception.getprevious.php
367
            $exception = new DeserializationException("Deserialization failed", $e);
368
369
            // at the moment, the response has to be set on the exception object.
370
            // try to refactor this and return the graviton.rest.response if none is set...
371
            $exception->setResponse($response);
372
            throw $exception;
373
        }
374
375
        return $record;
376
    }
377
378
    /**
379
     * Get the router from the dic
380
     *
381
     * @return Router
382
     */
383
    public function getRouter()
384
    {
385
        return $this->router;
386
    }
387
388
    /**
389
     * Update a record
390
     *
391
     * @param Number  $id      ID of record
392
     * @param Request $request Current http request
393
     *
394
     * @throws MalformedInputException
395
     *
396
     * @return Response $response Result of action with data (if successful)
397
     */
398
    public function putAction($id, Request $request)
399
    {
400
        $response = $this->getResponse();
401
        $model = $this->getModel();
402
403
        $this->restUtils->checkJsonRequest($request, $response, $this->getModel());
404
405
        // Check and wait if another update is being processed
406
        $this->collectionCache->updateOperationCheck($model->getRepository(), $id);
407
        $this->collectionCache->addUpdateLock($model->getRepository(), $id);
408
409
        $record = $this->validateRequest($request->getContent(), $model);
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\Cont...ller::validateRequest() does only seem to accept object|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...
410
411
        // handle missing 'id' field in input to a PUT operation
412
        // if it is settable on the document, let's set it and move on.. if not, inform the user..
413
        if ($record->getId() != $id) {
414
            // try to set it..
415
            if (is_callable(array($record, 'setId'))) {
416
                $record->setId($id);
417
            } else {
418
                $this->collectionCache->releaseUpdateLock($model->getRepository(), $id);
419
                throw new MalformedInputException('No ID was supplied in the request payload.');
420
            }
421
        }
422
423
        $repository = $model->getRepository();
424
425
        // And update the record, if everything is ok
426
        if (!$this->getModel()->recordExists($id)) {
427
            $this->getModel()->insertRecord($record, false);
428
        } else {
429
            $this->getModel()->updateRecord($id, $record, false);
430
        }
431
432
        $this->collectionCache->releaseUpdateLock($repository, $id);
433
434
        // Set status code
435
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
436
437
        // store id of new record so we dont need to reparse body later when needed
438
        $request->attributes->set('id', $record->getId());
439
440
        return $response;
441
    }
442
443
    /**
444
     * Patch a record
445
     *
446
     * @param Number  $id      ID of record
447
     * @param Request $request Current http request
448
     *
449
     * @throws MalformedInputException
450
     *
451
     * @return Response $response Result of action with data (if successful)
452
     */
453
    public function patchAction($id, Request $request)
454
    {
455
        $response = $this->getResponse();
456
        $model = $this->getModel();
457
458
        // Check JSON Patch request
459
        $this->restUtils->checkJsonRequest($request, $response, $model);
460
        $this->restUtils->checkJsonPatchRequest(json_decode($request->getContent(), 1));
461
462
        // Check and wait if another update is being processed
463
        $this->collectionCache->updateOperationCheck($model->getRepository(), $id);
464
        $this->collectionCache->addUpdateLock($model->getRepository(), $id);
465
466
        // Find record && apply $ref converter
467
        $record = $this->findRecord($id);
468
        $jsonDocument = $this->serialize($record);
0 ignored issues
show
Bug introduced by
It seems like $record defined by $this->findRecord($id) on line 467 can also be of type array; however, Graviton\RestBundle\Cont...Controller::serialize() does only seem to accept object|array<integer,object>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
469
470
        // Check/validate JSON Patch
471
        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...
472
            $this->collectionCache->releaseUpdateLock($model->getRepository(), $id);
473
            throw new InvalidJsonPatchException($this->jsonPatchValidator->getException()->getMessage());
474
        }
475
476
        try {
477
            // Apply JSON patches
478
            $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...
479
            $patchedDocument = $patch->apply();
480
        } catch (\Exception $e) {
481
            $this->collectionCache->releaseUpdateLock($model->getRepository(), $id);
482
            throw new InvalidJsonPatchException($e->getMessage());
483
        }
484
485
        // Validate result object
486
        $model = $this->getModel();
487
        $record = $this->validateRequest($patchedDocument, $model);
488
489
        // Update object
490
        $this->getModel()->updateRecord($id, $record);
491
492
        $this->collectionCache->releaseUpdateLock($model->getRepository(), $id);
493
494
        // Set status code
495
        $response->setStatusCode(Response::HTTP_OK);
496
497
        // Set Content-Location header
498
        $response->headers->set(
499
            'Content-Location',
500
            $this->getRouter()->generate($this->getRouteName($request), array('id' => $record->getId()))
501
        );
502
503
        return $response;
504
    }
505
506
    /**
507
     * Deletes a record
508
     *
509
     * @param Number $id ID of record
510
     *
511
     * @return Response $response Result of the action
512
     */
513
    public function deleteAction($id)
514
    {
515
        $response = $this->getResponse();
516
        $model = $this->getModel();
517
518
        // Check and wait if another update is being processed
519
        $this->collectionCache->updateOperationCheck($model->getRepository(), $id);
520
        $this->collectionCache->addUpdateLock($model->getRepository(), $id, 1);
521
522
        // does this record exist?
523
        $this->findRecord($id);
524
525
        $this->getModel()->deleteRecord($id);
526
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
527
528
        $this->collectionCache->releaseUpdateLock($model->getRepository(), $id);
529
530
        return $response;
531
    }
532
533
    /**
534
     * Return OPTIONS results.
535
     *
536
     * @param Request $request Current http request
537
     *
538
     * @throws SerializationException
539
     * @return \Symfony\Component\HttpFoundation\Response $response Result of the action
540
     */
541
    public function optionsAction(Request $request)
542
    {
543
        list($app, $module, , $modelName) = explode('.', $request->attributes->get('_route'));
544
545
        $response = $this->response;
546
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
547
548
        // enabled methods for CorsListener
549
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
550
        try {
551
            $router = $this->getRouter();
552
            // if post route is available we assume everything is readable
553
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
554
        } catch (RouteNotFoundException $exception) {
555
            // only allow read methods
556
            $corsMethods = 'GET, OPTIONS';
557
        }
558
        $request->attributes->set('corsMethods', $corsMethods);
559
560
        return $response;
561
    }
562
563
564
    /**
565
     * Return schema GET results.
566
     *
567
     * @param Request $request Current http request
568
     * @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...
569
     *
570
     * @throws SerializationException
571
     * @return \Symfony\Component\HttpFoundation\Response $response Result of the action
572
     */
573
    public function schemaAction(Request $request, $id = null)
574
    {
575
        $request->attributes->set('schemaRequest', true);
576
577
        list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
578
579
        $response = $this->response;
580
        $response->setStatusCode(Response::HTTP_OK);
581
        $response->setPublic();
582
583
        if (!$id && $schemaType != 'canonicalIdSchema') {
584
            $schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
585
        } else {
586
            $schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
587
        }
588
589
        // enabled methods for CorsListener
590
        $corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
591
        try {
592
            $router = $this->getRouter();
593
            // if post route is available we assume everything is readable
594
            $router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
595
        } catch (RouteNotFoundException $exception) {
596
            // only allow read methods
597
            $corsMethods = 'GET, OPTIONS';
598
        }
599
        $request->attributes->set('corsMethods', $corsMethods);
600
601
602
        return $this->render(
603
            'GravitonRestBundle:Main:index.json.twig',
604
            ['response' => $this->serialize($schema)],
605
            $response
606
        );
607
    }
608
609
    /**
610
     * Renders a view.
611
     *
612
     * @param string   $view       The view name
613
     * @param array    $parameters An array of parameters to pass to the view
614
     * @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...
615
     *
616
     * @return Response A Response instance
617
     */
618
    public function render($view, array $parameters = array(), Response $response = null)
619
    {
620
        return $this->templating->renderResponse($view, $parameters, $response);
621
    }
622
623
    /**
624
     * @param Request $request request
625
     * @return string
626
     */
627
    private function getRouteName(Request $request)
628
    {
629
        $routeName = $request->get('_route');
630
        $routeParts = explode('.', $routeName);
631
        $routeType = end($routeParts);
632
633
        if ($routeType == 'post') {
634
            $routeName = substr($routeName, 0, -4) . 'get';
635
        }
636
637
        return $routeName;
638
    }
639
640
    /**
641
     * Security needs to be enabled to get Object.
642
     *
643
     * @return String
0 ignored issues
show
Documentation introduced by
Should the return type not be \Graviton\SecurityBundle\Entities\SecurityUser?

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...
644
     * @throws UsernameNotFoundException
645
     */
646
    public function getSecurityUser()
647
    {
648
        return $this->securityUtils->getSecurityUser();
649
    }
650
}
651