-
Notifications
You must be signed in to change notification settings - Fork 824
/
InjectionCreator.php
37 lines (32 loc) · 1.11 KB
/
InjectionCreator.php
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
<?php
namespace SilverStripe\Core\Injector;
use InvalidArgumentException;
/**
* A class for creating new objects by the injector.
*/
class InjectionCreator implements Factory
{
/**
* Create a new instance of a class
*
* Passing an object for $class will result from using an anonymous class in unit testing, e.g.
* Injector::inst()->load([SomeClass::class => ['class' => new class { ... }]]);
*
* @param string|object $class - string: The FQCN of the class, object: A class instance
*/
public function create($class, array $params = [])
{
if (is_object($class ?? '')) {
$class = get_class($class);
}
if (!is_string($class ?? '')) {
throw new InvalidArgumentException('$class parameter must be a string or an object');
}
if (!class_exists($class)) {
throw new InjectorNotFoundException("Class {$class} does not exist");
}
// Ensure there are no string keys as they cannot be unpacked with the `...` operator
$values = array_values($params);
return new $class(...$values);
}
}