DynamicReferencesArray::from()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Definitions;
6
7
use Yiisoft\Definitions\Exception\InvalidConfigException;
8
9
/**
10
 * Allows creating an array of dynamic references from key-reference pairs.
11
 *
12
 * @see DynamicReference
13
 */
14
final class DynamicReferencesArray
15
{
16
    /**
17
     * Create dynamic references array from name-reference pairs.
18
     *
19
     * For example if we want to define a set of named dynamic references, usually
20
     * it is done as:
21
     *
22
     * ```php
23
     * // di-web.php
24
     *
25
     * ContentNegotiator::class => [
26
     *     '__construct()' => [
27
     *         'contentFormatters' => [
28
     *             'text/html' => DynamicReference::to(HtmlDataResponseFormatter::class),
29
     *             'application/xml' => DynamicReference::to(XmlDataResponseFormatter::class),
30
     *             'application/json' => DynamicReference::to(JsonDataResponseFormatter::class),
31
     *         ],
32
     *     ],
33
     * ],
34
     * ```
35
     *
36
     * That is not very convenient, so we can define formatters in a separate config and without explicitly using
37
     * `DynamicReference::to()` for each formatter:
38
     *
39
     * ```php
40
     * // params.php
41
     * return [
42
     *      'yiisoft/data-response' => [
43
     *          'contentFormatters' => [
44
     *              'text/html' => HtmlDataResponseFormatter::class,
45
     *              'application/xml' => XmlDataResponseFormatter::class,
46
     *              'application/json' => JsonDataResponseFormatter::class,
47
     *          ],
48
     *      ],
49
     * ];
50
     * ```
51
     *
52
     * Then we can use it like the following:
53
     *
54
     * ```php
55
     * // di-web.php
56
     *
57
     * ContentNegotiator::class => [
58
     *     '__construct()' => [
59
     *         'contentFormatters' =>
60
     * DynamicReferencesArray::from($params['yiisoft/data-response']['contentFormatters']),
61
     *     ],
62
     * ],
63
     * ```
64
     *
65
     * @param array $definitions Name-reference pairs.
66
     *
67
     * @throws InvalidConfigException
68
     *
69
     * @return DynamicReference[]
70
     */
71 1
    public static function from(array $definitions): array
72
    {
73 1
        $references = [];
74
75 1
        foreach ($definitions as $key => $definition) {
76 1
            $references[$key] = DynamicReference::to($definition);
77
        }
78
79 1
        return $references;
80
    }
81
}
82