Skip to content

Commit

Permalink
Merge pull request #9 from zlobec/master
Browse files Browse the repository at this point in the history
update to the new API endpoint, added hard limits to API parameters
  • Loading branch information
Fl0Cri authored May 27, 2021
2 parents 854f38d + af6a928 commit 7fde48f
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions components/SearchResults.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@
class SearchResults extends ComponentBase
{

const APIURL = 'https://www.googleapis.com/customsearch/v1';
const APIURL = 'https://customsearch.googleapis.com/customsearch/v1';

var $search;
var $currentPage;
var $resultPerPage;
var $maxResults;

public function componentDetails()
{
Expand Down Expand Up @@ -47,6 +48,8 @@ public function defineProperties()
'default' => 10,
'type' => 'string',
'required' => true,
'validationPattern' => '^([0-9]|10)$',
'validationMessage' => 'Maximum results per page is limited to 10 by Google API',
],
'sendReferer' => [
'title' => 'Send HTTP Referer',
Expand All @@ -64,7 +67,10 @@ public function onRun()
{
$this->search = get('q');
$this->currentPage = (int) get('page', 1);
$this->resultPerPage = $this->property('resultPerPage');
// maximum per page results allowed from Google API
$this->resultPerPage = min(10, $this->property('resultPerPage'));
// maximum results allowed from Google API
$this->maxResults = 100;

$http = $this->buildRequest();
$response = json_decode($http->send());
Expand All @@ -77,8 +83,11 @@ public function onRun()
}
elseif ($response->searchInformation->totalResults)
{
$this->page['totalResults'] = $response->searchInformation->totalResults;
$result = new LengthAwarePaginator($response->items, $response->searchInformation->totalResults, $this->resultPerPage, $this->currentPage);
// set the hard limit to all results and pagination
$totalResponseResults = min($this->maxResults, $response->searchInformation->totalResults);

$this->page['totalResults'] = $totalResponseResults;
$result = new LengthAwarePaginator($response->items, $totalResponseResults, $this->resultPerPage, $this->currentPage);
$result->setPath($this->page['baseFileName']);
$result->appends('q', $this->search);
$this->page['results'] = $result;
Expand All @@ -96,7 +105,7 @@ private function buildAPIUrl()
$apiKey = $this->property('apikey');
$cx = $this->property('cx');

$start = ($this->currentPage - 1) * $this->resultPerPage + 1;
$start = min($this->maxResults, ($this->currentPage - 1) * $this->resultPerPage + 1);
$params = array('key' => $apiKey,
'cx' => $cx,
'start' => $start,
Expand Down

0 comments on commit 7fde48f

Please sign in to comment.