Completed
Push — master ( 0df1f8...958d5f )
by Sébastien
07:01
created

ContainerAwareCallback::call()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.2408
c 0
b 0
f 0
cc 5
nc 6
nop 1
1
<?php
2
3
/*
4
 * This file is part of the StateMachine package.
5
 *
6
 * (c) Alexandre Bacco
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sebdesign\SM\Callback;
13
14
use SM\Callback\Callback;
15
use SM\Event\TransitionEvent;
16
use Illuminate\Contracts\Container\Container as ContainerInterface;
17
18
class ContainerAwareCallback extends Callback
19
{
20
    /**
21
     * @var \Illuminate\Contracts\Container\Container
22
     */
23
    protected $container;
24
25
    /**
26
     * @param array                                     $specs      Specification for the callback to be called
27
     * @param mixed                                     $callable   Closure, callable or string that will be called if specifications pass
28
     * @param \Illuminate\Contracts\Container\Container $container  The service container that will be used to resolve the callable
29
     */
30
    public function __construct(array $specs, $callable, ContainerInterface $container)
31
    {
32
        parent::__construct($specs, $callable);
33
34
        $this->container = $container;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function call(TransitionEvent $event)
41
    {
42
        // Load the services only now (when the callback is actually called)
43
44
        // Resolve 'Class@method' callables
45
        if ($this->isCallableWithAtSign()) {
46
            $this->callable = explode('@', $this->callable);
47
        }
48
49
        // Resolve ['Class', 'method'] callables from the container
50
        if (is_array($this->callable) && is_string($this->callable[0])) {
51
            $id = $this->callable[0];
52
53
            // If the class has no bindings in the container, call method statically.
54
            if (! $this->container->bound($id)) {
55
                return parent::call($event);
56
            }
57
58
            $this->callable[0] = $this->container->make($id);
59
        }
60
61
        return parent::call($event);
62
    }
63
64
    /**
65
     * Determine if the given string is in Class@method syntax.
66
     *
67
     * @return bool
68
     */
69
    protected function isCallableWithAtSign()
70
    {
71
        return is_string($this->callable) && strpos($this->callable, '@') !== false;
72
    }
73
}
74