Passed
Pull Request — master (#151)
by Sergei
02:12
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 FactoryContainer $factoryContainer;
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 106
    public function __construct(
45
        ContainerInterface $container,
46
        array $definitions = [],
47
        bool $validate = true
48
    ) {
49 106
        $this->factoryContainer = new FactoryContainer($container);
50 106
        $this->validate = $validate;
51 106
        $this->setMultiple($definitions);
52 104
    }
53
54
    /**
55
     * Creates a new object using the given configuration.
56
     *
57
     * You may view this method as an enhanced version of the `new` operator.
58
     * The method supports creating an object based on a class name, a configuration array or
59
     * an anonymous function.
60
     *
61
     * Below are some usage examples:
62
     *
63
     * ```php
64
     * // create an object using a class name
65
     * $object = $factory->create(\Yiisoft\Db\Connection::class);
66
     *
67
     * // create an object using a configuration array
68
     * $object = $factory->create([
69
     *     'class' => \Yiisoft\Db\Connection\Connection::class,
70
     *     '__construct()' => [
71
     *         'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
72
     *     ],
73
     *     'setUsername()' => ['root'],
74
     *     'setPassword()' => [''],
75
     *     'setCharset()' => ['utf8'],
76
     * ]);
77
     * ```
78
     *
79
     * Using [[Container|dependency injection container]], this method can also identify
80
     * dependent objects, instantiate them and inject them into the newly created object.
81
     *
82
     * @param mixed $config The object configuration. This can be specified in one of the following forms:
83
     *
84
     * - A string: representing the class name of the object to be created.
85
     *
86
     * - A configuration array: the array must contain a `class` element which is treated as the object class,
87
     *   and the rest of the name-value pairs will be used to initialize the corresponding object properties.
88
     *
89
     * - A PHP callable: either an anonymous function or an array representing a class method
90
     *   (`[$class or $object, $method]`). The callable should return a new instance of the object being created.
91
     *
92
     * @throws InvalidConfigException If the configuration is invalid.
93
     * @throws CircularReferenceException
94
     * @throws NotFoundException
95
     * @throws NotInstantiableException
96
     *
97
     * @return mixed|object The created object.
98
     *
99
     * @psalm-template T
100
     * @psalm-param mixed|class-string<T> $config
101
     * @psalm-return ($config is class-string ? T : mixed)
102
     * @psalm-suppress MixedReturnStatement
103
     */
104 103
    public function create($config)
105
    {
106 103
        if ($this->validate) {
107 99
            DefinitionValidator::validate($config);
108
        }
109
110 99
        if (is_string($config)) {
111 80
            if ($this->factoryContainer->hasDefinition($config)) {
112 59
                $definition = $this->factoryContainer->getDefinition($config);
113 21
            } elseif (class_exists($config)) {
114 18
                $definition = ArrayDefinition::fromPreparedData($config);
115
            } else {
116 78
                throw new NotFoundException($config);
117
            }
118
        } else {
119 21
            $definition = $this->createDefinition($config);
120
        }
121
122 93
        return $this->factoryContainer->create($definition);
123
    }
124
125
    /**
126
     * Sets a definition to the factory.
127
     *
128
     * @param mixed $definition
129
     *
130
     * @throws InvalidConfigException
131
     */
132 73
    public function set(string $id, $definition): void
133
    {
134 73
        if ($this->validate) {
135 70
            DefinitionValidator::validate($definition, $id);
136
        }
137
138 70
        $this->factoryContainer->setDefinition($id, $definition);
139 70
    }
140
141
    /**
142
     * Sets multiple definitions at once.
143
     *
144
     * @param array $definitions definitions indexed by their ids
145
     *
146
     * @psalm-param array<string, mixed> $definitions
147
     *
148
     * @throws InvalidConfigException
149
     */
150 106
    public function setMultiple(array $definitions): void
151
    {
152
        /** @var mixed $definition */
153 106
        foreach ($definitions as $id => $definition) {
154 71
            $this->set($id, $definition);
155
        }
156 104
    }
157
158
    /**
159
     * @param mixed $config
160
     *
161
     * @throws InvalidConfigException
162
     */
163 21
    private function createDefinition($config): DefinitionInterface
164
    {
165 21
        $definition = Normalizer::normalize($config);
166
167
        if (
168 20
            ($definition instanceof ArrayDefinition) &&
169 20
            $this->factoryContainer->hasDefinition($definition->getClass()) &&
170 20
            ($containerDefinition = $this->factoryContainer->getDefinition($definition->getClass())) instanceof ArrayDefinition
171
        ) {
172 4
            $definition = $this->mergeDefinitions(
173 4
                $containerDefinition,
174
                $definition
175
            );
176
        }
177
178 20
        return $definition;
179
    }
180
181 4
    private function mergeDefinitions(DefinitionInterface $one, ArrayDefinition $two): DefinitionInterface
182
    {
183 4
        return $one instanceof ArrayDefinition ? $one->merge($two) : $two;
184
    }
185
}
186