Skip to content

Instantly share code, notes, and snippets.

@jwage
Last active August 29, 2015 14:06
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 jwage/6d9e99ebb82bd3b4b243 to your computer and use it in GitHub Desktop.
Save jwage/6d9e99ebb82bd3b4b243 to your computer and use it in GitHub Desktop.
<?php
$em = getYourEntityManager();
$object = $em->getRepository('Object')->find(1);
$serializer = new ObjectSerializer($em);
$serialized = $serializer->serialize($object, 2);
<?php
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Persistence\ObjectManager;
class ObjectSerializer
{
private $om;
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
public function serialize($object, $maxDepth = 1)
{
$visited = array();
return $this->doSerialize($object, $visited, $maxDepth);
}
private function doSerialize($object, array &$visited, $maxDepth)
{
if ($object === null) {
return;
}
$oid = spl_object_hash($object);
if (!isset($visited[$oid])) {
$visited[$oid] = 0;
}
$visited[$oid]++;
if ($visited[$oid] > $maxDepth) {
return;
}
$metadata = $this->om->getClassMetadata(get_class($object));
$serialized = array();
foreach ($metadata->getFieldNames() as $fieldName) {
$serialized[$fieldName] = $metadata->getFieldValue($object, $fieldName);
}
foreach ($metadata->getAssociationNames() as $associationName) {
$associationValue = $metadata->getFieldValue($object, $associationName);
if ($associationValue === null) {
continue;
}
if ($metadata->isCollectionValuedAssociation($associationName)) {
if ($associationValue instanceof Collection || is_array($associationValue)) {
foreach ($associationValue as $collectionObject) {
$serialized[$associationName][] = $this->doSerialize($collectionObject, $visited, $maxDepth);
}
}
} else {
$serialized[$associationName] = $this->doSerialize($associationValue, $visited, $maxDepth);
}
}
return $serialized;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment