|
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
|
2 |
|
public static function addConverters($converters): void |
|
34
|
|
|
{ |
|
35
|
2 |
|
self::$additionalConverters = array_merge(self::$additionalConverters, $converters); |
|
36
|
2 |
|
} |
|
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
|
|
|
|