Passed
Pull Request — master (#92)
by Daniel
06:25
created

RouteEventListener   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 28
ccs 0
cts 15
cp 0
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onPreValidate() 0 19 5
A __construct() 0 3 1
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\EventListener\Api;
15
16
use Silverback\ApiComponentsBundle\Entity\Core\Route;
17
use Silverback\ApiComponentsBundle\Helper\Route\RouteGenerator;
18
use Symfony\Component\HttpKernel\Event\ViewEvent;
19
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class RouteEventListener
25
{
26
    private RouteGenerator $routeGenerator;
27
28
    public function __construct(RouteGenerator $routeGenerator)
29
    {
30
        $this->routeGenerator = $routeGenerator;
31
    }
32
33
    public function onPreValidate(ViewEvent $event): void
34
    {
35
        $request = $event->getRequest();
36
        $data = $request->attributes->get('data');
37
        if (
38
            empty($data) ||
39
            !$data instanceof Route ||
40
            'generate' !== $request->attributes->get('_api_collection_operation_name')
41
        ) {
42
            return;
43
        }
44
45
        $page = $data->getPageData() ?? $data->getPage();
46
        if (!$page) {
47
            throw new BadRequestHttpException('You must submit a page or pageData to generate a route.');
48
        }
49
50
        $route = $this->routeGenerator->createFromPage($page, $data);
51
        $request->attributes->set('data', $route);
52
    }
53
}
54