Passed
Pull Request — master (#241)
by Dmitriy
02:21
created

DynamicReferencesArray::from()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Di;
6
7
use Yiisoft\Factory\Definition\DynamicReference;
8
use Yiisoft\Factory\Exception\InvalidConfigException;
9
10
final class DynamicReferencesArray
11
{
12
    /**
13
     *  A usage example
14
     *
15
     * ```php
16
     * //params.php
17
     * return [
18
     *      'yiisoft/data-response' => [
19
     *          'contentFormatters' => [
20
     *              'text/html' => HtmlDataResponseFormatter::class,
21
     *              'application/xml' => XmlDataResponseFormatter::class,
22
     *              'application/json' => JsonDataResponseFormatter::class,
23
     *          ],
24
     *      ],
25
     * ];
26
     * ```
27
     *
28
     * This definition
29
     *
30
     * ```php
31
     * //web.php
32
     *
33
     * ContentNegotiator::class => [
34
     *     '__construct()' => [
35
     *         'contentFormatters' => DynamicReferencesArray::from($params['yiisoft/data-response']['contentFormatters']),
36
     *     ],
37
     * ],
38
     * ```
39
     *
40
     * equals to
41
     *
42
     * ```php
43
     * //web.php
44
     *
45
     * ContentNegotiator::class => [
46
     *     '__construct()' => [
47
     *         'contentFormatters' => [
48
     *             'text/html' => DynamicReference::to(HtmlDataResponseFormatter())),
49
     *             'application/xml' => DynamicReference::to(XmlDataResponseFormatter()),
50
     *             'application/json' => DynamicReference::to(JsonDataResponseFormatter()),
51
     *         ],
52
     *     ],
53
     * ],
54
     * ```
55
     *
56
     * @param array $ids
57
     * @return array
58
     * @throws InvalidConfigException
59
     */
60 2
    public static function from(array $ids)
61
    {
62 2
        $references = [];
63
64 2
        foreach ($ids as $key => $id) {
65 2
            if (!is_string($id)) {
66 1
                throw new InvalidConfigException('Values of an array must be string alias or class name.');
67
            }
68 2
            $references[$key] = DynamicReference::to($id);
69
        }
70
71 1
        return $references;
72
    }
73
}
74