ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
Transform.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
26use Closure;
28
30{
38 public function to(Transformation $transformation, Closure $parse): Closure
39 {
40 return $this->from(static fn($value): Result => $transformation->applyTo(new Ok($value))->map(
41 static fn($value): array => [$value]
42 ), $parse);
43 }
44
61 public function as(string $key, Closure $parse): Closure
62 {
63 return $this->from(
64 fn($value): Result => new Ok([$key => $this->removeArrayLevel($value)]),
65 $parse
66 );
67 }
68
73 private function removeArrayLevel($value)
74 {
75 if (is_array($value) && count($value) === 1 && isset($value[0])) {
76 return $value[0];
77 }
78
79 return $value;
80 }
81
82 private function from(Closure $transform, Closure $parse): Closure
83 {
84 return fn(Intermediate $previous, Closure $cc): Result => $parse(
85 $previous->onlyTodo(),
86 fn(Result $child): Result => $child->then(
87 fn(Intermediate $child): Result =>
88 $child->transform($transform)
89 ->then($this->combine($previous, $child, $cc))
90 ->except($this->error($cc))
91 )->except($this->error($cc))
92 );
93 }
94
95 private function combine(Intermediate $hasAccepted, Intermediate $hasTodos, Closure $cc): Closure
96 {
97 return static fn(array $values): Result => $cc(new Ok(
98 $hasTodos->onlyTodo()
99 ->push($hasAccepted->accepted())
100 ->push($values)
101 ));
102 }
103
104 private function error(Closure $cc): Closure
105 {
106 return static fn($error): Result => $cc(new Error($error));
107 }
108}
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Ok.php:31
to(Transformation $transformation, Closure $parse)
Transforms the value parsed by the given $parse parameter to the value returned by $transformation.
Definition: Transform.php:38
combine(Intermediate $hasAccepted, Intermediate $hasTodos, Closure $cc)
Definition: Transform.php:95
from(Closure $transform, Closure $parse)
Definition: Transform.php:82
removeArrayLevel($value)
self::to MUST add one array level, because it may be used in a context where more array levels are ad...
Definition: Transform.php:73
as(string $key, Closure $parse)
The value parsed by the given $parse parameter will be stored under the key $key.
Definition: Transform.php:61
ilErrorHandling $error
Definition: class.ilias.php:69
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:29
then(callable $f)
Get a new result from the callable or do nothing if this is an error.
A transformation is a function from one datatype to another.
applyTo(Result $result)
Perform the transformation and reify possible failures.