brucepc /
sum-up
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * Created by PhpStorm. |
||
| 4 | * User: brucepc |
||
| 5 | * Date: 26/02/18 |
||
| 6 | * Time: 13:52 |
||
| 7 | */ |
||
| 8 | |||
| 9 | namespace BPCI\SumUp\Traits; |
||
| 10 | |||
| 11 | use BPCI\SumUp\OAuth\AuthenticationHelper; |
||
| 12 | use BPCI\SumUp\SumUp; |
||
| 13 | use BPCI\SumUp\SumUpClientInterface; |
||
| 14 | use GuzzleHttp\Exception\BadResponseException; |
||
| 15 | use GuzzleHttp\Exception\ConnectException; |
||
| 16 | use GuzzleHttp\Exception\RequestException; |
||
| 17 | |||
| 18 | /** |
||
| 19 | * Trait Client |
||
| 20 | * @package BPCI\SumUp\Traits |
||
| 21 | */ |
||
| 22 | trait Client |
||
| 23 | { |
||
| 24 | /** |
||
| 25 | * @param string $action |
||
| 26 | * @param mixed $object |
||
| 27 | * @param string $endpoint |
||
| 28 | * @return bool|null |
||
| 29 | * @throws BadResponseException |
||
| 30 | * @throws ConnectException |
||
| 31 | */ |
||
| 32 | 5 | public function request(string $action, $object = null, string $endpoint = null):? bool |
|
| 33 | { |
||
| 34 | /** @var SumUpClientInterface $this */ |
||
| 35 | |||
| 36 | 5 | if (!$this instanceof SumUpClientInterface) { |
|
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 37 | throw new \RuntimeException('This object doesn\'t implements the SumUpClientInterface.'); |
||
| 38 | } |
||
| 39 | |||
| 40 | 5 | $scopes = $this::getScopes(); |
|
| 41 | |||
| 42 | 5 | $accessToken = AuthenticationHelper::getValidToken($this->getContext(), $this->getToken(), $scopes); |
|
| 43 | |||
| 44 | 5 | $client = SumUp::getClient($this->getOptions()); |
|
| 45 | 5 | $options = AuthenticationHelper::getOAuthHeader($accessToken); |
|
| 46 | 5 | if ($object !== null) { |
|
| 47 | 4 | $options['form_params'] = $this::getBody($object, $action); |
|
| 48 | } |
||
| 49 | |||
| 50 | 5 | $uri = $endpoint??$this->getEndPoint(); |
|
| 51 | |||
| 52 | try { |
||
| 53 | /** @var \GuzzleHttp\Psr7\Response $response */ |
||
| 54 | 5 | $response = $client->{$action}($uri, $options); |
|
| 55 | 4 | } catch (RequestException $e) { |
|
| 56 | 4 | $response = $e->getResponse(); |
|
| 57 | } |
||
| 58 | 5 | $this->setLastResponse($response); |
|
| 59 | 5 | $statusCode = $response->getStatusCode(); |
|
| 60 | 5 | if ($statusCode < 300 && $statusCode > 199) { |
|
| 61 | 5 | $data = \GuzzleHttp\json_decode($response->getBody(), true); |
|
| 62 | 5 | if ($object instanceof PropertyHandlerInterface) { |
|
| 63 | 2 | $object->fillProperties($data); |
|
| 64 | } |
||
| 65 | |||
| 66 | 5 | return true; |
|
| 67 | } |
||
| 68 | |||
| 69 | 4 | return false; |
|
| 70 | } |
||
| 71 | } |
||
| 72 |