From 451ba4c401ea8973f84a4ddad876e633a54cf60a Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Mon, 30 Apr 2018 04:14:30 +0000 Subject: [PATCH] General: Introduce a polyfill for `is_iterable()` function added in PHP 7.1. Props jrf, schlessera, desrosj. See #43619. git-svn-id: https://develop.svn.wordpress.org/trunk@43036 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/compat.php | 20 ++++++++++++++++- tests/phpunit/tests/compat.php | 41 ++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/compat.php b/src/wp-includes/compat.php index 77762cb6f6..cabe71d211 100644 --- a/src/wp-includes/compat.php +++ b/src/wp-includes/compat.php @@ -511,7 +511,7 @@ if ( ! function_exists( 'is_countable' ) ) { * Polyfill for is_countable() function added in PHP 7.3. * * Verify that the content of a variable is an array or an object - * implementing Countable. + * implementing the Countable interface. * * @since 4.9.6 * @@ -523,3 +523,21 @@ if ( ! function_exists( 'is_countable' ) ) { return ( is_array( $var ) || $var instanceof Countable ); } } + +if ( ! function_exists( 'is_iterable' ) ) { + /** + * Polyfill for is_iterable() function added in PHP 7.1. + * + * Verify that the content of a variable is an array or an object + * implementing the Traversable interface. + * + * @since 4.9.6 + * + * @param mixed $var The value to check. + * + * @return bool True if `$var` is iterable, false otherwise. + */ + function is_iterable( $var ) { + return ( is_array( $var ) || $var instanceof Traversable ); + } +} diff --git a/tests/phpunit/tests/compat.php b/tests/phpunit/tests/compat.php index 43f1600f25..0f17b2d7a8 100644 --- a/tests/phpunit/tests/compat.php +++ b/tests/phpunit/tests/compat.php @@ -230,6 +230,47 @@ EOT; array( (object) array( 'foo', 'bar', 'baz' ), false ), ); } + + /** + * @ticket 43619 + */ + function test_is_iterable_availability() { + $this->assertTrue( function_exists( 'is_iterable' ) ); + } + + /** + * Test is_iterable() polyfill. + * + * @ticket 43619 + * + * @dataProvider iterable_variable_test_data + */ + function test_is_iterable_functionality( $variable, $is_iterable ) { + $this->assertEquals( is_iterable( $variable ), $is_iterable ); + } + + /** + * Data provider for test_is_iterable_functionality(). + * + * @ticket 43619 + * + * @return array { + * @type array { + * @type mixed $variable Variable to check. + * @type bool $is_iterable The expected return value of PHP 7.1 is_iterable() function. + * } + * } + */ + public function iterable_variable_test_data() { + return array( + array( array(), true ), + array( array( 1, 2, 3 ), true ), + array( new ArrayIterator( array( 1, 2, 3 ) ), true ), + array( 1, false ), + array( 3.14, false ), + array( new stdClass(), false ), + ); + } } /* used in test_mb_substr_phpcore */