ValueAsKey::create()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 15
ccs 6
cts 6
cp 1
crap 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Knp\DictionaryBundle\Dictionary\Factory;
6
7
use InvalidArgumentException;
8
use Knp\DictionaryBundle\Dictionary;
9
use Knp\DictionaryBundle\Dictionary\Factory;
10
use Knp\DictionaryBundle\Dictionary\Simple;
11
use Knp\DictionaryBundle\ValueTransformer;
12
13
final class ValueAsKey implements Factory
14
{
15
    public function __construct(private readonly ValueTransformer $valueTransformer) {}
16
17
    /**
18
     * {@inheritdoc}
19
     *
20 5
     * @throw InvalidArgumentException if there is some problem with the config.
21
     */
22 5
    public function create(string $name, array $config): Dictionary
23 5
    {
24
        if (!isset($config['content'])) {
25
            throw new \InvalidArgumentException(\sprintf('The key content for dictionary %s must be set.', $name));
26
        }
27
28
        $content = $config['content'];
29
        $values  = [];
30 2
31
        foreach ($content as $value) {
32 2
            $builtValue          = $this->valueTransformer->transform($value);
33 1
            $values[$builtValue] = $builtValue;
34
        }
35
36 1
        return new Simple($name, $values);
37 1
    }
38
39 1
    public function supports(array $config): bool
40 1
    {
41 1
        return isset($config['type']) && 'value_as_key' === $config['type'];
42
    }
43
}
44