Completed
Push — master ( df6bb2...227d1b )
by Saulius
8s
created

ConvertTo::execute()   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 0
Metric Value
cc 3
eloc 6
nc 3
nop 2
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the sauls/helpers package.
4
 *
5
 * @author    Saulius Vaičeliūnas <[email protected]>
6
 * @link      http://saulius.vaiceliunas.lt
7
 * @copyright 2018
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Sauls\Component\Helper\Operation\TypeOperation;
14
15
use function Sauls\Component\Helper\array_merge;
16
use Sauls\Component\Helper\Exception\ConverterNotFoundException;
17
use Sauls\Component\Helper\Operation\TypeOperation\Collection\ConverterCollectionInterface;
18
19
class ConvertTo implements ConvertToInterface
20
{
21
    /**
22
     * @var ConverterCollectionInterface
23
     */
24
    private $ensurerCollection;
25
26
    private static $additionalConverters = [];
27
28 1
    public function __construct(ConverterCollectionInterface $ensurerCollection)
29
    {
30 1
        $this->ensurerCollection = $ensurerCollection;
31 1
    }
32
33 3
    public static function addConverters($converters): void
34
    {
35 3
        self::$additionalConverters = array_merge(self::$additionalConverters, $converters);
36 3
    }
37
38
    /**
39
     * @throws \Sauls\Component\Helper\Exception\ConverterNotFoundException
40
     */
41 5
    public function execute($value, string $type)
42
    {
43 5
        $this->ensurerCollection->add(self::$additionalConverters);
44
45 5
        foreach ($this->ensurerCollection->get($type) as $ensurer) {
46 4
            if ($ensurer->supports($value)) {
47 4
                return $ensurer->convert($value);
48
            }
49
        }
50
51 1
        throw new ConverterNotFoundException(
52 1
            sprintf('Given value of `%s` does not have any converters to type `%s`.', \gettype($value), $type)
53
        );
54
    }
55
}
56