ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
Marshal.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
24use ILIAS\Refinery\Factory as Refinery;
25use DateTimeImmutable;
26use Closure;
27use Exception;
28
30{
31 public function __construct(private readonly Refinery $refinery)
32 {
33 }
34
35 public function dateTime(): Convert
36 {
37 $from = $this->refinery->in()->series([
38 $this->custom(fn(string $s) => '@' . ($s ?: '0')),
39 $this->refinery->to()->dateTime(),
40 ]);
41
42 $to = $this->custom(fn(DateTimeImmutable $x) => (string) $x->getTimeStamp());
43
44 return new Convert($from, $to);
45 }
46
47 public function boolean(): Convert
48 {
49 // kindlyTo()->bool() doesn't count an empty string as `false`:
50 $from = $this->refinery->byTrying([
51 $this->refinery->kindlyTo()->bool(),
52 $this->custom(fn(string $s): bool => !($s === '' || $this->error('Value could not be transformed to bool.')))
53 ]);
54
55 $to = $this->refinery->kindlyTo()->string();
56
57 return new Convert($from, $to);
58 }
59
60 public function nullable(Convert $convert): Convert
61 {
62 $from = $this->refinery->byTrying([
63 $this->refinery->kindlyTo()->null(),
64 $convert->fromString(),
65 ]);
66
67 $to = $this->refinery->byTrying([
68 $this->refinery->in()->series([$this->refinery->null(), $this->refinery->always('')]),
69 $convert->toString(),
70 ]);
71
72 return new Convert($from, $to);
73 }
74
75 public function string(): Convert
76 {
77 return new Convert(
78 $this->refinery->identity(),
79 $this->refinery->identity()
80 );
81 }
82
83 private function custom(Closure $map): Transformation
84 {
85 return $this->refinery->custom()->transformation($map);
86 }
87
88 private function error(string $message): void
89 {
90 throw new Exception($message);
91 }
92}
Builds data types.
Definition: Factory.php:36
__construct(private readonly Refinery $refinery)
Definition: Marshal.php:31
A transformation is a function from one datatype to another.
$message
Definition: xapiexit.php:31