Skip to content

Commit b9e5c7e

Browse files
committed
Improvements on handling boolean values in mapping from and to array.
1 parent 1df24c9 commit b9e5c7e

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/Rehyved/Utilities/Mapper/ObjectMapper.php

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,8 @@ private function coerceType($value, \ReflectionType $type)
233233
return (string)$value;
234234
case "array":
235235
return (array)$value;
236+
case 'bool':
237+
return is_bool($value) ? $value : StringHelper::equals($value, "true", true);
236238
default:
237239
return $value;
238240

@@ -253,6 +255,9 @@ private function coerceType($value, \ReflectionType $type)
253255
public function mapObjectToArray($object, string $prefix = "")
254256
{
255257
if (!is_object($object)) {
258+
if(is_bool($object)){
259+
return $object === true? "true" : "false";
260+
}
256261
return $object;
257262
}
258263
if (get_class($object) === \stdClass::class) {
@@ -298,7 +303,34 @@ private static function isOfValidType($value, $type)
298303

299304
private static function isOfCoercibleType($value, $type): bool
300305
{
301-
return (($type === "int" || $type === "double" || $type === "float") && is_numeric($value)) || ($type === "bool" && is_bool($value));
306+
return (self::isNumericType($type) && is_numeric($value)) || ($type === "bool" && self::isBooleanValue($value));
307+
}
308+
309+
/**
310+
* @param $value
311+
* @return bool
312+
*/
313+
private static function isBooleanStringValue($value): bool
314+
{
315+
return is_string($value) && StringHelper::equals($value, "true", true) || StringHelper::equals($value, "false", true);
316+
}
317+
318+
/**
319+
* @param $value
320+
* @return bool
321+
*/
322+
private static function isBooleanValue($value): bool
323+
{
324+
return is_bool($value) || self::isBooleanStringValue($value);
325+
}
326+
327+
/**
328+
* @param $type
329+
* @return bool
330+
*/
331+
private static function isNumericType($type): bool
332+
{
333+
return $type === "int" || $type === "double" || $type === "float";
302334
}
303335

304336
private static function isCustomType(\ReflectionType $propertyType)

0 commit comments

Comments
 (0)