Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
82.35% |
14 / 17 |
|
33.33% |
1 / 3 |
CRAP | |
0.00% |
0 / 1 |
| Client | |
82.35% |
14 / 17 |
|
33.33% |
1 / 3 |
7.27 | |
0.00% |
0 / 1 |
| readResponse | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| getCurlClient | |
83.33% |
10 / 12 |
|
0.00% |
0 / 1 |
4.07 | |||
| send | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace BO\Zmsclient\Psr7; |
| 4 | |
| 5 | use BO\Zmsclient\Exception\ClientCreationException; |
| 6 | use BO\Zmsclient\Psr17\ResponseFactory; |
| 7 | use Exception; |
| 8 | use Slim\Psr7\Factory\StreamFactory; |
| 9 | use Psr\Http\Client\ClientExceptionInterface; |
| 10 | use Psr\Http\Client\ClientInterface; |
| 11 | use Psr\Http\Message\RequestInterface; |
| 12 | use Psr\Http\Message\ResponseInterface; |
| 13 | use Symfony\Component\OptionsResolver\Exception\InvalidArgumentException; |
| 14 | |
| 15 | class Client |
| 16 | { |
| 17 | /** |
| 18 | * @var array $curlopt List of curl options like [CURLOPT_TIMEOUT => 10] |
| 19 | * defined with each component's bootstrap.php |
| 20 | */ |
| 21 | public static $curlopt = []; |
| 22 | |
| 23 | /** |
| 24 | * @param RequestInterface $request |
| 25 | * @param array $curlOptions Additional or special curl options |
| 26 | * |
| 27 | * @return ResponseInterface |
| 28 | * @throws RequestException|ClientCreationException|ClientExceptionInterface |
| 29 | */ |
| 30 | public static function readResponse(RequestInterface $request, array $curlOptions = array()): ResponseInterface |
| 31 | { |
| 32 | $client = static::getCurlClient($curlOptions); |
| 33 | |
| 34 | try { |
| 35 | return $client->sendRequest($request); |
| 36 | } catch (Exception $exception) { |
| 37 | throw new RequestException($exception->getMessage(), $request, $exception); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * @param $curlOptions |
| 43 | * @return \Http\Client\Curl\Client |
| 44 | * @throws ClientCreationException |
| 45 | */ |
| 46 | public static function getCurlClient($curlOptions): ClientInterface |
| 47 | { |
| 48 | $curlOptions = $curlOptions + static::$curlopt; |
| 49 | if (!isset($curlOptions[CURLOPT_USERAGENT])) { |
| 50 | $curlOptions[CURLOPT_USERAGENT] = |
| 51 | 'Client' . (defined("\App::IDENTIFIER") ? constant("\App::IDENTIFIER") : 'ZMS'); |
| 52 | } |
| 53 | |
| 54 | try { |
| 55 | $client = new \Http\Client\Curl\Client( |
| 56 | new ResponseFactory(), |
| 57 | new StreamFactory(), |
| 58 | $curlOptions |
| 59 | ); |
| 60 | } catch (InvalidArgumentException $exception) { |
| 61 | throw new ClientCreationException($exception->getMessage(), 0, $exception); |
| 62 | } |
| 63 | |
| 64 | return $client; |
| 65 | } |
| 66 | |
| 67 | public function send(RequestInterface $request) |
| 68 | { |
| 69 | return static::readResponse($request); |
| 70 | } |
| 71 | } |