Passed
Push — master ( ba48b8...05b6a0 )
by Alexander
02:42
created

Factory::withDefinitions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 105
    public function __construct(
45
        ContainerInterface $container,
46
        array $definitions = [],
47
        bool $validate = true
48
    ) {
49 105
        $this->validate = $validate;
50 105
        $this->validateDefinitions($definitions);
51 103
        $this->internalContainer = new FactoryInternalContainer($container, $definitions);
52 103
    }
53
54
    /**
55
     * @param array $definitions Definitions to create objects with.
56
     * @psalm-param array<string, mixed> $definitions
57
     *
58
     * @throws InvalidConfigException
59
     *
60
     * @return self
61
     */
62 1
    public function withDefinitions(array $definitions): self
63
    {
64 1
        $this->validateDefinitions($definitions);
65
66 1
        $new = clone $this;
67 1
        $new->internalContainer = $this->internalContainer->withDefinitions($definitions);
68 1
        return $new;
69
    }
70
71
    /**
72
     * @param array $definitions Definitions to validate.
73
     * @psalm-param array<string, mixed> $definitions
74
     *
75
     * @throws InvalidConfigException
76
     */
77 105
    private function validateDefinitions(array $definitions): void
78
    {
79 105
        if ($this->validate) {
80
            /** @var mixed $definition */
81 101
            foreach ($definitions as $id => $definition) {
82 69
                DefinitionValidator::validate($definition, $id);
83
            }
84
        }
85 103
    }
86
87
    /**
88
     * Creates a new object using the given configuration.
89
     *
90
     * You may view this method as an enhanced version of the `new` operator.
91
     * The method supports creating an object based on a class name, a configuration array or
92
     * an anonymous function.
93
     *
94
     * Below are some usage examples:
95
     *
96
     * ```php
97
     * // create an object using a class name
98
     * $object = $factory->create(\Yiisoft\Db\Connection::class);
99
     *
100
     * // create an object using a configuration array
101
     * $object = $factory->create([
102
     *     'class' => \Yiisoft\Db\Connection\Connection::class,
103
     *     '__construct()' => [
104
     *         'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
105
     *     ],
106
     *     'setUsername()' => ['root'],
107
     *     'setPassword()' => [''],
108
     *     'setCharset()' => ['utf8'],
109
     * ]);
110
     * ```
111
     *
112
     * Using [[Container|dependency injection container]], this method can also identify
113
     * dependent objects, instantiate them and inject them into the newly created object.
114
     *
115
     * @param mixed $config The object configuration. This can be specified in one of the following forms:
116
     *
117
     * - A string: representing the class name of the object to be created.
118
     *
119
     * - A configuration array: the array must contain a `class` element which is treated as the object class,
120
     *   and the rest of the name-value pairs will be used to initialize the corresponding object properties.
121
     *
122
     * - A PHP callable: either an anonymous function or an array representing a class method
123
     *   (`[$class or $object, $method]`). The callable should return a new instance of the object being created.
124
     *
125
     * @throws InvalidConfigException If the configuration is invalid.
126
     * @throws CircularReferenceException
127
     * @throws NotFoundException
128
     * @throws NotInstantiableException
129
     *
130
     * @return mixed|object The created object.
131
     *
132
     * @psalm-template T
133
     * @psalm-param mixed|class-string<T> $config
134
     * @psalm-return ($config is class-string ? T : mixed)
135
     * @psalm-suppress MixedReturnStatement
136
     */
137 103
    public function create($config)
138
    {
139 103
        if ($this->validate) {
140 99
            DefinitionValidator::validate($config);
141
        }
142
143 99
        if (is_string($config)) {
144 80
            if ($this->internalContainer->hasDefinition($config)) {
145 59
                $definition = $this->internalContainer->getDefinition($config);
146 21
            } elseif (class_exists($config)) {
147 18
                $definition = ArrayDefinition::fromPreparedData($config);
148
            } else {
149 78
                throw new NotFoundException($config);
150
            }
151
        } else {
152 21
            $definition = $this->createDefinition($config);
153
        }
154
155 93
        return $this->internalContainer->create($definition);
156
    }
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->internalContainer->hasDefinition($definition->getClass()) &&
170 20
            ($containerDefinition = $this->internalContainer->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