1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Guillermoandrae\Repositories; |
4
|
|
|
|
5
|
|
|
final class RepositoryFactory |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* The namespace to use when creating repository objects. |
9
|
|
|
* |
10
|
|
|
* @var string |
11
|
|
|
*/ |
12
|
|
|
private static $namespace; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* The default namespace to use when creating repository objects. |
16
|
|
|
* |
17
|
|
|
* @var string |
18
|
|
|
*/ |
19
|
|
|
private static $defaultNamespace = 'App\Repositories'; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Sets the namespace to use when creating repository objects. |
23
|
|
|
* |
24
|
|
|
* @param string $namespace The repositories namespace. |
25
|
|
|
*/ |
26
|
1 |
|
public static function setNamespace(string $namespace) |
27
|
|
|
{ |
28
|
1 |
|
static::$namespace = $namespace; |
|
|
|
|
29
|
1 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Returns the namespace to use when creating repository objects. |
33
|
|
|
* |
34
|
|
|
* @return string |
35
|
|
|
*/ |
36
|
4 |
|
public static function getNamespace(): string |
37
|
|
|
{ |
38
|
4 |
|
if (is_null(static::$namespace)) { |
|
|
|
|
39
|
2 |
|
return static::$defaultNamespace; |
40
|
|
|
} |
41
|
2 |
|
return static::$namespace; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Returns the desired repository using the provided data. |
46
|
|
|
* |
47
|
|
|
* @param string $name The name of the desired repository. |
48
|
|
|
* @param mixed|null $options The data needed to build the repository. |
49
|
|
|
* @return RepositoryInterface |
50
|
|
|
* @throws InvalidRepositoryException Thrown when an invalid repository is |
51
|
|
|
* requested. |
52
|
|
|
*/ |
53
|
4 |
|
public static function factory(string $name, $options = null): RepositoryInterface |
54
|
|
|
{ |
55
|
|
|
try { |
56
|
4 |
|
$className = sprintf( |
57
|
4 |
|
'%s\%sRepository', |
58
|
4 |
|
static::getNamespace(), |
59
|
4 |
|
ucfirst(strtolower($name)) |
60
|
|
|
); |
61
|
4 |
|
$reflectionClass = new \ReflectionClass($className); |
62
|
3 |
|
if (is_null($options)) { |
63
|
2 |
|
return $reflectionClass->newInstance(); |
64
|
|
|
} |
65
|
1 |
|
return $reflectionClass->newInstance($options); |
66
|
1 |
|
} catch (\ReflectionException $ex) { |
67
|
1 |
|
throw new InvalidRepositoryException( |
68
|
1 |
|
sprintf('The %s repository does not exist.', $name) |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|