Skip to content

Commit

Permalink
Bugfixes, v5 API by default, updated documentation, cosmetic changes. (
Browse files Browse the repository at this point in the history
…#13)

* Autoload for those not using Composer. Refactoring. v5 is now default API for search.

Signed-off-by: Carlos Escribano <[email protected]>

* Results and bugfixes

Signed-off-by: Carlos Escribano <[email protected]>

* Small cosmetic changes

Signed-off-by: Carlos Escribano <[email protected]>

* README

Signed-off-by: Carlos Escribano <[email protected]>

* sc

Signed-off-by: Carlos Escribano <[email protected]>
  • Loading branch information
carlosescri authored and JoeZ99 committed Oct 26, 2016
1 parent 69fd397 commit 7e9cc42
Show file tree
Hide file tree
Showing 14 changed files with 1,320 additions and 1,368 deletions.
907 changes: 423 additions & 484 deletions README.md

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions autoload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
spl_autoload_register('autoload_doofinder_classes');

function autoload_doofinder_classes($className) {
$libraryPrefix = 'Doofinder\\Api\\';
$libraryDirectory = __DIR__ . '/src/';

$len = strlen($libraryPrefix);

// Binary safe comparison of $len first characters
if (strncmp($libraryPrefix, $className, $len) !== 0) {
return;
}

$classPath = str_replace('\\', '/', substr($className, $len)) . '.php';
$file = $libraryDirectory . $classPath;

if (file_exists($file)) {
require $file;
}
}
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "doofinder/doofinder",
"type": "library",
"description": "Doofinder php API Client",
"keywords": ["search","api", "doofinder"],
"description": "Doofinder PHP API Client",
"keywords": ["search", "api", "doofinder"],
"homepage": "https://github.com/doofinder/php-doofinder",
"license": "MIT",
"authors": [
Expand Down
20 changes: 13 additions & 7 deletions src/Management/AggregatesIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Doofinder\Api\Management;

use Doofinder\Api\Management\SearchEngine;
use Doofinder\Api\Management\ItemsResultSet;

class AggregatesIterator extends ItemsResultSet {
Expand All @@ -17,36 +18,41 @@ class AggregatesIterator extends ItemsResultSet {
* @param DateTime $from_date . Starting date of the period. Default: 15 days ago
* @param DateTime $to_date. Ending date of the period. Default: today.
*/
function __construct($searchEngine, $from_date=null, $to_date=null){
public function __construct(SearchEngine $searchEngine, $from_date = null, $to_date = null){
$this->last_page = 0;
if($from_date!=null){

if (!is_null($from_date)) {
$this->searchParams['from'] = $from_date->format("Ymd");
}
if($to_date!=null){
if (!is_null($to_date)) {
$this->searchParams['to'] = $to_date->format("Ymd");
}

parent::__construct($searchEngine);
}

protected function fetchResultsAndTotal(){
$params = $this->last_page > 0 ? array("page"=>$this->last_page + 1) : array();
protected function fetchResultsAndTotal() {
$params = $this->last_page > 0 ? array("page" => $this->last_page + 1) : array();

try{
$apiResponse = $this->searchEngine->dma->managementApiCall(
$apiResponse = $this->searchEngine->client->managementApiCall(
'GET',
"{$this->searchEngine->hashid}/stats",
array_merge($params, $this->searchParams)
);

$this->resultsPage = $apiResponse['response']['aggregates'];
$this->total = $apiResponse['response']['count'];
$this->last_page++;
$this->currentItem = each($this->resultsPage);
} catch (NotFound $nfe) {
$this->resultsPage = array();
}

reset($this->resultsPage);
}

function rewind(){
public function rewind() {
$this->last_page = 0;
parent::rewind();
}
Expand Down
35 changes: 19 additions & 16 deletions src/Management/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@ class Client
private $token = null;
private $baseManagementUrl = null;

function __construct($apiKey, $local = false){
public function __construct($apiKey, $local = false) {
$this->apiKey = $apiKey;
$clusterToken = explode('-', $apiKey);
$this->clusterRegion = $clusterToken[0];
$this->token = $clusterToken[1];

if ($local === true){
$this->baseManagementUrl = self::LOCAL_API_ENDPOINT;
} else {
Expand All @@ -59,13 +60,16 @@ function __construct($apiKey, $local = false){
* @param array $data If any, body request parameters
* @return array Array with both status code and response .
*/
function managementApiCall($method='GET', $entryPoint='', $params=null, $data=null){
$headers = array('Authorization: Token '.$this->token, // for Auth
'Content-Type: application/json',
'Expect:'); // Fixes the HTTP/1.1 417 Expectation Failed
public function managementApiCall($method = 'GET', $entryPoint = '', $params = null, $data = null) {
$headers = array(
'Authorization: Token ' . $this->token,
'Content-Type: application/json',
'Expect:', // Fixes the HTTP/1.1 417 Expectation Failed error
);

$url = $this->baseManagementUrl.'/'.$entryPoint;
if (is_array($params) && sizeof($params) > 0){

if (is_array($params) && sizeof($params) > 0) {
$url .= '?'.http_build_query($params);
}

Expand All @@ -75,7 +79,7 @@ function managementApiCall($method='GET', $entryPoint='', $params=null, $data=nu
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // Tell curl to return the response
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); // Adding request headers

if (in_array($method, array('POST', 'PUT'))){
if (in_array($method, array('POST', 'PUT'))) {
curl_setopt($session, CURLOPT_POSTFIELDS, $data);
}

Expand All @@ -86,20 +90,20 @@ function managementApiCall($method='GET', $entryPoint='', $params=null, $data=nu
$error = Utils::handleErrors($httpCode, $response);

if ($error) {
throw $error;
throw $error;
}

$return = array('statusCode' => $httpCode);
$return['response'] = ($decoded = json_decode($response, true)) ? $decoded : $response;

return $return;
return array(
'statusCode' => $httpCode,
'response' => ($decoded = json_decode($response, true)) ? $decoded : $response,
);
}

/**
* To get info on all possible api entry points
* @return array An assoc. array with the different entry points
*/
function getApiRoot(){
public function getApiRoot() {
$response = $this->managementApiCall();
return $response['response'];
}
Expand All @@ -108,16 +112,15 @@ function getApiRoot(){
* Obtain a list of SearchEngines objects, ready to interact with the API
* @return array list of searchEngines objects
*/
function getSearchEngines(){
public function getSearchEngines(){
$searchEngines = array();
$apiRoot = $this->getApiRoot();
unset($apiRoot['searchengines']);

foreach($apiRoot as $hashid => $props){
foreach ($apiRoot as $hashid => $props) {
$searchEngines[] = new SearchEngine($this, $hashid, $props['name']);
}

return $searchEngines;
}

}
66 changes: 33 additions & 33 deletions src/Management/Errors/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,43 +11,43 @@


class Utils {
public static function handleErrors($statusCode, $response) {
switch($statusCode)
{
case 403:
return new NotAllowed("The user does not have permissions to perform this operation: ".Utils::readError($response));
case 401:
return new NotAllowed("The user hasn't provided valid authorization: ".Utils::readError($response));
case 404:
return new NotFound("Not Found: ".Utils::readError($response));
case 409: // trying to post with an already used id
return new BadRequest("Request conflict: ".Utils::readError($response));
case 429:
if (stripos($response, 'throttled')) {
return new ThrottledResponse(Utils::readError($response));
} else {
return new QuotaExhausted("The query quota has been reached. No more queries can be requested right now");
}
}

if ($statusCode >= 500) {
return new WrongResponse("Server error: ".Utils::readError($response));
public static function handleErrors($statusCode, $response) {
switch ($statusCode) {
case 403:
return new NotAllowed("The user does not have permissions to perform this operation: ".Utils::readError($response));
case 401:
return new NotAllowed("The user hasn't provided valid authorization: ".Utils::readError($response));
case 404:
return new NotFound("Not Found: ".Utils::readError($response));
case 409: // trying to post with an already used id
return new BadRequest("Request conflict: ".Utils::readError($response));
case 429:
if (stripos($response, 'throttled')) {
return new ThrottledResponse(Utils::readError($response));
} else {
return new QuotaExhausted("The query quota has been reached. No more queries can be requested right now");
}
}

if ($statusCode >= 400) {
return new BadRequest("The client made a bad request: ".Utils::readError($response));
}
return false;
if ($statusCode >= 500) {
return new WrongResponse("Server error: ".Utils::readError($response));
}

private static function readError($response) {
$error = json_decode($response, true);
$error = $error['detail'];
if (!isset($error)) {
$error = $response;
}
return $error;
if ($statusCode >= 400) {
return new BadRequest("The client made a bad request: ".Utils::readError($response));
}

return false;
}

private static function readError($response) {
$error = json_decode($response, true);
$error = $error['detail'];

if (!isset($error)) {
$error = $response;
}

}
return $error;
}
}
30 changes: 16 additions & 14 deletions src/Management/ItemsResultSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace Doofinder\Api\Management;

use Doofinder\Api\Management\SearchEngine;


/**
* Helper class to iterate through the search engine's items
*
Expand All @@ -13,44 +16,43 @@ class ItemsResultSet implements \Iterator {
protected $searchEngine = null;
protected $resultsPage = null;
protected $position = 0;
protected $total = null;
protected $total = null;

function __construct($searchEngine) {
public function __construct(SearchEngine $searchEngine) {
$this->searchEngine = $searchEngine;
}

protected function fetchResultsAndTotal(){
/**
* Function to be implemented in children
*
**/
throw new Exception('Not implemented method');
/**
* To be implemented in children
*/
protected function fetchResultsAndTotal() {
throw new Exception('Not implemented.');
}

function rewind(){
public function rewind() {
$this->position = 0;
$this->total = null;
$this->resultsPage = null;
$this->fetchResultsAndTotal();
$this->currentItem = each($this->resultsPage);
}

function valid(){
public function valid() {
return $this->position < $this->total;
}

function current(){
public function current() {
return $this->currentItem['value'];
}

function key(){
public function key() {
return $this->position;
}

function next(){
public function next() {
++$this->position;
$this->currentItem = each($this->resultsPage);
if(!$this->currentItem && $this->position < $this->total){
if (!$this->currentItem && $this->position < $this->total) {
$this->fetchResultsAndTotal();
$this->currentItem = each($this->resultsPage);
}
Expand Down
20 changes: 11 additions & 9 deletions src/Management/ScrollIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Doofinder\Api\Management;

use Doofinder\Api\Management\SearchEngine;
use \Doofinder\Api\Management\ItemsResultSet;

/**
Expand All @@ -12,14 +13,14 @@
class ScrollIterator extends ItemsResultSet {

private $scrollId = null;
private $dType = null;
private $datatype = null;

/**
* @param SearchEngine $searchEngine
* @param string $dType type of item . i.e. 'product'
* @param string $datatype type of item . i.e. 'product'
*/
function __construct($searchEngine, $dType){
$this->dType = $dType;
public function __construct(SearchEngine $searchEngine, $datatype){
$this->datatype = $datatype;
parent::__construct($searchEngine);
}

Expand All @@ -28,20 +29,21 @@ function __construct($searchEngine, $dType){
*
*/
protected function fetchResultsAndTotal(){
$params = $this->scrollId ? array("scroll_id" => $this->scrollId) : null;
$apiResults = $this->searchEngine->dma->managementApiCall(
$apiResults = $this->searchEngine->client->managementApiCall(
'GET',
"{$this->searchEngine->hashid}/items/{$this->dType}",
$params
"{$this->searchEngine->hashid}/items/{$this->datatype}",
($this->scrollId ? array("scroll_id" => $this->scrollId) : null)
);

$this->total = $apiResults['response']['count'];
$this->scrollId = $apiResults['response']['scroll_id'];
$this->resultsPage = $apiResults['response']['results'];
$this->currentItem = each($this->resultsPage);

reset($this->resultsPage);
}

function rewind(){
public function rewind(){
$this->scrollId = null;
parent::rewind();
}
Expand Down
Loading

0 comments on commit 7e9cc42

Please sign in to comment.