ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
TupleTransformation.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
27
29{
32
34 private array $transformations;
35
39 public function __construct(array $transformations)
40 {
41 foreach ($transformations as $transformation) {
42 if (!$transformation instanceof Transformation) {
43 $transformationClassName = Transformation::class;
44
46 sprintf('The array must contain only "%s" instances', $transformationClassName),
47 'not_a_transformation',
48 $transformationClassName
49 );
50 }
51 }
52 $this->transformations = $transformations;
53 }
54
58 public function transform($from): array
59 {
60 if (!is_array($from)) {
61 $from = [$from];
62 }
63
64 if ([] === $from) {
66 sprintf('The array "%s" ist empty', var_export($from, true)),
67 'value_array_is_empty',
68 $from
69 ) ;
70 }
71
72 $this->testLengthOf($from);
73
74 $result = [];
75 foreach ($from as $key => $value) {
76 if (!array_key_exists($key, $this->transformations)) {
78 sprintf('Matching key "%s" not found', $key),
79 'matching_values_not_found',
80 $value
81 );
82 }
83 $transformedValue = $this->transformations[$key]->transform($value);
84 $result[] = $transformedValue;
85 }
86
87 return $result;
88 }
89
90 private function testLengthOf(array $values): void
91 {
92 $countOfValues = count($values);
93 $countOfTransformations = count($this->transformations);
94
95 if ($countOfValues !== $countOfTransformations) {
97 sprintf('The length of given value "%s" does not match with the given transformations', $countOfValues),
98 'given_values_',
99 $countOfValues
100 );
101 }
102 }
103}
A transformation is a function from one datatype to another.