Nextras\Orm\Entity\ToArrayConverter::toArray PHP Méthode

toArray() public static méthode

Converts IEntity to array
public static toArray ( Nextras\Orm\Entity\IEntity $entity, integer $type = IEntity::TO_ARRAY_RELATIONSHIP_AS_IS, integer $recursionLevel ) : array | null
$entity Nextras\Orm\Entity\IEntity
$type integer
$recursionLevel integer
Résultat array | null
    public static function toArray(IEntity $entity, $type = IEntity::TO_ARRAY_RELATIONSHIP_AS_IS, $recursionLevel = 0)
    {
        if ($recursionLevel >= static::$maxRecursionLevel) {
            return null;
        }
        $return = [];
        $metadata = $entity->getMetadata();
        foreach ($metadata->getProperties() as $name => $metadataProperty) {
            if (!$entity->hasValue($name)) {
                $value = null;
            } else {
                $value = $entity->getValue($name);
            }
            if ($value instanceof IEntity) {
                if ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ID) {
                    $value = $value->getValue('id');
                } elseif ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ARRAY) {
                    $value = static::toArray($value, $type, $recursionLevel + 1);
                }
            } elseif ($value instanceof IRelationshipCollection) {
                if ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ID) {
                    $collection = [];
                    foreach ($value as $collectionEntity) {
                        $collection[] = $collectionEntity->getValue('id');
                    }
                    $value = $collection;
                } elseif ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ARRAY) {
                    $collection = [];
                    foreach ($value as $collectionEntity) {
                        $collection[] = static::toArray($collectionEntity, $type, $recursionLevel + 1);
                    }
                    $value = $collection;
                }
            }
            $return[$name] = $value;
        }
        return $return;
    }

Usage Example

Exemple #1
0
 public function toArray($mode = self::TO_ARRAY_RELATIONSHIP_AS_IS)
 {
     return ToArrayConverter::toArray($this, $mode);
 }
ToArrayConverter