-
-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathHelpers.php
More file actions
98 lines (81 loc) · 2.38 KB
/
Helpers.php
File metadata and controls
98 lines (81 loc) · 2.38 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
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
declare(strict_types=1);
namespace Saloon\Helpers;
use Closure;
use ReflectionClass;
use Saloon\Http\Request;
use Saloon\Http\Connector;
use Saloon\Http\PendingRequest;
/**
* @internal
*/
final class Helpers
{
/**
* Returns all traits used by a class, its parent classes and trait of their traits.
*
* @param object|class-string $class
* @return array<class-string, class-string>
*/
public static function classUsesRecursive(object|string $class): array
{
if (is_object($class)) {
$class = get_class($class);
}
$results = [];
foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) {
$results += static::traitUsesRecursive($class);
}
return array_unique($results);
}
/**
* Returns all traits used by a trait and its traits.
*
* @param class-string $trait
* @return array<class-string, class-string>
*/
public static function traitUsesRecursive(string $trait): array
{
/** @var array<class-string, class-string> $traits */
$traits = class_uses($trait) ?: [];
foreach ($traits as $trait) {
$traits += static::traitUsesRecursive($trait);
}
return $traits;
}
/**
* Return the default value of the given value.
*/
public static function value(mixed $value, mixed ...$args): mixed
{
return $value instanceof Closure ? $value(...$args) : $value;
}
/**
* Check if a class is a subclass of another.
*
* @param class-string $class
*/
public static function isSubclassOf(string $class, string $subclass): bool
{
if ($class === $subclass) {
return true;
}
return (new ReflectionClass($class))->isSubclassOf($subclass);
}
/**
* Boot a plugin
*
* @param class-string $trait
* @param Connector|Request<mixed> $resource
* @throws \ReflectionException
*/
public static function bootPlugin(PendingRequest $pendingRequest, Connector|Request $resource, string $trait): void
{
$traitReflection = new ReflectionClass($trait);
$bootMethodName = 'boot' . $traitReflection->getShortName();
if (! method_exists($resource, $bootMethodName)) {
return;
}
$resource->{$bootMethodName}($pendingRequest);
}
}