Last active
February 3, 2020 15:07
-
-
Save saulmoralespa/7089774d628007ac496bccba523d9990 to your computer and use it in GitHub Desktop.
Traits request Elastic search laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use GuzzleHttp\Client; | |
use GuzzleHttp\Exception\RequestException; | |
trait Elastic | |
{ | |
public static function api() | |
{ | |
return new Client([ | |
'base_uri' => env('API_BASE_URL'), | |
'timeout' => 10 | |
]); | |
} | |
/** | |
* @param string $method | |
* @param string $params | |
* @throws \Exception | |
*/ | |
public static function request($method = 'GET', $params = '') | |
{ | |
try{ | |
$response = self::api()->request($method, $params); | |
$result = self::responseJson($response); | |
self::checkErrors($result); | |
return $result; | |
}catch (RequestException $exception){ | |
throw new \Exception($exception->getMessage()); | |
} | |
} | |
/** | |
* @param $response | |
* @return mixed | |
*/ | |
public static function responseJson($response) | |
{ | |
return \GuzzleHttp\json_decode( | |
$response->getBody()->getContents() | |
); | |
} | |
/** | |
* @param $results | |
* @throws \Exception | |
*/ | |
public static function checkErrors($results) | |
{ | |
global $resultEnd; | |
$resultEnd = []; | |
foreach ($results as $result) { | |
if(is_array($results)){ | |
if ($result->status !== 200) | |
$resultEnd[] = $result->error->reason; | |
}else { | |
self::checkErrors($result->responses); | |
} | |
} | |
if (!empty($resultEnd)) | |
throw new \Exception(implode(PHP_EOL, $resultEnd)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment