forked from Respect/Rest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractSyncedRoutine.php
More file actions
85 lines (67 loc) · 2.43 KB
/
AbstractSyncedRoutine.php
File metadata and controls
85 lines (67 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace Respect\Rest\Routines;
use Closure;
use ReflectionClass;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use ReflectionObject;
use ReflectionParameter;
use Reflector;
use Respect\Rest\DispatchContext;
use Respect\Rest\ResolvesCallbackArguments;
use function assert;
use function is_array;
use function is_callable;
use function is_string;
/** Base class for routines that sync parameters */
// phpcs:ignore SlevomatCodingStandard.Classes.SuperfluousAbstractClassNaming.SuperfluousPrefix
abstract class AbstractSyncedRoutine extends AbstractRoutine implements ParamSynced
{
use ResolvesCallbackArguments;
protected Reflector|null $reflection = null;
/** @return array<int, ReflectionParameter> */
public function getParameters(): array
{
$reflection = $this->getReflection();
if ($reflection instanceof ReflectionFunctionAbstract) {
return $reflection->getParameters();
}
return [];
}
/** @param array<int, mixed> $params */
public function execute(DispatchContext $context, array $params): mixed
{
$callback = $this->getCallback();
if (is_string($callback)) {
$reflection = $this->getReflection();
if ($reflection instanceof ReflectionClass) {
$routineInstance = $reflection->newInstanceArgs($params);
assert(is_callable($routineInstance));
return $routineInstance();
}
}
$reflection = $this->getReflection();
if ($reflection instanceof ReflectionFunction || $reflection instanceof ReflectionMethod) {
$args = $this->resolveCallbackArguments($reflection, $params, $context);
return $callback(...$args);
}
return $callback(...$params);
}
protected function getReflection(): Reflector
{
$callback = $this->getCallback();
if (is_array($callback)) {
return new ReflectionMethod($callback[0], $callback[1]);
}
if ($callback instanceof Closure) {
return new ReflectionFunction($callback);
}
if (is_string($callback)) {
/** @var class-string $callback */ // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.MissingVariable
return new ReflectionClass($callback);
}
return new ReflectionObject($callback);
}
}