Version: current

     1 <?php
     2 /**
     3  * Lets you wrap a bunch of array data into a {@link ViewableData} object.
     4  *
     5  * <code>
     6  * new ArrayData(array(
     7  *    "ClassName" => "Page",
     8  *    "AddAction" => "Add a new Page page",
     9  * ));
    10  * </code>
    11  *
    12  * @package sapphire
    13  * @subpackage view
    14  */
    15 class ArrayData extends ViewableData {
    16
    17     protected $array;
    18
    19     /**
    20      * @param object|array $array Either an object with simple properties or an associative array.
    21      * Converts object-properties to indices of an associative array.
    22      */
    23     public function __construct($array) {
    24         if(is_object($array)) {
    25             $this->array = self::object_to_array($array);
    26         } elseif(is_array($array) && (ArrayLib::is_associative($array) || count($array) === 0)) {
    27             $this->array = $array;
    28         } else {
    29             $this->array = $array;
    30             user_error(
    31                 "ArrayData::__construct: Parameter needs to be an object or associative array",
    32                 E_USER_WARNING
    33             );
    34         }
    35         parent::__construct();
    36     }
    37
    38     public function getField($f) {
    39         if((is_object($this->array[$f]) && !$this->array[$f] instanceof ViewableData) || (is_array($this->array[$f]) && ArrayLib::is_associative($this->array[$f]))) {
    40             return new ArrayData($this->array[$f]);
    41         } else {
    42             return $this->array[$f];
    43         }
    44     }
    45
    46     public function hasField($f) {
    47         return isset($this->array[$f]);
    48     }
    49
    50     /**
    51      * Converts an object with simple properties to
    52      * an associative array.
    53      *
    54      * @param obj $obj
    55      * @return array
    56      */
    57     protected static function object_to_array($obj) {
    58         $arr = array();
    59         foreach($obj as $k=>$v) {
    60             $arr[$k] = $v;
    61         }
    62
    63         return $arr;
    64     }
    65
    66     /**
    67      * This is pretty crude, but it helps diagnose error situations
    68      */
    69     function forTemplate() {
    70         return var_export($this->array, true);
    71     }
    72
    73     function getAllFields() {
    74         return $this->array;
    75     }
    76 }
    77
    78 ?>

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -