Permalink
Browse files

Add $generator->close() method

Calling $generator->close() is equivalent to executing a return statement
at the current position in the generator.
  • Loading branch information...
1 parent 12e9283 commit 72a91d08e7d70d5524feb6cc7c8e32b3bd68f1df @nikic committed May 29, 2012
Showing with 49 additions and 0 deletions.
  1. +32 −0 Zend/tests/generators/generator_close.phpt
  2. +17 −0 Zend/zend_generators.c
View
32 Zend/tests/generators/generator_close.phpt
@@ -0,0 +1,32 @@
+--TEST--
+Generator can be closed by calling ->close()
+--FILE--
+<?php
+
+function *allNumbers() {
+ for ($i = 0; true; ++$i) {
+ yield $i;
+ }
+}
+
+$numbers = allNumbers();
+
+foreach ($numbers as $n) {
+ var_dump($n);
+ if ($n == 9) {
+ $numbers->close();
+ }
+}
+
+?>
+--EXPECT--
+int(0)
+int(1)
+int(2)
+int(3)
+int(4)
+int(5)
+int(6)
+int(7)
+int(8)
+int(9)
View
17 Zend/zend_generators.c
@@ -324,6 +324,22 @@ ZEND_METHOD(Generator, send)
zend_generator_resume(object, generator TSRMLS_CC);
}
+/* {{{ proto void Generator::close()
+ * Closes the generator */
+ZEND_METHOD(Generator, close)
+{
+ zend_generator *generator;
+
+ if (zend_parse_parameters_none() == FAILURE) {
+ return;
+ }
+
+ generator = (zend_generator *) zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ zend_generator_close(generator, 0);
+}
+/* }}} */
+
ZEND_BEGIN_ARG_INFO(arginfo_generator_void, 0)
ZEND_END_ARG_INFO()
@@ -338,6 +354,7 @@ static const zend_function_entry generator_functions[] = {
ZEND_ME(Generator, key, arginfo_generator_void, ZEND_ACC_PUBLIC)
ZEND_ME(Generator, next, arginfo_generator_void, ZEND_ACC_PUBLIC)
ZEND_ME(Generator, send, arginfo_generator_send, ZEND_ACC_PUBLIC)
+ ZEND_ME(Generator, close, arginfo_generator_void, ZEND_ACC_PUBLIC)
ZEND_FE_END
};

0 comments on commit 72a91d0

Please sign in to comment.