Skip to content

Instantly share code, notes, and snippets.

@Danack
Created August 23, 2019 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danack/3091169b4be64ba8e1f79788c8120a96 to your computer and use it in GitHub Desktop.
Save Danack/3091169b4be64ba8e1f79788c8120a96 to your computer and use it in GitHub Desktop.
toArray + toString
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);
}
<?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;
}
}
<?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