Generator.hx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package php;
  2. /**
  3. @see http://php.net/manual/en/class.generator.php
  4. Generator is not a Haxe Iterable. It can be iterated one time only.
  5. Unfortunately Haxe does not know that in PHP generators may have no `return` expression or `return value` with any type of `value`.
  6. Use `return null` or untyped cast to workaround this issue:
  7. ```
  8. function generatorWithoutReturn():Generator {
  9. php.Syntax.yield(1);
  10. return null;
  11. }
  12. function generatorWithReturn():Generator {
  13. php.Syntax.yield(1);
  14. return cast "hello";
  15. }
  16. var g = generatorWithReturn();
  17. for(i in g) {
  18. trace(i);
  19. }
  20. trace(g.getReturn()); // "hello"
  21. ```
  22. **/
  23. @:native('Generator')
  24. extern class Generator {
  25. function current() : Dynamic;
  26. function getReturn() : Dynamic;
  27. function key() : Dynamic;
  28. function next() : Void;
  29. function rewind() : Void;
  30. function send(value : Dynamic) : Dynamic;
  31. @:native('throw')
  32. function throwError(exception : Throwable) : Dynamic;
  33. function valid() : Bool;
  34. inline function iterator():GeneratorIterator {
  35. return new GeneratorIterator(this);
  36. }
  37. }
  38. private class GeneratorIterator {
  39. var generator : Generator;
  40. /**
  41. This field is required to maintain execution order of .next()/.valid()/.current() methods.
  42. @see http://php.net/manual/en/class.iterator.php
  43. **/
  44. var first : Bool = true;
  45. public inline function new(generator : Generator) {
  46. this.generator = generator;
  47. }
  48. public inline function hasNext() : Bool {
  49. if(first) {
  50. first = false;
  51. } else {
  52. generator.next();
  53. }
  54. return generator.valid();
  55. }
  56. public inline function next() : Dynamic {
  57. return generator.current();
  58. }
  59. }