Completed
Push — master ( a3283a...df6bb2 )
by Saulius
27s
created

ConvertTo::addConverters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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