1 | <?php |
||
15 | class MapFactory extends AbstractFactory |
||
16 | { |
||
17 | /** |
||
18 | * The class map array holds available types, in `[$type => $className]` format. |
||
19 | * @var array $map |
||
20 | */ |
||
21 | private $map = []; |
||
22 | |||
23 | /** |
||
24 | * Add a class name to the available types _map_. |
||
25 | * |
||
26 | * @param string $type The type (class ident). |
||
27 | * @param string $className The FQN of the class. |
||
28 | * @throws InvalidArgumentException If the $type parameter is not a striing or the $className class does not exist. |
||
29 | * @return FactoryInterface Chainable |
||
30 | */ |
||
31 | public function addClass($type, $className) |
||
32 | { |
||
33 | if (!is_string($type)) { |
||
34 | throw new InvalidArgumentException( |
||
35 | 'Type (class key) must be a string' |
||
36 | ); |
||
37 | } |
||
38 | if (!class_exists($className)) { |
||
39 | throw new InvalidArgumentException( |
||
40 | sprintf('Class "%s" is not a valid class name.', $className) |
||
41 | ); |
||
42 | } |
||
43 | |||
44 | $this->map[$type] = $className; |
||
45 | return $this; |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Add multiple types, in a an array of `type` => `className`. |
||
50 | * |
||
51 | * @param array $map The map (key=>classname) to use. |
||
52 | * @return FactoryInterface Chainable |
||
53 | */ |
||
54 | public function setMap(array $map) |
||
55 | { |
||
56 | // Resets (overwrites) map. |
||
57 | $this->map = []; |
||
58 | foreach ($map as $type => $className) { |
||
59 | $this->addClass($type, $className); |
||
60 | } |
||
61 | return $this; |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * Get the map of all types in `[$type => $class]` format. |
||
66 | * |
||
67 | * @return array |
||
68 | */ |
||
69 | public function map() |
||
73 | |||
74 | /** |
||
75 | * The "Map Factory" implements `AbstractFactory`'s `resolve()` abstract method |
||
76 | * by fetching the class ident from the `map` member array. |
||
77 | * |
||
78 | * If the object's `type` is not defined in the class map, an exception will be thrown. |
||
79 | * |
||
80 | * @param string $type The "type" of object to resolve (the object ident). |
||
81 | * @throws InvalidArgumentException If the type parameter is not a string. |
||
82 | * @return string |
||
83 | */ |
||
84 | public function resolve($type) |
||
100 | |||
101 | /** |
||
102 | * The "Map Factory" implements `AbstractFactory`'s `is_resolvable()` abstract method |
||
103 | * by ensuring the class ident is defined in the class map and is a validd class. |
||
104 | * |
||
105 | * @param string $type The "type" of object to resolve (the object ident). |
||
106 | * @throws InvalidArgumentException If the type parameter is not a string. |
||
107 | * @return boolean |
||
108 | */ |
||
109 | public function isResolvable($type) |
||
125 | } |
||
126 |