Passed
Pull Request — master (#151)
by Alexander
03:59 queued 01:56
created

Factory::create()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 12
c 3
b 0
f 0
nc 8
nop 1
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 5
rs 9.5555
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
    /**
27
     * @var ContainerInterface|null Container to use for resolving dependencies. When null, only definitions
28
     * are used.
29
     */
30
    private ?ContainerInterface $container;
31
    private FactoryContainer $factoryContainer;
32
33
    /**
34
     * @var bool $validate If definitions should be validated when set.
35
     */
36
    private bool $validate;
37
38
    /**
39
     * Factory constructor.
40
     *
41
     * @param ContainerInterface|null $container Container to use for resolving dependencies. When null, only definitions
42
     * are used.
43
     * @param array $definitions Definitions to create objects with.
44
     * @psalm-param array<string, mixed> $definitions
45
     *
46
     * @param bool $validate If definitions should be validated when set.
47
     *
48
     * @throws InvalidConfigException
49
     */
50 107
    public function __construct(
51
        ContainerInterface $container = null,
52
        array $definitions = [],
53
        bool $validate = true
54
    ) {
55 107
        $this->container = $container;
56 107
        $this->factoryContainer = new FactoryContainer($container);
57 107
        $this->validate = $validate;
58 107
        $this->setMultiple($definitions);
59 105
    }
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 104
    public function create($config)
112
    {
113 104
        if ($this->validate) {
114 100
            DefinitionValidator::validate($config);
115
        }
116
117 100
        if (is_string($config)) {
118 81
            if ($this->factoryContainer->hasDefinition($config)) {
119 60
                $definition = $this->factoryContainer->getDefinition($config);
120 21
            } elseif (class_exists($config)) {
121 18
                $definition = ArrayDefinition::fromPreparedData($config);
122
            } else {
123 79
                throw new NotFoundException($config);
124
            }
125
        } else {
126 21
            $definition = $this->createDefinition($config);
127
        }
128
129 94
        return $this->factoryContainer->create($definition);
130
    }
131
132
    /**
133
     * Sets a definition to the factory.
134
     *
135
     * @param mixed $definition
136
     *
137
     * @throws InvalidConfigException
138
     */
139 74
    public function set(string $id, $definition): void
140
    {
141 74
        if ($this->validate) {
142 71
            DefinitionValidator::validate($definition, $id);
143
        }
144
145 71
        $this->factoryContainer->setDefinition($id, $definition);
146 71
    }
147
148
    /**
149
     * Sets multiple definitions at once.
150
     *
151
     * @param array $definitions definitions indexed by their ids
152
     *
153
     * @psalm-param array<string, mixed> $definitions
154
     *
155
     * @throws InvalidConfigException
156
     */
157 107
    public function setMultiple(array $definitions): void
158
    {
159
        /** @var mixed $definition */
160 107
        foreach ($definitions as $id => $definition) {
161 72
            $this->set($id, $definition);
162
        }
163 105
    }
164
165
    /**
166
     * @param mixed $config
167
     *
168
     * @throws InvalidConfigException
169
     */
170 21
    private function createDefinition($config): DefinitionInterface
171
    {
172 21
        $definition = Normalizer::normalize($config);
173
174
        if (
175 20
            ($definition instanceof ArrayDefinition) &&
176 20
            $this->factoryContainer->hasDefinition($definition->getClass()) &&
177 20
            ($containerDefinition = $this->factoryContainer->getDefinition($definition->getClass())) instanceof ArrayDefinition
178
        ) {
179 4
            $definition = $this->mergeDefinitions(
180 4
                $containerDefinition,
181
                $definition
182
            );
183
        }
184
185 20
        return $definition;
186
    }
187
188 4
    private function mergeDefinitions(DefinitionInterface $one, ArrayDefinition $two): DefinitionInterface
189
    {
190 4
        return $one instanceof ArrayDefinition ? $one->merge($two) : $two;
191
    }
192
}
193