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

ActionEndpointType::httpVerb()   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 Exception;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Routing\Route;
8
use Illuminate\Routing\Router;
9
10
class ActionEndpointType extends EndpointType
11
{
12
    /** @var array */
13
    private $action;
14
15
    /** @var string|null */
16
    private $httpVerb;
17
18
    /** @var string|null */
19
    private $name;
20
21
    public static function make(array $action): ActionEndpointType
22
    {
23
        return new self($action);
24
    }
25
26
    public function __construct(array $action)
27
    {
28
        $this->action = $action;
29
    }
30
31
    public function httpVerb(string $httpVerb): ActionEndpointType
32
    {
33
        $this->httpVerb = $httpVerb;
34
35
        return $this;
36
    }
37
38
    public function name(?string $name): ActionEndpointType
39
    {
40
        $this->name = $name;
41
42
        return $this;
43
    }
44
45
    public function getEndpoints(Model $model = null): array
46
    {
47
        $formattedAction = $this->formatAction();
48
49
        $route = app(Router::class)
50
            ->getRoutes()
51
            ->getByAction($formattedAction);
52
53
        if ($route === null) {
54
            throw new Exception("Route `{$formattedAction}` does not exist!");
55
        }
56
57
        return RouteEndpointType::make($route)
58
            ->name($this->name)
59
            ->httpVerb($this->httpVerb)
60
            ->prefix($this->prefix)
61
            ->parameters($this->getParameters($model))
62
            ->getEndpoints($model);
63
    }
64
65
    private function formatAction(): string
66
    {
67
        return trim('\\' . implode('@', $this->action), '\\');
68
    }
69
70
    private function getParameters(?Model $model)
71
    {
72
        if (! optional($model)->exists) {
73
            return $this->parameters;
74
        }
75
76
        return array_merge($this->parameters, [$model]);
77
    }
78
}
79