Completed
Push — master ( 5593b2...dd663d )
by Ruben
02:08
created

RouteEndpointType::make()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
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\Exceptions\EndpointGenerationException;
6
use Spatie\LaravelEndpointResources\Formatters\DefaultFormatter;
7
use Spatie\LaravelEndpointResources\Formatters\Endpoint;
8
use Spatie\LaravelEndpointResources\Formatters\FlatFormatter;
9
use Spatie\LaravelEndpointResources\ParameterResolver;
10
use Illuminate\Database\Eloquent\Model;
11
use Illuminate\Routing\Exceptions\UrlGenerationException;
12
use Illuminate\Routing\Route;
13
14
class RouteEndpointType extends EndpointType
15
{
16
    /** @var \Illuminate\Routing\Route */
17
    protected $route;
18
19
    /** @var string|null */
20
    protected $httpVerb;
21
22
    /** @var string|null */
23
    protected $name;
24
25
    public static function make(Route $route): RouteEndpointType
26
    {
27
        return new self($route);
28
    }
29
30
    public function __construct(Route $route)
31
    {
32
        $this->route = $route;
33
    }
34
35
    public function httpVerb(?string $httpVerb): RouteEndpointType
36
    {
37
        $this->httpVerb = $httpVerb;
38
39
        return $this;
40
    }
41
42
    public function name(?string $name): RouteEndpointType
43
    {
44
        $this->name = $name;
45
46
        return $this;
47
    }
48
49
    public function getEndpoints(Model $model = null): array
50
    {
51
        $parameterResolver = new ParameterResolver($model, $this->parameters);
52
53
        try {
54
            $action = action("\\{$this->route->getActionName()}", $parameterResolver->forRoute($this->route));
55
        } catch (UrlGenerationException $exception) {
56
            throw EndpointGenerationException::make($this->route, $model, $this->parameters);
57
        }
58
59
        $endpoint = Endpoint::make(
60
            $this->name ?? $this->route->getActionMethod(),
61
            $this->httpVerb ?? $this->getHttpVerbForRoute($this->route),
62
            $action,
63
            $this->prefix
64
        );
65
66
        $formatter = new DefaultFormatter();
67
68
        return $formatter->format($endpoint);
69
    }
70
71
    private function getHttpVerbForRoute(Route $route): string
72
    {
73
        $httpVerbs = $route->methods;
74
75
        if (count($httpVerbs) === 1) {
76
            return $httpVerbs[0];
77
        }
78
79
        if ($httpVerbs === ['GET', 'HEAD']) {
80
            return 'GET';
81
        }
82
83
        return $httpVerbs[0];
84
    }
85
}
86