Skip to content

Instantly share code, notes, and snippets.

@semihkeskindev
Last active January 1, 2025 01:42
Show Gist options
  • Save semihkeskindev/e751caf0bf52d776bf5f20e2d10b326c to your computer and use it in GitHub Desktop.
Save semihkeskindev/e751caf0bf52d776bf5f20e2d10b326c to your computer and use it in GitHub Desktop.
Convert class to simple object using reflection
<?php
/**
* Create a simplified object suitable for straightforward
* conversion to JSON. This is relatively expensive
* due to the usage of reflection, but shouldn't be called
* a whole lot, and is the most straightforward way to filter.
*/
public function toSimpleObject()
{
$object = new stdClass();
// Process all other data.
foreach ($this->modelData as $key => $val) {
$result = $this->getSimpleValue($val);
if ($result !== null) {
$object->$key = $this->nullPlaceholderCheck($result);
}
}
// Process all public properties.
$reflect = new ReflectionObject($this);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $member) {
$name = $member->getName();
$result = $this->getSimpleValue($this->$name);
if ($result !== null) {
$name = $this->getMappedName($name);
$object->$name = $this->nullPlaceholderCheck($result);
}
}
return $object;
}
@semihkeskindev
Copy link
Author

This method is copied from \Google\Model::toSimpleObject(google/apiclient package)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment