1: <?php
2: namespace NGS;
3:
4: use NGS\Converter\PrimitiveConverter;
5:
6: class Location
7: {
8: protected $x;
9: protected $y;
10:
11: public function __construct($x=0, $y=0)
12: {
13: if (is_array($x)) {
14: $this->setX($x['X']);
15: $this->setY($x['Y']);
16: }
17: elseif ($x instanceof Location) {
18: $this->setX($x->x);
19: $this->setY($x->y);
20: }
21: elseif ($x instanceof Point) {
22: $this->setX($x->x);
23: $this->setY($x->y);
24: }
25: else {
26: $this->setX($x);
27: $this->setY($y);
28: }
29: }
30:
31: 32: 33: 34: 35: 36: 37:
38: public static function toArray(array $items, $allowNullValues=false)
39: {
40: $results = array();
41: try {
42: foreach ($items as $key => $val) {
43: if ($allowNullValues && $val===null) {
44: $results[] = null;
45: } elseif ($val === null) {
46: throw new \InvalidArgumentException('Null value found in provided array');
47: } elseif (!$val instanceof \NGS\Location) {
48: $results[] = new \NGS\Location($val);
49: } else {
50: $results[] = $val;
51: }
52: }
53: }
54: catch(\Exception $e) {
55: throw new \InvalidArgumentException('Element at index '.$key.' could not be converted to Location!', 42, $e);
56: }
57: return $results;
58: }
59:
60: public static function toArrayList(array $items)
61: {
62: $results = array();
63: foreach ($items as $key => $val) {
64: if ($val === null) {
65: $results[] = null;
66: } elseif (!$val instanceof \NGS\Location) {
67: throw new \InvalidArgumentException('Value was not an instance of NGS\Location');
68: } else {
69: $results[] = $val->asArray();
70: }
71: }
72: return $results;
73: }
74:
75: public function asArray()
76: {
77: return array(
78: 'X' => $this->x,
79: 'Y' => $this->y
80: );
81: }
82:
83: public function __get($name)
84: {
85: if ($name==='x') {
86: return $this->x;
87: }
88: if ($name==='y') {
89: return $this->y;
90: }
91: throw new \InvalidArgumentException('Cannot use getter on invalid property '.$name.' in NGS\\Location');
92: }
93:
94: public function setX($value)
95: {
96: $this->x = PrimitiveConverter::toFloat($value);
97: }
98:
99: public function setY($value)
100: {
101: $this->y = PrimitiveConverter::toFloat($value);
102: }
103:
104: public function __set($name, $value)
105: {
106: if ($name==='x') {
107: $this->setX($value);
108: }
109: if ($name==='y') {
110: $this->setY($value);
111: }
112: throw new \InvalidArgumentException('Cannot use setter on invalid property '.$name.' in NGS\\Location');
113: }
114:
115: public function __toString()
116: {
117: return json_encode($this->asArray());
118: }
119: }
120: