1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the ICanBoogie package. |
5
|
|
|
* |
6
|
|
|
* (c) Olivier Laviale <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace ICanBoogie\Transformation; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* A transformation that uses a provider to find the best transformation for a given data. |
16
|
|
|
* |
17
|
|
|
* This transformation is very useful when dealing with nested data, or when you don't want to deal with type |
18
|
|
|
* checking. |
19
|
|
|
*/ |
20
|
|
|
class MainTransformation implements Transformation |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var TransformationProvider|callable |
24
|
|
|
*/ |
25
|
|
|
private $transformationProvider; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param TransformationProvider|callable $transformationProvider |
29
|
|
|
*/ |
30
|
|
|
public function __construct(callable $transformationProvider) |
31
|
|
|
{ |
32
|
|
|
$this->transformationProvider = $transformationProvider; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param mixed $data |
37
|
|
|
* @param Transformation|callable|null $transformation If provided, the specified transformation is used |
38
|
|
|
* instead of this one as parameter for the transformation associated with the data. |
39
|
|
|
* |
40
|
|
|
* @return mixed |
41
|
|
|
*/ |
42
|
|
|
public function __invoke($data, callable $transformation = null) |
43
|
|
|
{ |
44
|
|
|
if ($data === null || is_scalar($data)) { |
45
|
|
|
return $data; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$transformation = $transformation ?: $this; |
49
|
|
|
|
50
|
|
|
try { |
51
|
|
|
return ($this->transformationProvider)($data)($data, $transformation); |
52
|
|
|
} catch (TransformationNotFound $e) { |
53
|
|
|
// it's ok, we might still be able to transform it… |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (!is_array($data) && !$data instanceof \Traversable) { |
57
|
|
|
throw new TransformationNotFound($data, null, $e); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $this->transformIterable($data, $transformation); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param \Traversable|array $data |
65
|
|
|
* @param callable $transformation |
66
|
|
|
* |
67
|
|
|
* @return array |
68
|
|
|
*/ |
69
|
|
|
private function transformIterable($data, callable $transformation): array |
70
|
|
|
{ |
71
|
|
|
$array = []; |
72
|
|
|
|
73
|
|
|
foreach ($data as $item) { |
74
|
|
|
$array[] = $this($item, $transformation); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $array; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|