|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\ResourceLinks\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
|
|
|
->formatter($this->formatter) |
|
63
|
|
|
->getEndpoints($model); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
private function formatAction(): string |
|
67
|
|
|
{ |
|
68
|
|
|
return trim('\\' . implode('@', $this->action), '\\'); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
private function getParameters(?Model $model) |
|
72
|
|
|
{ |
|
73
|
|
|
if (! optional($model)->exists) { |
|
74
|
|
|
return $this->parameters; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
return array_merge($this->parameters, [$model]); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|