ReferencesArray   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 68
ccs 7
cts 7
cp 1
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A from() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Definitions;
6
7
use Yiisoft\Definitions\Exception\InvalidConfigException;
8
9
use function is_string;
10
11
/**
12
 * Allows creating an array of references from key-reference pairs.
13
 *
14
 * @see Reference
15
 */
16
final class ReferencesArray
17
{
18
    /**
19
     * Create references array from name-reference pairs.
20
     *
21
     * For example if we want to define a set of named references, usually
22
     * it is done as:
23
     *
24
     * ```php
25
     * //web.php
26
     *
27
     * ContentNegotiator::class => [
28
     *     '__construct()' => [
29
     *         'contentFormatters' => [
30
     *             'text/html' => Reference::to(HtmlDataResponseFormatter::class),
31
     *             'application/xml' => Reference::to(XmlDataResponseFormatter::class),
32
     *             'application/json' => Reference::to(JsonDataResponseFormatter::class),
33
     *         ],
34
     *     ],
35
     * ],
36
     * ```
37
     * That is not very convenient, so we can define formatters in a separate config and without explicitly using
38
     * `Reference::to()` for each formatter:
39
     *
40
     * ```php
41
     * //params.php
42
     * return [
43
     *      'yiisoft/data-response' => [
44
     *          'contentFormatters' => [
45
     *              'text/html' => HtmlDataResponseFormatter::class,
46
     *              'application/xml' => XmlDataResponseFormatter::class,
47
     *              'application/json' => JsonDataResponseFormatter::class,
48
     *          ],
49
     *      ],
50
     * ];
51
     * ```
52
     *
53
     * Then we can use it like the following:
54
     *
55
     * ```php
56
     * //web.php
57
     *
58
     * ContentNegotiator::class => [
59
     *     '__construct()' => [
60
     *         'contentFormatters' => ReferencesArray::from($params['yiisoft/data-response']['contentFormatters']),
61
     *     ],
62
     * ],
63
     * ```
64
     *
65
     * @param string[] $ids Name-reference pairs.
66
     *
67
     * @throws InvalidConfigException
68
     *
69
     * @return Reference[]
70
     * @psalm-suppress DocblockTypeContradiction
71
     */
72 2
    public static function from(array $ids): array
73
    {
74 2
        $references = [];
75
76 2
        foreach ($ids as $key => $id) {
77 2
            if (!is_string($id)) {
78 1
                throw new InvalidConfigException('Values of an array must be string alias or class name.');
79
            }
80 2
            $references[$key] = Reference::to($id);
81
        }
82
83 1
        return $references;
84
    }
85
}
86