Repository navigation
Expand file tree
/
Copy pathModelFactory.php
More file actions
111 lines (96 loc) · 2.24 KB
/
Copy pathModelFactory.php
File metadata and controls
111 lines (96 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php namespace CodeIgniter\Database;
use Config\Services;
class ModelFactory
{
/**
* Cache for instance of any models that
* have been requested as "shared" instance.
*
* @var array
*/
static private $instances = [];
/**
* Create new configuration instances or return
* a shared instance
*
* @param string $name Configuration name
* @param boolean $getShared Use shared instance
* @param ConnectionInterface $connection
*
* @return mixed|null
*/
public static function get(string $name, bool $getShared = true, ConnectionInterface $connection = null)
{
$class = $name;
if (($pos = strrpos($name, '\\')) !== false)
{
$class = substr($name, $pos + 1);
}
if (! $getShared)
{
return self::createClass($name, $connection);
}
if (! isset( self::$instances[$class] ))
{
self::$instances[$class] = self::createClass($name, $connection);
}
return self::$instances[$class];
}
/**
* Helper method for injecting mock instances while testing.
*
* @param string $class
* @param $instance
*/
public static function injectMock(string $class, $instance)
{
self::$instances[$class] = $instance;
}
/**
* Resets the instances array
*/
public static function reset()
{
static::$instances = [];
}
/**
* Find configuration class and create instance
*
* @param string $name Classname
* @param ConnectionInterface|null $connection
*
* @return mixed|null
*/
private static function createClass(string $name, ConnectionInterface &$connection = null)
{
if (class_exists($name))
{
return new $name();
}
$locator = Services::locator();
$file = $locator->locateFile($name, 'Models');
if (empty($file))
{
// No file found - check if the class was namespaced
if (strpos($name, '\\') !== false)
{
// Class was namespaced and locateFile couldn't find it
return null;
}
// Check all namespaces
$files = $locator->search('Models/' . $name);
if (empty($files))
{
return null;
}
// Get the first match (prioritizes user and framework)
$file = reset($files);
}
$name = $locator->getClassname($file);
if (empty($name))
{
return null;
}
return new $name($connection);
}
}