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

DefaultCallableStrategy   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 2
Metric Value
wmc 12
c 4
b 0
f 2
lcom 1
cbo 1
dl 0
loc 72
ccs 23
cts 23
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
B resolve() 0 21 8
A resolveSafe() 0 9 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