From c4c887c46b479e569af32fb4acb52e74dc2fb9f8 Mon Sep 17 00:00:00 2001 From: hantianfeng Date: Fri, 6 Sep 2024 16:51:10 +0800 Subject: [PATCH] Fix crash when object is not iterable --- src/php/object.cc | 12 ++++++++---- tests/phpunit/IterTest.php | 10 ++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/php/object.cc b/src/php/object.cc index 6bea5ab..7b23cb6 100644 --- a/src/php/object.cc +++ b/src/php/object.cc @@ -62,17 +62,21 @@ PyObject *phpy_object_get_iterator(zval *object) { void phpy_object_iterator_reset(zval *object) { auto oo = phpy_object_get_object(object); - // Return value: New reference if (oo->iterator != NULL) { Py_DECREF(oo->iterator); } - oo->iterator = PyObject_GetIter(oo->object); - // Return value: New reference if (oo->current != NULL) { Py_DECREF(oo->current); } - oo->current = PyIter_Next(oo->iterator); oo->index = 0; + // Return value: New reference + oo->iterator = PyObject_GetIter(oo->object); + if (oo->iterator == NULL) { + phpy::php::throw_error_if_occurred(); + } else { + // Return value: New reference + oo->current = PyIter_Next(oo->iterator); + } } PyObject *phpy_object_iterator_next(zval *object) { diff --git a/tests/phpunit/IterTest.php b/tests/phpunit/IterTest.php index d4dd468..60df147 100644 --- a/tests/phpunit/IterTest.php +++ b/tests/phpunit/IterTest.php @@ -41,4 +41,14 @@ function testNextInt() } $this->assertEquals($array, range(1, 12)); } + + function testNotIterable() + { + $slice = PyCore::slice(1, 10); + try { + $iter = PyCore::iter($slice); + } catch (PyError $error) { + $this->assertStringContainsString("'slice' object is not iterable", $error->getMessage()); + } + } }