ILIAS  release_8 Revision v8.19
All Data Structures Namespaces Files Functions Variables Modules Pages
TupleTransformation.php
Go to the documentation of this file.
1 <?php
2 
3 declare(strict_types=1);
4 
22 
30 
32 {
35  use ProblemBuilder;
36 
37  private string $error = '';
39  private array $transformations;
40 
44  public function __construct(array $transformations)
45  {
46  foreach ($transformations as $transformation) {
47  if (!$transformation instanceof Transformation) {
48  $transformationClassName = Transformation::class;
49 
51  sprintf('The array MUST contain only "%s" instances', $transformationClassName),
52  'not_a_transformation',
53  $transformationClassName
54  );
55  }
56  }
57 
58  $this->transformations = $transformations;
59  }
60 
64  public function transform($from): array
65  {
66  $this->check($from);
67 
68  $result = [];
69  foreach ($from as $key => $value) {
70  $transformedValue = $this->transformations[$key]->transform($value);
71  $result[] = $transformedValue;
72  }
73 
74  return $result;
75  }
76 
80  public function getError(): string
81  {
82  return $this->error;
83  }
84 
88  public function check($value)
89  {
90  if (!$this->accepts($value)) {
91  throw new UnexpectedValueException($this->getErrorMessage($value));
92  }
93 
94  return null;
95  }
96 
100  public function accepts($value): bool
101  {
102  if (!$this->isLengthOfValueAndTransformationEqual($value)) {
103  return false;
104  }
105 
106  return count(array_filter($value, function ($key): bool {
107  if (!array_key_exists($key, $this->transformations)) {
108  $this->error = sprintf('There is no entry "%s" defined in the transformation array', $key);
109  return true;
110  }
111  return false;
112  }, ARRAY_FILTER_USE_KEY)) === 0;
113  }
114 
115  private function isLengthOfValueAndTransformationEqual($values): bool
116  {
117  $countOfValues = count($values);
118  $countOfTransformations = count($this->transformations);
119 
120  if ($countOfValues !== $countOfTransformations) {
121  $this->error = sprintf(
122  'The given values(count: "%s") does not match with the given transformations("%s")',
123  $countOfValues,
124  $countOfTransformations
125  );
126  return false;
127  }
128 
129  return true;
130  }
131 
135  public function problemWith($value): ?string
136  {
137  if (!$this->accepts($value)) {
138  return $this->getErrorMessage($value);
139  }
140 
141  return null;
142  }
143 }
A constraint encodes some resrtictions on values.
Definition: Constraint.php:31
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
string $key
Consumer key/client ID value.
Definition: System.php:193
getErrorMessage($value)
Get the problem message.
A transformation is a function from one datatype to another.
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...