Completed
Pull Request — master (#4)
by Iacovos
02:39
created

CallableResolver::fillClass()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
ccs 9
cts 9
cp 1
rs 8.2222
cc 7
eloc 7
nc 6
nop 1
crap 7
1
<?php
2
3
namespace Softius\ResourcesResolver;
4
5
use Interop\Container\ContainerInterface;
6
7
/**
8
 * Class CallableResolver.
9
 */
10
class CallableResolver 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 $class
38
     * @return string
39
     */
40 7
    protected function fillClass($class)
41
    {
42
        // Use backtrace to find the calling Class
43 7
        if (empty($class) || $class === 'parent' || $class === 'self') {
44 3
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
45 3
            $class = ($class === 'parent') ? get_parent_class($trace[2]['class']) : $trace[2]['class'];
46 3
        }
47
48 7
        if ($this->container !== null && $this->container->has($class)) {
49 2
            $class = $this->container->get($class);
50 2
        }
51
52 7
        return $class;
53
    }
54
55
    /**
56
     * @param string $in
57
     *
58
     * @return array
59
     *
60
     * @throws \Exception
61
     */
62 8
    public function resolve($in)
63
    {
64 8
        $pos = strrpos($in, $this->method_separator);
65 8
        if ($pos === false) {
66 1
            throw new \Exception(sprintf('Method separator not found in %s', $in));
67
        }
68
69 7
        $class = substr($in, 0, $pos);
70 7
        $class = $this->fillClass($class);
71 7
        $method = substr($in, $pos + strlen($this->method_separator));
72
73 7
        return [$class, $method];
74
    }
75
76
    /**
77
     * @param $in
78
     *
79
     * @return array
80
     *
81
     * @throws \Exception
82
     */
83 3
    public function resolveSafe($in)
84
    {
85 3
        $callable = $this->resolve($in);
86 3
        if (is_callable($callable)) {
87 2
            return $callable;
88
        }
89
90 1
        throw new \Exception(sprintf('Could not resolve %s to a callable', $in));
91
    }
92
}
93