Completed
Push — master ( d5f163...f917da )
by Iacovos
9s
created

DefaultCallableStrategy::resolveSafe()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Softius\ResourcesResolver;
4
5
use Interop\Container\ContainerInterface;
6
7
/**
8
 * Class DefaultCallableStrategy.
9
 */
10
class DefaultCallableStrategy implements ResolvableInterface
11
{
12
    const DEFAULT_METHOD_SEPARATOR = '::';
13
14
    /**
15
     * @var ContainerInterface
16
     */
17
    private $container;
18
19
    /**
20
     * @var null|string
21
     */
22
    private $method_separator;
23
24
    /**
25
     * DefaultCallableStrategy constructor.
26
     *
27
     * @param \Interop\Container\ContainerInterface $container
28
     * @param string                                $method_separator
29
     */
30 8
    public function __construct(ContainerInterface $container = null, $method_separator = null)
31
    {
32 8
        $this->container = $container;
33 8
        $this->method_separator = ($method_separator === null) ? self::DEFAULT_METHOD_SEPARATOR : $method_separator;
34 8
    }
35
36
    /**
37
     * @param string $in
38
     *
39
     * @return array
40
     *
41
     * @throws \Exception
42
     */
43 8
    public function resolve($in)
44
    {
45 8
        $pos = strrpos($in, $this->method_separator);
46 8
        if ($pos === false) {
47 1
            throw new \Exception(sprintf('Method separator not found in %s', $in));
48
        }
49
50 7
        $class = substr($in, 0, $pos);
51 7
        $method = substr($in, $pos + strlen($this->method_separator));
52 7
        if ($pos === 0 || $class === 'parent' || $class === 'self') {
53
            // Use backtrace to find the calling Class
54 3
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
55 3
            $class = ($class === 'parent') ? get_parent_class($trace[2]['class']) : $trace[2]['class'];
56 3
        }
57
58 7
        if ($this->container !== null && $this->container->has($class)) {
59 2
            $class = $this->container->get($class);
60 2
        }
61
62 7
        return [$class, $method];
63
    }
64
65
    /**
66
     * @param $in
67
     *
68
     * @return array
69
     *
70
     * @throws \Exception
71
     */
72 3
    public function resolveSafe($in)
73
    {
74 3
        $callable = $this->resolve($in);
75 3
        if (is_callable($callable)) {
76 2
            return $callable;
77
        }
78
79 1
        throw new \Exception(sprintf('Could not resolve %s to a callable', $in));
80
    }
81
}
82