Blame view

framework/view/ArrayData.php 2.28 KB
0084d336   Administrator   Importers CRUD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
  <?php
  /**
   * Lets you wrap a bunch of array data, or object members, into a {@link ViewableData} object.
   *
   * <code>
   * new ArrayData(array(
   *    "ClassName" => "Page",
   *    "AddAction" => "Add a new Page page",
   * ));
   * </code>
   *
   * @package framework
   * @subpackage view
   */
  class ArrayData extends ViewableData {
  
  	/**
  	 * @var array 
  	 * @see ArrayData::_construct()
  	 */
  	protected $array;
  	
  	/**
  	 * @param object|array $value An associative array, or an object with simple properties.
  	 * Converts object properties to keys of an associative array.
  	 */
  	public function __construct($value) {
  		if (is_object($value)) {
  			$this->array = get_object_vars($value);
  		} elseif (ArrayLib::is_associative($value)) {
  			$this->array = $value;
  		} elseif (is_array($value) && count($value) === 0) {
  			$this->array = array();
  		} else {
  			$message = 'Parameter to ArrayData constructor needs to be an object or associative array';
  			throw new InvalidArgumentException($message);
  		}
  		parent::__construct();
  	}
  	
  	/**
  	 * Get the source array
  	 *
  	 * @return array
  	 */
  	public function toMap() {
  		return $this->array;
  	}
  	
  	/**
  	 * Gets a field from this object.
  	 *
  	 * @param string $field
  	 *
  	 * If the value is an object but not an instance of
  	 * ViewableData, it will be converted recursively to an
  	 * ArrayData.
  	 *
  	 * If the value is an associative array, it will likewise be
  	 * converted recursively to an ArrayData.
  	 */
  	public function getField($f) {
  		$value = $this->array[$f];
  		if (is_object($value) && !$value instanceof ViewableData) {
  			return new ArrayData($value);
  		} elseif (ArrayLib::is_associative($value)) {
  			return new ArrayData($value);
  		} else {
  			return $value;
  		}
  	}
  	/**
  	* Add or set a field on this object.
  	*
  	* @param string $field
  	* @param mixed $value
  	*/
  	public function setField($field, $value) {
  		$this->array[$field] = $value;
  	}
  	
  	/**
  	 * Check array to see if field isset
  	 *
  	 * @param string Field Key
  	 * @return bool
  	 */
  	public function hasField($f) {
  		return isset($this->array[$f]);
  	}
  	
  	/**
  	 * Converts an associative array to a simple object
  	 *
  	 * @param array
  	 * @return obj $obj
  	 */
  	public static function array_to_object($arr = null) {
  		$obj = new stdClass();
  		if ($arr) foreach($arr as $name => $value) $obj->$name = $value;
  		return $obj;
  	}
  
  }