| Total Complexity | 12 |
| Total Lines | 78 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | <?php |
||
| 20 | class MainTransformation implements Transformation |
||
| 21 | { |
||
| 22 | /** |
||
| 23 | * @var TransformationProvider|callable |
||
| 24 | */ |
||
| 25 | private $transformationProvider; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var Transformation[] |
||
| 29 | */ |
||
| 30 | private $cache = []; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @param TransformationProvider|callable $transformationProvider |
||
| 34 | */ |
||
| 35 | public function __construct(callable $transformationProvider) |
||
| 38 | } |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @param mixed $data |
||
| 42 | * @param Transformation|callable|null $transformation If provided, the specified transformation is used |
||
| 43 | * instead of this one as parameter for the transformation associated with the data. |
||
| 44 | * |
||
| 45 | * @return mixed |
||
| 46 | */ |
||
| 47 | public function __invoke($data, callable $transformation = null) |
||
| 48 | { |
||
| 49 | if ($data === null || is_scalar($data)) { |
||
| 50 | return $data; |
||
| 51 | } |
||
| 52 | |||
| 53 | $transformation = $transformation ?: $this; |
||
| 54 | |||
| 55 | if (is_object($data)) { |
||
| 56 | try { |
||
| 57 | return $this->resolveTransformation($data)($data, $transformation); |
||
| 58 | } catch (TransformationNotFound $e) { |
||
| 59 | if (!$data instanceof \Traversable) { |
||
| 60 | throw $e; |
||
| 61 | } |
||
| 62 | |||
| 63 | // The Traversable does not have a transformation, let's iterate over it. |
||
| 64 | } |
||
| 65 | } |
||
| 66 | |||
| 67 | return $this->transformIterable($data, $transformation); |
||
| 68 | } |
||
| 69 | |||
| 70 | /** |
||
| 71 | * @param mixed $data |
||
| 72 | * |
||
| 73 | * @return callable |
||
| 74 | */ |
||
| 75 | private function resolveTransformation($data): callable |
||
| 81 | } |
||
| 82 | |||
| 83 | /** |
||
| 84 | * @param \Traversable|array $data |
||
| 85 | * @param callable $transformation |
||
| 86 | * |
||
| 87 | * @return array |
||
| 88 | */ |
||
| 89 | private function transformIterable($data, callable $transformation): array |
||
| 100 |