Add base\Struct from phalanx
[hoplite.git] / base / struct.php
1 <?php
2 // Hoplite
3 // Copyright (c) 2011 Blue Static
4 //
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.
8 //
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
12 // more details.
13 //
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/>.
16
17 namespace hoplite\base;
18
19 /*!
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.
22 */
23 class Struct
24 {
25 /*! @var array The fields of this struct. */
26 protected $fields = array();
27
28 /*! @var array The data that corresponds to the |$fields|. */
29 protected $data = array();
30
31 /*!
32 Creates a new Struct, optionally initializing the data members from an
33 iterable object.
34 */
35 public function __construct($data = array())
36 {
37 foreach ($data as $key => $value)
38 if (!in_array($key, $this->fields))
39 throw new StructException('Invalid field "' . $key . '"');
40 else
41 $this->data[$key] = $value;
42 }
43
44 /*! Gets a specified key. This can return NULL. */
45 public function __get($key)
46 {
47 if (!in_array($key, $this->fields))
48 throw new StructException('Invalid field "' . $key . '"');
49
50 if (!isset($this->data[$key]))
51 return NULL;
52
53 return $this->data[$key];
54 }
55 public function Get($key) { return $this->__get($key); }
56
57 /*! Sets the specified key-value pair. */
58 public function __set($key, $value)
59 {
60 if (!in_array($key, $this->fields))
61 throw new StructException('Cannot set value for invalid field "' . $key . '"');
62 $this->data[$key] = $value;
63 }
64 public function Set($key, $value) { $this->__set($key, $value); }
65
66 /*! Takes values from an array or object and sets the relevant values. */
67 public function SetFrom($array)
68 {
69 foreach ($array as $key => $value)
70 if (in_array($key, $this->fields))
71 $this->data[$key] = $value;
72 }
73
74 /*! Returns the data members as an array. */
75 public function ToArray()
76 {
77 return $this->data;
78 }
79
80 /*! Returns the number of members in the struct. */
81 public function Count()
82 {
83 return count($this->fields);
84 }
85
86 /*! Returns the list of fields the Struct has. */
87 public function GetFields()
88 {
89 return $this->fields;
90 }
91 }
92
93 class StructException extends \Exception {}