1: <?php
2:
3: namespace Charcoal\Factory;
4:
5: use \InvalidArgumentException;
6:
7: 8: 9:
10: class GenericResolver
11: {
12: 13: 14:
15: private $prefix = '';
16:
17: 18: 19:
20: private $suffix = '';
21:
22: 23: 24:
25: private $capitals;
26:
27: 28: 29:
30: private $replacements;
31:
32: 33: 34:
35: public function __construct(array $data = null)
36: {
37: if (!isset($data['prefix'])) {
38: $data['prefix'] = '';
39: }
40: if (!isset($data['suffix'])) {
41: $data['suffix'] = '';
42: }
43: if (!isset($data['capitals'])) {
44: $data['capitals'] = [
45: '-',
46: '\\',
47: '/',
48: '.',
49: '_'
50: ];
51: }
52: if (!isset($data['replacements'])) {
53: $data['replacements'] = [
54: '-'=>'',
55: '/'=>'\\',
56: '.'=>'_'
57: ];
58: }
59: $this->prefix = $data['prefix'];
60: $this->suffix = $data['suffix'];
61: $this->capitals = $data['capitals'];
62: $this->replacements = $data['replacements'];
63: }
64:
65: 66: 67: 68: 69: 70:
71: public function __invoke($type)
72: {
73: return $this->resolve($type);
74: }
75:
76: 77: 78: 79: 80: 81: 82:
83: public function resolve($type)
84: {
85: if (!is_string($type)) {
86: throw new InvalidArgumentException(
87: 'Can not resolve class ident: type must be a string'
88: );
89: }
90:
91:
92: $type = $this->prefix.$type.$this->suffix;
93:
94: $capitalizeNext = function(&$i) {
95: $i = ucfirst($i);
96: };
97:
98: $capitals = $this->capitals;
99: foreach ($capitals as $cap) {
100: $expl = explode($cap, $type);
101: array_walk($expl, $capitalizeNext);
102: $type = implode($cap, $expl);
103: }
104:
105: $replacements = $this->replacements;
106: foreach ($replacements as $rep => $target) {
107: $type = str_replace($rep, $target, $type);
108: }
109:
110: $class = '\\'.trim($type, '\\');
111:
112: return $class;
113: }
114: }
115: