11<?php
22namespace PHPHtmlParser \Dom ;
33
4- use IteratorAggregate ;
5- use ArrayIterator ;
6- use ArrayAccess ;
74use Countable ;
5+ use ArrayAccess ;
6+ use ArrayIterator ;
7+ use IteratorAggregate ;
88
99class Collection implements IteratorAggregate, ArrayAccess, Countable {
1010
@@ -15,6 +15,54 @@ class Collection implements IteratorAggregate, ArrayAccess, Countable {
1515 */
1616 protected $ collection = [];
1717
18+ /**
19+ * Attempts to call the method on the first node in
20+ * the collection.
21+ *
22+ * @param string $method
23+ * @param array $arguments
24+ * @return mixed;
25+ */
26+ public function __call ($ method , $ arguments )
27+ {
28+ $ node = reset ($ this ->collection );
29+ if ($ node instanceof Node)
30+ {
31+ return call_user_func_array ([$ node , $ method ], $ arguments );
32+ }
33+ }
34+
35+ /**
36+ * Attempts to apply the magic get to the first node
37+ * in the collection.
38+ *
39+ * @param mixed $key
40+ * @return mixed
41+ */
42+ public function __get ($ key )
43+ {
44+ $ node = reset ($ this ->collection );
45+ if ($ node instanceof Node)
46+ {
47+ return $ node ->$ key ;
48+ }
49+ }
50+
51+ /**
52+ * Applies the magic string method to the first node in
53+ * the collection.
54+ *
55+ * @return string
56+ */
57+ public function __toString ()
58+ {
59+ $ node = reset ($ this ->collection );
60+ if ($ node instanceof Node)
61+ {
62+ return (string ) $ node ;
63+ }
64+ }
65+
1866 /**
1967 * Returns the count of the collection.
2068 *
@@ -84,4 +132,16 @@ public function offsetGet($offset)
84132 {
85133 return isset ($ this ->collection [$ offset ]) ? $ this ->collection [$ offset ] : null ;
86134 }
135+
136+ /**
137+ * Similar to jQuery "each" method. Calls the callback with each
138+ * Node in this collection.
139+ */
140+ public function each ($ callback )
141+ {
142+ foreach ($ this ->collection as $ key => $ value )
143+ {
144+ $ callback ($ value , $ key );
145+ }
146+ }
87147}
0 commit comments