Completed
Push — master ( 834214...ebf38e )
by Ruben
01:35
created

RouteEndpointType::resolveName()   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 0
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 string|null */
16
    protected $httpVerb;
17
18
    /** @var string|null */
19
    protected $name;
20
21
    public static function make(Route $route): RouteEndpointType
22
    {
23
        return new self($route);
24
    }
25
26
    public function __construct(Route $route)
27
    {
28
        $this->route = $route;
29
    }
30
31
    public function httpVerb(?string $httpVerb): RouteEndpointType
32
    {
33
        $this->httpVerb = $httpVerb;
34
35
        return $this;
36
    }
37
38
    public function name(?string $name): RouteEndpointType
39
    {
40
        $this->name = $name;
41
42
        return $this;
43
    }
44
45
    public function getEndpoints(Model $model = null): array
46
    {
47
        $parameterResolver = new ParameterResolver($model, $this->parameters);
48
49
        $action = action("\\{$this->route->getActionName()}", $parameterResolver->forRoute($this->route));
50
51
        return [
52
            $this->resolveName() => [
53
                'method' => $this->httpVerb ?? $this->getHttpVerbForRoute($this->route),
54
                'action' => $action,
55
            ],
56
        ];
57
    }
58
59
    private function resolveName() : string
60
    {
61
        $name = $this->name ?? $this->route->getActionMethod();
62
63
        return "{$this->prefix}$name";
64
    }
65
66
    private function getHttpVerbForRoute(Route $route): string
67
    {
68
        $httpVerbs = $route->methods;
69
70
        if (count($httpVerbs) === 1) {
71
            return $httpVerbs[0];
72
        }
73
74
        if ($httpVerbs === ['GET', 'HEAD']) {
75
            return 'GET';
76
        }
77
78
        return $httpVerbs[0];
79
    }
80
}
81