Completed
Push — master ( 4d7d0c...65bf09 )
by Mathieu
02:04
created

AbstractFactory::setBaseClass()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 26
Code Lines 15

Duplication

Lines 10
Ratio 38.46 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 10
loc 26
rs 6.7272
cc 7
eloc 15
nc 9
nop 1
1
<?php
2
3
namespace Charcoal\Factory;
4
5
// Dependencies from `PHP`
6
use \Exception;
7
use \InvalidArgumentException;
8
9
// Local namespace dependencies
10
use \Charcoal\Factory\FactoryInterface;
11
12
/**
13
 * Full implementation, as Abstract class, of the FactoryInterface.
14
 */
15
abstract class AbstractFactory implements FactoryInterface
16
{
17
    /**
18
     * If a base class is set, then it must be ensured that the
19
     * @var string $baseClass
20
     */
21
    private $baseClass = '';
22
    /**
23
     *
24
     * @var string $defaultClass
25
     */
26
    private $defaultClass = '';
27
28
    /**
29
     * Keeps loaded instances in memory, in `[$type => $instance]` format.
30
     * Used with the `get()` method only.
31
     * @var array $instances
32
     */
33
    private $instances = [];
34
35
    /**
36
     * Create a new instance of a class, by type.
37
     *
38
     * Unlike `get()`, this method *always* return a new instance of the requested class.
39
     *
40
     * @param string $type The type (class ident).
41
     * @param array  $args The constructor arguments (optional).
42
     * @throws Exception If the base class is set and  the resulting instance is not of the base class.
43
     * @throws InvalidArgumentException If type argument is not a string or is not an available type.
44
     * @return mixed The instance / object
45
     */
46
    public function create($type, array $args = null)
47
    {
48
        if (!is_string($type)) {
49
            throw new InvalidArgumentException(
50
                sprintf(
51
                    '%s: Type must be a string.',
52
                    get_called_class()
53
                )
54
            );
55
        }
56
57
        if ($this->isResolvable($type) === false) {
58
            $defaultClass = $this->defaultClass();
59
            if ($defaultClass !== '') {
60
                return new $defaultClass($args);
61
            } else {
62
                $e = new InvalidArgumentException(
63
                    sprintf(
64
                        '%1$s: Type "%2$s" is not a valid type. (Using default class "%3$s")',
65
                        get_called_class(),
66
                        $type,
67
                        $defaultClass
68
                    )
69
                );
70
71
                throw $e;
72
            }
73
        }
74
75
        // Create the object from the type's class name.
76
        $classname = $this->resolve($type);
77
        $obj = new $classname($args);
78
79
80
        // Ensure base class is respected, if set.
81
        $baseClass = $this->baseClass();
82
        if ($baseClass !== '' && !($obj instanceof $baseClass)) {
83
            throw new Exception(
84
                sprintf(
85
                    '%1$s: Object is not a valid "%2$s" class',
86
                    get_called_class(),
87
                    $baseClass
88
                )
89
            );
90
        }
91
92
        return $obj;
93
    }
94
95
    /**
96
     * Get (load or create) an instance of a class, by type.
97
     *
98
     * Unlike `create()` (which always call a `new` instance), this function first tries to load / reuse
99
     * an already created object of this type, from memory.
100
     *
101
     * @param string $type The type (class ident).
102
     * @param array  $args The constructor arguments (optional).
103
     * @throws InvalidArgumentException If type argument is not a string.
104
     * @return mixed The instance / object
105
     */
106
    public function get($type, array $args = null)
107
    {
108
        if (!is_string($type)) {
109
            throw new InvalidArgumentException(
110
                'Type must be a string.'
111
            );
112
        }
113
        if (!isset($this->instances[$type]) || $this->instances[$type] === null) {
114
            $this->instances[$type] = $this->create($type, $args);
115
        }
116
        return $this->instances[$type];
117
    }
118
119
    /**
120
     * If a base class is set, then it must be ensured that the created objects
121
     * are `instanceof` this base class.
122
     *
123
     * @param string $type The FQN of the class, or "type" of object, to set as base class.
124
     * @throws InvalidArgumentException If the class is not a string or is not an existing class / interface.
125
     * @return FactoryInterface
126
     */
127
    public function setBaseClass($type)
128
    {
129
        if (!is_string($type) || empty($type)) {
130
            throw new InvalidArgumentException(
131
                'Class name or type must be a non-empty string.'
132
            );
133
        }
134
135
        $exists = (class_exists($type) || interface_exists($type));
136
        if ($exists) {
137
            $classname = $type;
138 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
139
            $classname = $this->resolve($type);
140
141
            $exists = (class_exists($classname) || interface_exists($classname));
142
            if (!$exists) {
143
                throw new InvalidArgumentException(
144
                    sprintf('Can not set "%s" as base class: Invalid class or interface name.', $classname)
145
                );
146
            }
147
        }
148
149
        $this->baseClass = $classname;
150
151
        return $this;
152
    }
153
154
    /**
155
     * @return string The FQN of the base class
156
     */
157
    public function baseClass()
158
    {
159
        return $this->baseClass;
160
    }
161
162
    /**
163
     * If a default class is set, then calling `get()` or `create()` an invalid type
164
     * should return an object of this class instead of throwing an error.
165
     *
166
     * @param string $type The FQN of the class, or "type" of object, to set as default class.
167
     * @throws InvalidArgumentException If the class name is not a string or not a valid class.
168
     * @return FactoryInterface
169
     */
170
    public function setDefaultClass($type)
171
    {
172
        if (!is_string($type) || empty($type)) {
173
            throw new InvalidArgumentException(
174
                'Class name or type must be a non-empty string.'
175
            );
176
        }
177
178 View Code Duplication
        if (class_exists($type)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
179
            $classname = $type;
180
        } else {
181
            $classname = $this->resolve($type);
182
183
            if (!class_exists($classname)) {
184
                throw new InvalidArgumentException(
185
                    sprintf('Can not set "%s" as defaut class: Invalid class name.', $classname)
186
                );
187
            }
188
        }
189
190
        $this->defaultClass = $classname;
191
192
        return $this;
193
    }
194
195
    /**
196
     * @return string The FQN of the default class
197
     */
198
    public function defaultClass()
199
    {
200
        return $this->defaultClass;
201
    }
202
203
204
205
    /**
206
     * Resolve the class name from "type".
207
     *
208
     * @param string $type The "type" of object to resolve (the object ident).
209
     * @return string
210
     */
211
    abstract public function resolve($type);
212
213
    /**
214
     * Returns wether a type is resolvable (is valid)
215
     *
216
     * @param string $type The "type" of object to resolve (the object ident).
217
     * @return boolean True if the type is available, false if not
218
     */
219
    abstract public function isResolvable($type);
220
}
221