-
-
Save Danack/3091169b4be64ba8e1f79788c8120a96 to your computer and use it in GitHub Desktop.
toArray + toString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convertToValue($name, $value) | |
{ | |
if (is_scalar($value) === true) { | |
return $value; | |
} | |
if ($value === null) { | |
return null; | |
} | |
$callable = [$value, 'toArray']; | |
if (is_object($value) === true && is_callable($callable)) { | |
return $callable(); | |
} | |
if (is_object($value) === true && $value instanceof \DateTime) { | |
return $value->format("Y-m-d\TH:i:s.uP"); | |
} | |
if (is_array($value) === true) { | |
$values = []; | |
foreach ($value as $key => $entry) { | |
$values[$key] = convertToValue($key, $entry); | |
} | |
return $values; | |
} | |
$message = "Unsupported type [" . gettype($value) . "] for toArray for property $name."; | |
if (is_object($value) === true) { | |
$message = "Unsupported type [" . gettype($value) . "] of class [" . get_class($value) . "] for toArray for property $name."; | |
} | |
throw new \Exception($message); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait ToArray | |
{ | |
public function toArray(): array | |
{ | |
$data = []; | |
foreach ($this as $name => $value) { | |
if (strpos($name, '__') === 0) { | |
//Skip | |
continue; | |
} | |
$data[$name] = \convertToValue($name, $value); | |
} | |
return $data; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait ToString | |
{ | |
public function toArray(): array | |
{ | |
$data = []; | |
foreach ($this as $name => $value) { | |
if (strpos($name, '__') === 0) { | |
//Skip | |
continue; | |
} | |
$data[$name] = \convertToValue($name, $value); | |
} | |
return $data; | |
} | |
public function toString() | |
{ | |
return json_encode_safe($this->toArray()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment