-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
CatchableCollectionProxy.php
63 lines (49 loc) · 1.62 KB
/
CatchableCollectionProxy.php
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
<?php
namespace Spatie\CollectionMacros\Helpers;
use Closure;
use Illuminate\Support\Enumerable;
use ReflectionFunction;
use Throwable;
/**
* @mixin \Illuminate\Support\Enumerable
*/
class CatchableCollectionProxy
{
protected Enumerable $collection;
protected array $calledMethods = [];
public function __construct(Enumerable $collection)
{
$this->collection = $collection;
}
public function __call(string $method, array $parameters): self
{
$this->calledMethods[] = ['name' => $method, 'parameters' => $parameters];
return $this;
}
public function catch(Closure ...$handlers): Enumerable
{
$originalCollection = $this->collection;
try {
foreach ($this->calledMethods as $calledMethod) {
$this->collection = $this->collection->{$calledMethod['name']}(...$calledMethod['parameters']);
}
} catch (Throwable $exception) {
foreach ($handlers as $callable) {
$type = $this->exceptionType($callable);
if ($exception instanceof $type) {
return $callable($exception, $originalCollection) ?? $originalCollection;
}
}
throw $exception;
}
return $this->collection;
}
private function exceptionType(Closure $callable): string
{
$reflection = new ReflectionFunction($callable);
if (empty($reflection->getParameters())) {
return Throwable::class;
}
return optional($reflection->getParameters()[0]->getType())->getName() ?? Throwable::class;
}
}