From 818a0f1ccf5e7adff74aaa3337fbedfa488a90cb Mon Sep 17 00:00:00 2001 From: Aaron Jorbin Date: Wed, 24 Jan 2018 01:20:24 +0000 Subject: [PATCH] Query: Fix warning on counting non countable Adds tests to continue the behavior for both null and strings. See https://wiki.php.net/rfc/counting_non_countables for information on the PHP change. Fixes #42860. Props janak007 and ayeshrajans for initial patches. git-svn-id: https://develop.svn.wordpress.org/trunk@42581 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-query.php | 10 +++++++- tests/phpunit/tests/post/query.php | 41 ++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-query.php b/src/wp-includes/class-wp-query.php index f70c4aee1a..930e33d883 100644 --- a/src/wp-includes/class-wp-query.php +++ b/src/wp-includes/class-wp-query.php @@ -3158,7 +3158,15 @@ class WP_Query { */ $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) ); } else { - $this->found_posts = count( $this->posts ); + if ( is_array( $this->posts ) ) { + $this->found_posts = count( $this->posts ); + } else { + if ( null === $this->posts ) { + $this->found_posts = 0; + } else { + $this->found_posts = 1; + } + } } /** diff --git a/tests/phpunit/tests/post/query.php b/tests/phpunit/tests/post/query.php index 0e8f8499f8..122e956bbb 100644 --- a/tests/phpunit/tests/post/query.php +++ b/tests/phpunit/tests/post/query.php @@ -642,4 +642,45 @@ class Tests_Post_Query extends WP_UnitTestCase { $this->assertEquals( 2, $q->found_posts ); $this->assertEquals( 2, $q->max_num_pages ); } + + /** + * @ticket 42860 + */ + public function test_set_found_posts_fields_posts_is_string() { + $q = new WP_Query( + array( + 'post_type' => 'wptests_pt', + 'posts_per_page' => 1, + ) + ); + + $q->posts = "To life, to life, l'chaim"; + + $methd = new \ReflectionMethod( 'WP_Query', 'set_found_posts' ); + $methd->setAccessible( true ); + $methd->invoke( $q, array( 'no_found_rows' => false ), array() ); + + $this->assertEquals( 1, $q->found_posts ); + } + + /** + * @ticket 42860 + */ + public function test_set_found_posts_fields_posts_is_null() { + $q = new WP_Query( + array( + 'post_type' => 'wptests_pt', + 'posts_per_page' => 1, + ) + ); + + $q->posts = null; + + $methd = new \ReflectionMethod( 'WP_Query', 'set_found_posts' ); + $methd->setAccessible( true ); + $methd->invoke( $q, array( 'no_found_rows' => false ), array() ); + + $this->assertEquals( 0, $q->found_posts ); + } + }