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