1
|
|
|
<?php
|
2
|
|
|
/**
|
3
|
|
|
* @category Library
|
4
|
|
|
* @license MIT http://opensource.org/licenses/MIT
|
5
|
|
|
* @link https://github.com/emlynwest/changelog
|
6
|
|
|
*/
|
7
|
|
|
|
8
|
|
|
namespace ChangeLog;
|
9
|
|
|
|
10
|
|
|
use InvalidArgumentException;
|
11
|
|
|
use ReflectionClass;
|
12
|
|
|
|
13
|
|
|
/**
|
14
|
|
|
* Basic factory class that can be used to load classes from any given namespace.
|
15
|
|
|
*/
|
16
|
|
|
class GenericFactory
|
17
|
|
|
{
|
18
|
|
|
|
19
|
|
|
/**
|
20
|
|
|
* Base namespace
|
21
|
|
|
*
|
22
|
|
|
* @var string
|
23
|
|
|
*/
|
24
|
|
|
protected $baseNamespace;
|
25
|
|
|
|
26
|
|
|
/**
|
27
|
|
|
* Contains any mappings for extra classes.
|
28
|
|
|
*
|
29
|
|
|
* @var array
|
30
|
|
|
*/
|
31
|
|
|
protected $addedClasses = [];
|
32
|
|
|
|
33
|
|
|
/**
|
34
|
|
|
* GenericFactory constructor.
|
35
|
|
|
*
|
36
|
|
|
* @param string $baseNamespace
|
37
|
|
|
*/
|
38
|
14 |
|
public function __construct($baseNamespace)
|
39
|
|
|
{
|
40
|
14 |
|
$this->baseNamespace = $baseNamespace;
|
41
|
|
|
}
|
42
|
|
|
|
43
|
|
|
/**
|
44
|
|
|
* Returns a constructed instance of the named class.
|
45
|
|
|
*
|
46
|
|
|
* @param string $name
|
47
|
|
|
* @param array $parameters
|
48
|
|
|
*
|
49
|
|
|
* @return mixed
|
50
|
|
|
*
|
51
|
|
|
* @throws InvalidArgumentException If the class cannot be found.
|
52
|
|
|
*/
|
53
|
14 |
|
public function getInstance($name, $parameters = [])
|
54
|
|
|
{
|
55
|
14 |
|
$class = $this->baseNamespace . ucfirst($name);
|
56
|
|
|
|
57
|
|
|
// If we have a custom class, use that instead.
|
58
|
14 |
|
if ( ! empty($this->addedClasses[$name]))
|
59
|
|
|
{
|
60
|
2 |
|
$class = $this->addedClasses[$name];
|
61
|
|
|
}
|
62
|
|
|
|
63
|
|
|
// Ensure our class actually exists
|
64
|
14 |
|
if ( ! class_exists($class))
|
65
|
|
|
{
|
66
|
1 |
|
throw new InvalidArgumentException("$name is not a known class ($class)");
|
67
|
|
|
}
|
68
|
|
|
|
69
|
13 |
|
return new $class($parameters);
|
70
|
|
|
}
|
71
|
|
|
|
72
|
|
|
/**
|
73
|
|
|
* Adds a new named class to the factory.
|
74
|
|
|
*
|
75
|
|
|
* @param string $name
|
76
|
|
|
* @param string $class
|
77
|
|
|
*/
|
78
|
2 |
|
public function addClass($name, $class)
|
79
|
|
|
{
|
80
|
2 |
|
$this->addedClasses[$name] = $class;
|
81
|
|
|
}
|
82
|
|
|
|
83
|
|
|
}
|
84
|
|
|
|