|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Flight Routing. |
|
5
|
|
|
* |
|
6
|
|
|
* PHP version 8.0 and above required |
|
7
|
|
|
* |
|
8
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
|
9
|
|
|
* @copyright 2019 Divine Niiquaye Ibok (https://divinenii.com/) |
|
10
|
|
|
* @license https://opensource.org/licenses/BSD-3-Clause License |
|
11
|
|
|
* |
|
12
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
13
|
|
|
* file that was distributed with this source code. |
|
14
|
|
|
*/ |
|
15
|
|
|
|
|
16
|
|
|
namespace Flight\Routing\Handlers; |
|
17
|
|
|
|
|
18
|
|
|
use Flight\Routing\Exceptions\InvalidControllerException; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* An extendable HTTP Verb-based route handler to provide a RESTful API for a resource. |
|
22
|
|
|
* |
|
23
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
|
24
|
|
|
*/ |
|
25
|
|
|
final class ResourceHandler |
|
26
|
|
|
{ |
|
27
|
|
|
/** |
|
28
|
|
|
* @param string $method The method name eg: action -> getAction |
|
29
|
|
|
*/ |
|
30
|
8 |
|
public function __construct( |
|
31
|
|
|
private string|object $resource, |
|
32
|
|
|
private string $method = 'action' |
|
33
|
|
|
) { |
|
34
|
8 |
|
if (\is_callable($resource) || \is_subclass_of($resource, self::class)) { |
|
35
|
1 |
|
throw new \Flight\Routing\Exceptions\InvalidControllerException( |
|
36
|
|
|
'Expected a class string or class object, got a type of "callable" instead' |
|
37
|
|
|
); |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @return array<int,object|string> |
|
43
|
|
|
*/ |
|
44
|
7 |
|
public function __invoke(string $requestMethod, bool $validate = false): array |
|
45
|
|
|
{ |
|
46
|
7 |
|
$method = \strtolower($requestMethod).\ucfirst($this->method); |
|
47
|
|
|
|
|
48
|
7 |
|
if (\is_string($class = $this->resource)) { |
|
49
|
4 |
|
$class = \ltrim($class, '\\'); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
7 |
|
if ($validate && !\method_exists($class, $method)) { |
|
53
|
1 |
|
$err = 'Method %s() for resource route "%s" is not found.'; |
|
54
|
|
|
|
|
55
|
1 |
|
throw new InvalidControllerException(\sprintf($err, $method, \is_object($class) ? $class::class : $class)); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
6 |
|
return [$class, $method]; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Append a missing namespace to resource class. |
|
63
|
|
|
* |
|
64
|
|
|
* @internal |
|
65
|
|
|
*/ |
|
66
|
1 |
|
public function namespace(string $namespace): self |
|
67
|
|
|
{ |
|
68
|
1 |
|
if (!\is_string($resource = $this->resource) || '\\' === $resource[0]) { |
|
69
|
1 |
|
return $this; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
1 |
|
if (!\str_starts_with($resource, $namespace)) { |
|
73
|
1 |
|
$this->resource = $namespace.$resource; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
1 |
|
return $this; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|