|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\CollectionMacros\Helpers; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Illuminate\Support\Enumerable; |
|
7
|
|
|
use ReflectionFunction; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* @mixin \Illuminate\Support\Enumerable |
|
11
|
|
|
*/ |
|
12
|
|
|
class CatchableCollectionProxy |
|
13
|
|
|
{ |
|
14
|
|
|
/** @var \Illuminate\Support\Enumerable */ |
|
15
|
|
|
protected $collection; |
|
16
|
|
|
|
|
17
|
|
|
/** @var array */ |
|
18
|
|
|
protected $calledMethods = []; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct(Enumerable $collection) |
|
21
|
|
|
{ |
|
22
|
|
|
$this->collection = $collection; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @param string $method |
|
27
|
|
|
* @param array $parameters |
|
28
|
|
|
* |
|
29
|
|
|
* @return $this |
|
30
|
|
|
*/ |
|
31
|
|
|
public function __call($method, $parameters) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->calledMethods[] = ['name' => $method, 'parameters' => $parameters]; |
|
34
|
|
|
|
|
35
|
|
|
return $this; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param \Closure[] $handlers |
|
40
|
|
|
* |
|
41
|
|
|
* @return \Illuminate\Support\Enumerable |
|
42
|
|
|
* @throws \Exception |
|
43
|
|
|
*/ |
|
44
|
|
|
public function catch(...$handlers) |
|
45
|
|
|
{ |
|
46
|
|
|
$originalCollection = $this->collection; |
|
47
|
|
|
|
|
48
|
|
|
try { |
|
49
|
|
|
foreach ($this->calledMethods as $calledMethod) { |
|
50
|
|
|
$this->collection = $this->collection->{$calledMethod['name']}(...$calledMethod['parameters']); |
|
51
|
|
|
} |
|
52
|
|
|
} catch (Exception $exception) { |
|
53
|
|
|
foreach ($handlers as $callable) { |
|
54
|
|
|
$type = $this->exceptionType($callable); |
|
55
|
|
|
if ($exception instanceof $type) { |
|
56
|
|
|
return $callable($exception, $originalCollection) ?? $originalCollection; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
throw $exception; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return $this->collection; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
private function exceptionType($callable) |
|
67
|
|
|
{ |
|
68
|
|
|
$reflection = new ReflectionFunction($callable); |
|
69
|
|
|
|
|
70
|
|
|
if (empty($reflection->getParameters())) { |
|
71
|
|
|
return Exception::class; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return optional($reflection->getParameters()[0]->getType())->getName() ?? Exception::class; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|