Created
February 22, 2012 17:33
-
-
Save zspine/1886214 to your computer and use it in GitHub Desktop.
Pimcore Object toArray()
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 | |
class Website_Model_Product extends Object_Concrete | |
{ | |
/** | |
* Retreive the values in an array | |
* | |
* @return array | |
*/ | |
public function toArray() | |
{ | |
return self::_toArray($this); | |
} | |
/** | |
* Retreive the values in json format | |
* | |
* @return string | |
*/ | |
public function toJson() | |
{ | |
return json_encode(self::_toArray($this)); | |
} | |
/** | |
* Re-usable helper method | |
* @todo move to the library helpers | |
* | |
* @static | |
* @param $object | |
* @param null $fieldDefintions | |
* @return array | |
*/ | |
protected static function _toArray($object, $fieldDefintions=null) | |
{ | |
//if the given object is an array then loop through each element | |
if(is_array($object)) | |
{ | |
$collections = array(); | |
foreach($object as $o) | |
{ | |
$collections[] = self::_toArray($o, $fieldDefintions); | |
} | |
return $collections; | |
} | |
if(!is_object($object)) return false; | |
//Custom list field definitions | |
if(null === $fieldDefintions) | |
{ | |
$fieldDefintions = $object->getClass()->getFieldDefinitions(); | |
} | |
$collection = array(); | |
foreach($fieldDefintions as $fd) | |
{ | |
$fieldName = $fd->getName(); | |
$getter = "get" . ucfirst($fieldName); | |
$value = $object->$getter(); | |
switch($fd->getFieldtype()) | |
{ | |
case 'fieldcollections': | |
if(($value instanceof Object_Fieldcollection) && is_array($value->getItems())) | |
{ | |
/** @var $value Object_Fieldcollection */ | |
$def = $value->getItemDefinitions(); | |
$collection[$fieldName] = self::_toArray($value->getItems(), $def['children']->getFieldDefinitions()); | |
} | |
break; | |
case 'date': | |
/** @var $value Pimcore_Date */ | |
$collection[$fieldName] = ($value instanceof Pimcore_Date) ? $value->getTimestamp() : 0; | |
break; | |
default: | |
/** @var $value string */ | |
$collection[$fieldName] = $value; | |
} | |
} | |
//Parent class properties | |
$collection['id'] = $object->o_id; | |
$collection['key'] = $object->o_key; | |
return $collection; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment