|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Sebdesign\SM\Callback; |
|
4
|
|
|
|
|
5
|
|
|
use SM\Callback\Callback; |
|
6
|
|
|
use SM\Event\TransitionEvent; |
|
7
|
|
|
use Illuminate\Contracts\Container\Container as ContainerInterface; |
|
8
|
|
|
|
|
9
|
|
|
class ContainerAwareCallback extends Callback |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var \Illuminate\Contracts\Container\Container |
|
13
|
|
|
*/ |
|
14
|
|
|
protected $container; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param array $specs Specification for the callback to be called |
|
18
|
|
|
* @param mixed $callable Closure, callable or string that will be called if specifications pass |
|
19
|
|
|
* @param \Illuminate\Contracts\Container\Container $container The service container that will be used to resolve the callable |
|
20
|
|
|
*/ |
|
21
|
|
|
public function __construct(array $specs, $callable, ContainerInterface $container) |
|
22
|
|
|
{ |
|
23
|
|
|
parent::__construct($specs, $callable); |
|
24
|
|
|
|
|
25
|
|
|
$this->container = $container; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* {@inheritDoc} |
|
30
|
|
|
*/ |
|
31
|
|
|
public function call(TransitionEvent $event) |
|
32
|
|
|
{ |
|
33
|
|
|
if (isset($this->specs['args'])) { |
|
34
|
|
|
return parent::call($event); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$callable = $this->filterCallable($this->callable, $event); |
|
38
|
|
|
|
|
39
|
|
|
return BoundCallback::call($this->container, $callable, [ |
|
|
|
|
|
|
40
|
|
|
'event' => $event, |
|
41
|
|
|
$event->getStateMachine()->getObject(), |
|
42
|
|
|
]); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* {@inheritDoc} |
|
47
|
|
|
*/ |
|
48
|
|
|
protected function filterCallable($callable, TransitionEvent $event) |
|
49
|
|
|
{ |
|
50
|
|
|
if ($this->isCallableWithAtSign($callable)) { |
|
51
|
|
|
$callable = explode('@', $callable); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
$callable = parent::filterCallable($callable, $event); |
|
55
|
|
|
|
|
56
|
|
|
if (is_array($callable) && is_string($callable[0])) { |
|
57
|
|
|
return [$this->container->make($callable[0]), $callable[1]]; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return $callable; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* Determine if the given string is in Class@method syntax. |
|
65
|
|
|
* |
|
66
|
|
|
* @param mixed $callback |
|
67
|
|
|
* @return bool |
|
68
|
|
|
*/ |
|
69
|
|
|
protected function isCallableWithAtSign($callback) |
|
70
|
|
|
{ |
|
71
|
|
|
return is_string($callback) && strpos($callback, '@') !== false; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|
This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.
Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.