1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\LaravelEndpointResources\EndpointTypes; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Routing\Route; |
7
|
|
|
use Illuminate\Routing\Router; |
8
|
|
|
use Illuminate\Support\Collection; |
9
|
|
|
use Illuminate\Support\Str; |
10
|
|
|
use ReflectionClass; |
11
|
|
|
|
12
|
|
|
class ControllerEndpointType extends EndpointType |
13
|
|
|
{ |
14
|
|
|
/** @var string */ |
15
|
|
|
protected $controller; |
16
|
|
|
|
17
|
|
|
/** @var array */ |
18
|
|
|
protected $defaultParameters; |
19
|
|
|
|
20
|
|
|
/** @var array */ |
21
|
|
|
protected static $cachedRoutes = []; |
22
|
|
|
|
23
|
|
|
public function __construct(string $controller, array $defaultParameters = null) |
24
|
|
|
{ |
25
|
|
|
$this->controller = $controller; |
26
|
|
|
$this->defaultParameters = $defaultParameters ?? []; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function getEndpoints(Model $model = null): array |
30
|
|
|
{ |
31
|
|
|
$controller = new $this->controller(); |
32
|
|
|
|
33
|
|
|
$endpoints = property_exists($controller, 'endPointMethods') |
34
|
|
|
? $controller->endPointMethods |
35
|
|
|
: ['show', 'edit', 'update', 'delete']; |
36
|
|
|
|
37
|
|
|
return $this->resolveEndpoints( |
38
|
|
|
$endpoints, |
39
|
|
|
$model |
40
|
|
|
); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function getCollectionEndpoints(): array |
44
|
|
|
{ |
45
|
|
|
$controller = new $this->controller(); |
46
|
|
|
|
47
|
|
|
$endpoints = property_exists($controller, 'globalEndPointMethods') |
48
|
|
|
? $controller->globalEndPointMethods |
49
|
|
|
: ['index', 'store', 'create']; |
50
|
|
|
|
51
|
|
|
return $this->resolveEndpoints($endpoints); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
protected function resolveEndpoints(array $methodsToInclude, Model $model = null) : array |
55
|
|
|
{ |
56
|
|
|
return self::getRoutesForController($this->controller) |
57
|
|
|
->filter(function (Route $route) use ($methodsToInclude) { |
58
|
|
|
return in_array($route->getActionMethod(), $methodsToInclude); |
59
|
|
|
})->mapWithKeys(function (Route $route) use ($model) { |
60
|
|
|
$routesToEndpoint = new RouteEndpointType($route, $this->defaultParameters); |
61
|
|
|
|
62
|
|
|
return $routesToEndpoint->getEndpoints($model); |
63
|
|
|
})->toArray(); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected static function getRoutesForController(string $controller): Collection |
67
|
|
|
{ |
68
|
|
|
if (in_array($controller, self::$cachedRoutes)) { |
69
|
|
|
return self::$cachedRoutes[$controller]; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$routes = collect(resolve(Router::class)->getRoutes()->getRoutes()); |
73
|
|
|
|
74
|
|
|
self::$cachedRoutes[$controller] = $routes |
75
|
|
|
->filter(function (Route $route) use ($controller) { |
76
|
|
|
return $controller === Str::before($route->getActionName(), '@'); |
77
|
|
|
}); |
78
|
|
|
|
79
|
|
|
return self::$cachedRoutes[$controller]; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|