Passed
Pull Request — master (#156)
by Alexander
02:08
created

Factory::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Factory;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Definitions\ArrayDefinition;
9
use Yiisoft\Definitions\Contract\DefinitionInterface;
10
use Yiisoft\Definitions\Helpers\DefinitionValidator;
11
use Yiisoft\Definitions\Exception\CircularReferenceException;
12
use Yiisoft\Definitions\Exception\InvalidConfigException;
13
use Yiisoft\Definitions\Exception\NotInstantiableException;
14
use Yiisoft\Definitions\Helpers\Normalizer;
15
16
use function is_string;
17
18
/**
19
 * Factory allows creating objects passing arguments runtime.
20
 * A factory will try to use a PSR-11 compliant container to get dependencies,
21
 * but will fall back to manual instantiation
22
 * if the container cannot provide a required dependency.
23
 */
24
final class Factory
25
{
26
    private FactoryInternalContainer $internalContainer;
27
28
    /**
29
     * @var bool $validate If definitions should be validated when set.
30
     */
31
    private bool $validate;
32
33
    /**
34
     * Factory constructor.
35
     *
36
     * @param ContainerInterface $container Container to use for resolving dependencies.
37
     * @param array $definitions Definitions to create objects with.
38
     * @psalm-param array<string, mixed> $definitions
39
     *
40
     * @param bool $validate If definitions should be validated when set.
41
     *
42
     * @throws InvalidConfigException
43
     */
44 103
    public function __construct(
45
        ContainerInterface $container,
46
        array $definitions = [],
47
        bool $validate = true
48
    ) {
49 103
        $this->validate = $validate;
50
51 103
        if ($this->validate) {
52
            /** @var mixed $definition */
53 99
            foreach ($definitions as $id => $definition) {
54 67
                DefinitionValidator::validate($definition, $id);
55
            }
56
        }
57
58 101
        $this->internalContainer = new FactoryInternalContainer($container, $definitions);
59 101
    }
60
61
    /**
62
     * Creates a new object using the given configuration.
63
     *
64
     * You may view this method as an enhanced version of the `new` operator.
65
     * The method supports creating an object based on a class name, a configuration array or
66
     * an anonymous function.
67
     *
68
     * Below are some usage examples:
69
     *
70
     * ```php
71
     * // create an object using a class name
72
     * $object = $factory->create(\Yiisoft\Db\Connection::class);
73
     *
74
     * // create an object using a configuration array
75
     * $object = $factory->create([
76
     *     'class' => \Yiisoft\Db\Connection\Connection::class,
77
     *     '__construct()' => [
78
     *         'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
79
     *     ],
80
     *     'setUsername()' => ['root'],
81
     *     'setPassword()' => [''],
82
     *     'setCharset()' => ['utf8'],
83
     * ]);
84
     * ```
85
     *
86
     * Using [[Container|dependency injection container]], this method can also identify
87
     * dependent objects, instantiate them and inject them into the newly created object.
88
     *
89
     * @param mixed $config The object configuration. This can be specified in one of the following forms:
90
     *
91
     * - A string: representing the class name of the object to be created.
92
     *
93
     * - A configuration array: the array must contain a `class` element which is treated as the object class,
94
     *   and the rest of the name-value pairs will be used to initialize the corresponding object properties.
95
     *
96
     * - A PHP callable: either an anonymous function or an array representing a class method
97
     *   (`[$class or $object, $method]`). The callable should return a new instance of the object being created.
98
     *
99
     * @throws InvalidConfigException If the configuration is invalid.
100
     * @throws CircularReferenceException
101
     * @throws NotFoundException
102
     * @throws NotInstantiableException
103
     *
104
     * @return mixed|object The created object.
105
     *
106
     * @psalm-template T
107
     * @psalm-param mixed|class-string<T> $config
108
     * @psalm-return ($config is class-string ? T : mixed)
109
     * @psalm-suppress MixedReturnStatement
110
     */
111 101
    public function create($config)
112
    {
113 101
        if ($this->validate) {
114 97
            DefinitionValidator::validate($config);
115
        }
116
117 97
        if (is_string($config)) {
118 78
            if ($this->internalContainer->hasDefinition($config)) {
119 57
                $definition = $this->internalContainer->getDefinition($config);
120 21
            } elseif (class_exists($config)) {
121 18
                $definition = ArrayDefinition::fromPreparedData($config);
122
            } else {
123 76
                throw new NotFoundException($config);
124
            }
125
        } else {
126 21
            $definition = $this->createDefinition($config);
127
        }
128
129 91
        return $this->internalContainer->create($definition);
130
    }
131
132
    /**
133
     * @param mixed $config
134
     *
135
     * @throws InvalidConfigException
136
     */
137 21
    private function createDefinition($config): DefinitionInterface
138
    {
139 21
        $definition = Normalizer::normalize($config);
140
141
        if (
142 20
            ($definition instanceof ArrayDefinition) &&
143 20
            $this->internalContainer->hasDefinition($definition->getClass()) &&
144 20
            ($containerDefinition = $this->internalContainer->getDefinition($definition->getClass())) instanceof ArrayDefinition
145
        ) {
146 4
            $definition = $this->mergeDefinitions(
147 4
                $containerDefinition,
148
                $definition
149
            );
150
        }
151
152 20
        return $definition;
153
    }
154
155 4
    private function mergeDefinitions(DefinitionInterface $one, ArrayDefinition $two): DefinitionInterface
156
    {
157 4
        return $one instanceof ArrayDefinition ? $one->merge($two) : $two;
158
    }
159
}
160