| 1 |
<?php |
| 2 |
namespace wpCloud\StatelessMedia\Google_Client; |
| 3 |
|
| 4 |
/** |
| 5 |
* Extension to the regular Google_Model that automatically |
| 6 |
* exposes the items array for iteration, so you can just |
| 7 |
* iterate over the object rather than a reference inside. |
| 8 |
*/ |
| 9 |
class Google_Collection extends Google_Model implements \Iterator, \Countable |
| 10 |
{ |
| 11 |
protected $collection_key = 'items'; |
| 12 |
|
| 13 |
public function rewind() |
| 14 |
{ |
| 15 |
if (isset($this->{$this->collection_key}) |
| 16 |
&& is_array($this->{$this->collection_key})) { |
| 17 |
reset($this->{$this->collection_key}); |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
public function current() |
| 22 |
{ |
| 23 |
$this->coerceType($this->key()); |
| 24 |
if (is_array($this->{$this->collection_key})) { |
| 25 |
return current($this->{$this->collection_key}); |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
public function key() |
| 30 |
{ |
| 31 |
if (isset($this->{$this->collection_key}) |
| 32 |
&& is_array($this->{$this->collection_key})) { |
| 33 |
return key($this->{$this->collection_key}); |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
public function next() |
| 38 |
{ |
| 39 |
return next($this->{$this->collection_key}); |
| 40 |
} |
| 41 |
|
| 42 |
public function valid() |
| 43 |
{ |
| 44 |
$key = $this->key(); |
| 45 |
return $key !== null && $key !== false; |
| 46 |
} |
| 47 |
|
| 48 |
public function count() |
| 49 |
{ |
| 50 |
if (!isset($this->{$this->collection_key})) { |
| 51 |
return 0; |
| 52 |
} |
| 53 |
return count($this->{$this->collection_key}); |
| 54 |
} |
| 55 |
|
| 56 |
public function offsetExists($offset) |
| 57 |
{ |
| 58 |
if (!is_numeric($offset)) { |
| 59 |
return parent::offsetExists($offset); |
| 60 |
} |
| 61 |
return isset($this->{$this->collection_key}[$offset]); |
| 62 |
} |
| 63 |
|
| 64 |
public function offsetGet($offset) |
| 65 |
{ |
| 66 |
if (!is_numeric($offset)) { |
| 67 |
return parent::offsetGet($offset); |
| 68 |
} |
| 69 |
$this->coerceType($offset); |
| 70 |
return $this->{$this->collection_key}[$offset]; |
| 71 |
} |
| 72 |
|
| 73 |
public function offsetSet($offset, $value) |
| 74 |
{ |
| 75 |
if (!is_numeric($offset)) { |
| 76 |
return parent::offsetSet($offset, $value); |
| 77 |
} |
| 78 |
$this->{$this->collection_key}[$offset] = $value; |
| 79 |
} |
| 80 |
|
| 81 |
public function offsetUnset($offset) |
| 82 |
{ |
| 83 |
if (!is_numeric($offset)) { |
| 84 |
return parent::offsetUnset($offset); |
| 85 |
} |
| 86 |
unset($this->{$this->collection_key}[$offset]); |
| 87 |
} |
| 88 |
|
| 89 |
private function coerceType($offset) |
| 90 |
{ |
| 91 |
$keyType = $this->keyType($this->collection_key); |
| 92 |
if ($keyType && !is_object($this->{$this->collection_key}[$offset])) { |
| 93 |
$this->{$this->collection_key}[$offset] = |
| 94 |
new $keyType($this->{$this->collection_key}[$offset]); |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
|