1: <?php
2: namespace ShippoClient\Http;
3:
4: use Guzzle\Http\Client;
5: use Guzzle\Http\Message\RequestInterface;
6: use Guzzle\Http\Exception\ClientErrorResponseException as GuzzleClientErrorException;
7: use Guzzle\Http\Exception\ServerErrorResponseException as GuzzleServerErrorException;
8: use ShippoClient\Http\Request\MockCollection;
9: use ShippoClient\Http\Response\Exception\ClientErrorException;
10: use ShippoClient\Http\Response\Exception\ServerErrorException;
11:
12: class Request
13: {
14: const BASE_URI = 'https://api.goshippo.com/v1/';
15:
16: private $delegated;
17: private $mockContainer;
18:
19: public function __construct($accessToken)
20: {
21: $this->delegated = new Client(static::BASE_URI, [
22: 'request.options' => [
23: 'headers' => ['Authorization' => 'ShippoToken ' . $accessToken],
24: ]
25: ]);
26: $this->mockContainer = MockCollection::getInstance();
27: }
28:
29: public function post($endPoint, $body = [])
30: {
31: $this->mockFilter($endPoint);
32: $request = $this->delegated->post($endPoint, null, $body);
33: $guzzleResponse = $this->sendWithCheck($request);
34:
35: return $guzzleResponse->json();
36: }
37:
38: public function postWithJsonBody($endPoint, $body = [])
39: {
40: $this->mockFilter($endPoint);
41: $request = $this->delegated->post($endPoint, ['Content-Type' => 'application/json']);
42: $request->setBody(json_encode($body));
43: $guzzleResponse = $this->sendWithCheck($request);
44:
45: return $guzzleResponse->json();
46: }
47:
48: public function get($endPoint, $parameter = [])
49: {
50: $this->mockFilter($endPoint);
51: $queryString = http_build_query($parameter);
52: $request = $this->delegated->get("$endPoint?$queryString");
53: $guzzleResponse = $this->sendWithCheck($request);
54:
55: return $guzzleResponse->json();
56: }
57:
58: public function setDefaultOption($keyOrPath, $value)
59: {
60: $this->delegated->setDefaultOption($keyOrPath, $value);
61: }
62:
63: private function sendWithCheck(RequestInterface $request)
64: {
65: try {
66: return $request->send();
67: } catch (GuzzleClientErrorException $e) {
68: throw new ClientErrorException(
69: $e->getMessage(),
70: $e->getResponse()->getStatusCode(),
71: explode("\r\n", $e->getRequest()->__toString()),
72: explode("\r\n", $e->getResponse()->__toString())
73: );
74: } catch (GuzzleServerErrorException $e) {
75: throw new ServerErrorException(
76: $e->getMessage(),
77: $e->getResponse()->getStatusCode(),
78: explode("\r\n", $e->getRequest()->__toString()),
79: explode("\r\n", $e->getResponse()->__toString())
80: );
81: }
82: }
83:
84: 85: 86: 87: 88:
89: private function mockFilter($endPoint)
90: {
91: if ($this->mockContainer->has($endPoint)) {
92: $this->delegated->addSubscriber($this->mockContainer->getMockResponse($endPoint));
93: $this->mockContainer->clear();
94: }
95: }
96: }
97: