Location: PHPKode > scripts > Redstart Templating > Redstart-Templating-master/Redstart/Util/ObjectToDict.php
<?php

namespace Redstart\Util;

use Redstart\Util\Dict;

/**
 * ObjectToDict
 *
 * Take any kind of php object and convert its non-static public properties into 
 * A Dictionary Object or php array.
 * 
 * <b> Note :</b>
 * If the variables declared in the class of which the object is an instance, 
 * have not been assigned a value, those will not be included in the array
 * 
 * <b>Example :</b>
 * 
 * <code>
 *  use Redstart\Util\ObjectToDict;
 * 
 *  class Object {
 *      public $public = "I am public";
 *      public $publicNotIncluded;
 *  }
 *  
 *  $dict=ObjectToDict::convert(new Object());
 *  $array=ObjectToDict::convert(new Object(),ObjectToDict::CT_ARRAY);
 *  var_dump($dict->items())
 *  print_r($array)
 * </code>
 * 
 * @package Redstart
 * @subpackage Redstart_Util
 *
 * @author Hyyan Abo Fakher
 * @since Redstart 1.0
 * @version 1.0
 */
class ObjectToDict {

    const CT_ARRAY = "array";
    const CT_DICT = "dict";

    /**
     * Convert the non-static  properties of php object into Dictionary Object or
     * php array .
     * 
     * <b>Note :</b>
     * see <b>ObjectToDict<b> class documentation to read the usage example.
     * 
     * @param object $obj php object(class,interface,array,..)
     * @param string $type (ObjectToDict::CT_DICT) Or(ObjectToDict::CT_ARRAY)
     * @throws \InvalidArgumentException
     * @return Dict|array
     */
    public static function convert($obj, $type = self::CT_DICT) {
        if (!in_array($type, array($type == self::CT_ARRAY || $type == self::CT_DICT))) {
            throw new \InvalidArgumentException(
                    sprintf(
                            "Expect (ObjectToDict::CT_DICT) Or (ObjectToDict::CT_ARRAY)"
                            . " But (%s) Was Given"
                            , gettype($type)
                    )
            );
        }
        $arrData = array();
        if (is_object($obj)) {
            $obj = get_object_vars($obj);
        }
        if (is_array($obj)) {
            foreach ($obj as $index => $value) {
                if (is_object($value) || is_array($value)) {
                    $value = self::convert($value, $type);
                }
                $arrData[$index] = $value;
            }
        }
        return ($type == self::CT_DICT) ? new Dict($arrData) : $arrData;
    }

}

Return current item: Redstart Templating