26 public const INT =
'Int';
38 public const DATE =
'Date';
41 private $fieldMap = [];
45 if (!empty($fieldMap))
47 $this->fieldMap = $fieldMap;
51 private function castToNothing($value)
56 private function castToString($value): string
58 return (
string)$value;
61 private function castToNullableString($value): ?string
65 $value = $this->castToString($value);
71 private function castToInt($value): int
76 private function castToNullableInt($value): ?int
80 $value = $this->castToInt($value);
86 private function castToMultiInt($value): array
89 if (!is_array($value))
93 foreach ($value as $item)
95 if ($item ===
'' || $item ===
null)
99 $result[] = (int)$item;
105 private function castToNullableMultiInt($value): ?array
109 $value = $this->castToMultiInt($value);
119 private function castToFloat($value): float
121 return (
float)$value;
124 private function castToNullableFloat($value): ?float
128 $value = $this->castToFloat($value);
134 private function castToYesOrNo($value): string
138 return $value ?
'Y' :
'N';
141 return (
string)$value ===
'Y' ?
'Y' :
'N';
144 private function castToYesOrNoOrDefault($value): string
148 return $value ?
'Y' :
'N';
151 $value = (string)$value;
153 if ($value !==
'Y' && $value !==
'D')
161 private function castToBoolean($value): bool
166 private function castToDate($value): ?Date
168 if ($value !==
null && $value !==
'')
170 return new Date($value);
176 private function castToDateTime($value): ?DateTime
178 if ($value !==
null && $value !==
'')
180 return new DateTime($value);
186 public function cast($name, $value)
188 if ($this->
has($name))
190 if (is_string($this->fieldMap[$name]))
192 $castMethod =
"castTo{$this->fieldMap[$name]}";
193 if (is_callable([$this, $castMethod]))
195 return $this->$castMethod($value);
199 if (is_callable($this->fieldMap[$name]))
201 return $this->fieldMap[$name]($value);
205 'Could not find casting {%s} for field {%s}.',
206 $this->fieldMap[$name], $name
213 public function has($name): bool
215 return isset($this->fieldMap[$name]);