3 // Copyright (c) 2011 Blue Static
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
17 namespace hoplite
\base
;
20 A struct can be used to maintain a list of properties. Any properties not
21 strictly defined in the |$fields| array will throw exceptions when accessed.
25 /*! @var array The fields of this struct. */
26 protected $fields = array();
28 /*! @var array The data that corresponds to the |$fields|. */
29 protected $data = array();
32 Creates a new Struct, optionally initializing the data members from an
35 public function __construct($data = array())
37 foreach ($data as $key => $value)
38 if (!in_array($key, $this->fields
))
39 throw new StructException('Invalid field "' . $key . '"');
41 $this->data
[$key] = $value;
44 /*! Gets a specified key. This can return NULL. */
45 public function __get($key)
47 if (!in_array($key, $this->fields
))
48 throw new StructException('Invalid field "' . $key . '"');
50 if (!isset($this->data
[$key]))
53 return $this->data
[$key];
55 public function Get($key) { return $this->__get($key); }
57 /*! Sets the specified key-value pair. */
58 public function __set($key, $value)
60 if (!in_array($key, $this->fields
))
61 throw new StructException('Cannot set value for invalid field "' . $key . '"');
62 $this->data
[$key] = $value;
64 public function Set($key, $value) { $this->__set($key, $value); }
66 /*! Takes values from an array or object and sets the relevant values. */
67 public function SetFrom($array)
69 foreach ($array as $key => $value)
70 if (in_array($key, $this->fields
))
71 $this->data
[$key] = $value;
74 /*! Returns the data members as an array. */
75 public function ToArray()
80 /*! Returns the number of members in the struct. */
81 public function Count()
83 return count($this->fields
);
86 /*! Returns the list of fields the Struct has. */
87 public function GetFields()
93 class StructException
extends \Exception
{}