Last active
January 1, 2025 01:42
-
-
Save semihkeskindev/e751caf0bf52d776bf5f20e2d10b326c to your computer and use it in GitHub Desktop.
Convert class to simple object using reflection
This file contains hidden or 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 | |
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This method is copied from \Google\Model::toSimpleObject(google/apiclient package)