No Description

Collection.php 2.3KB

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