From c61dde91e4fb2b62e49313144577c6dc1058340c Mon Sep 17 00:00:00 2001 From: Lars Vierbergen Date: Sat, 5 Oct 2013 15:09:55 +0200 Subject: [PATCH] Handle case where no results are returned When 0 results are returned, Forage returns a string "no results" instead of a properly formatted JSON string. So json_decode() returns null, and that gets passed to SearchResult. SearchResult only accepts an array as input, and throws an E_RECOVERABLE_ERROR. Http Transport now intercepts this case, and outputs a properly formatted array containing no hits or facets, and set totalHits to 0. PHP error: Catchable fatal error: Argument 1 passed to vierbergenlars\Forage\SearchResult\SearchResult::__construct() must be an array, null given, called in /var/www/bay/vendor/vierbergenlars/forage-client/lib/vierbergenlars/Forage/SearchQuery/Query.php on line 174 and defined in /var/www/bay/vendor/vierbergenlars/forage-client/lib/vierbergenlars/Forage/SearchResult/SearchResult.php on line 42 XDebug Trace: 8 0.1450 21947952 vierbergenlars\Forage\ODM\SearchQuery->execute( ) ../SearchController.php:43 9 0.1451 21947952 vierbergenlars\Forage\SearchQuery\Query->execute( ) ../SearchQuery.php:44 10 0.1490 21999232 vierbergenlars\Forage\SearchResult\SearchResult->__construct( $result_array = NULL ) ../Query.php:174 --- lib/vierbergenlars/Forage/Transport/Http.php | 8 +++++++- test/transport/http.php | 12 +++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/vierbergenlars/Forage/Transport/Http.php b/lib/vierbergenlars/Forage/Transport/Http.php index ce77f13..8a808be 100644 --- a/lib/vierbergenlars/Forage/Transport/Http.php +++ b/lib/vierbergenlars/Forage/Transport/Http.php @@ -145,7 +145,13 @@ public function search( if(curl_errno($ch)) throw new TransportException('cURL error: '.curl_error($ch), curl_errno($ch)); curl_close($ch); - + if($resp === 'no results') { + return array( + 'totalHits'=>0, + 'facets'=>array(), + 'hits'=> array(), + ); + } return json_decode($resp, true); } diff --git a/test/transport/http.php b/test/transport/http.php index 5c988e5..a9518f2 100644 --- a/test/transport/http.php +++ b/test/transport/http.php @@ -72,6 +72,17 @@ function testBasicSearch() $this->assertEqual($lolCatSearch['totalHits'], 2); } + function testSearchEmptyResultSet() + { + $search = $this->transport->search('s'); + var_dump($search); + $this->assertTrue(is_array($search)); + $this->assertEqual($search['totalHits'], 0); + $this->assertEqual($search['hits'], array()); + $this->assertEqual($search['facets'], array()); + } + + function testFieldedSearch() { $lolSearch = $this->transport->search('Lol', array('title')); @@ -131,5 +142,4 @@ function testDelete() $lolSearch = $this->transport->search('Lol'); $this->assertEqual($lolSearch['totalHits'], 2); } - }