Completed
Push — master ( ab46c1...42a3a5 )
by Ruben
02:07
created

RouteEndpointType::setName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\LaravelEndpointResources\EndpointTypes;
4
5
use Spatie\LaravelEndpointResources\ParameterResolver;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Routing\Exceptions\UrlGenerationException;
8
use Illuminate\Routing\Route;
9
10
class RouteEndpointType extends EndpointType
11
{
12
    /** @var \Illuminate\Routing\Route */
13
    protected $route;
14
15
    /** @var array */
16
    protected $defaultParameters;
17
18
    /** @var string|null */
19
    protected $httpVerb;
20
21
    /** @var string|null */
22
    protected $name;
23
24
    public function __construct(Route $route, array $defaultParameters = [], string $httpVerb = null)
25
    {
26
        $this->route = $route;
27
        $this->defaultParameters = $defaultParameters;
28
        $this->httpVerb = $httpVerb;
29
    }
30
31
    public function getEndpoints(Model $model = null): array
32
    {
33
        $parameterResolver = new ParameterResolver($model, $this->defaultParameters);
34
35
        $action = null;
36
37
        try {
38
            $action = action(
39
                $this->route->getActionName(),
40
                $parameterResolver->forRoute($this->route)
41
            );
42
        } catch (UrlGenerationException $exception) {
43
            return [];
44
        }
45
46
        return [
47
            $this->name ?? $this->route->getActionMethod() => [
48
                'method' => $this->httpVerb ?? $this->getHttpVerbForRoute($this->route),
49
                'action' => $action,
50
            ],
51
        ];
52
    }
53
54
    public function setName(?string $name) : RouteEndpointType
55
    {
56
        $this->name = $name;
57
58
        return $this;
59
    }
60
61
    protected function getHttpVerbForRoute(Route $route): string
62
    {
63
        $httpVerbs = $route->methods;
64
65
        if (count($httpVerbs) === 1) {
66
            return $httpVerbs[0];
67
        }
68
69
        if ($httpVerbs === ['GET', 'HEAD']) {
70
            return 'GET';
71
        }
72
73
        return $httpVerbs[0];
74
    }
75
}
76