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