A modest collection of PHP libraries used at SparkFun.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.7 KiB

  1. <?php
  2. namespace SparkLib;
  3. use InvalidArgumentException;
  4. abstract class Iterator implements \Iterator {
  5. protected $_useCache = false;
  6. /**
  7. * Require that children of this class implement a getNext()
  8. */
  9. abstract public function getNext ();
  10. /**
  11. * Should child classes attempt to use cached return values?
  12. *
  13. * It's up to a child to decide what, if anything, this means.
  14. */
  15. public function useCache ($value = true)
  16. {
  17. $this->_useCache = $value;
  18. return $this;
  19. }
  20. /**
  21. * Calls $function() on each remaining element in the iterator.
  22. *
  23. * @param callback $function
  24. * @return SparkFriendFinder the finder
  25. */
  26. public function each ($function)
  27. {
  28. if (! \is_callable($function) )
  29. throw new InvalidArgumentException('each(): parameter is not a callback');
  30. // handle first/current result
  31. $rec = $this->getNext();
  32. if (! $rec)
  33. return $this;
  34. call_user_func($function, $rec);
  35. // handle the rest, if any
  36. while ($this->valid()) {
  37. $rec = $this->getNext();
  38. if ($rec) {
  39. call_user_func($function, $rec);
  40. }
  41. }
  42. return $this;
  43. }
  44. /**
  45. * Map iterator results to an array, using a callback function.
  46. *
  47. * Dubiously, this cannot yet elide or combine elements, but it's
  48. * still somewhat useful.
  49. *
  50. * @param callback $function
  51. * @return array $results
  52. */
  53. public function map ($function)
  54. {
  55. if (! \is_callable($function))
  56. throw new InvalidArgumentException('map(): parameter is not a callback.');
  57. $results = [];
  58. $this->each(function ($result) use ($function, &$results) {
  59. $results[] = call_user_func($function, $result);
  60. });
  61. return $results;
  62. }
  63. }