1 | <?php |
||
24 | class GoogleUrl |
||
25 | { |
||
26 | /** |
||
27 | * |
||
28 | */ |
||
29 | const BASE_URL = 'https://www.googleapis.com/urlshortener/v1/url'; |
||
30 | |||
31 | /** |
||
32 | * @var \GuzzleHttp\ClientInterface |
||
33 | */ |
||
34 | private $http; |
||
35 | |||
36 | /** |
||
37 | * @var |
||
38 | */ |
||
39 | private $key; |
||
40 | |||
41 | /** |
||
42 | * GoogleUrl constructor. |
||
43 | * @param $key |
||
44 | * @param \GuzzleHttp\ClientInterface|null $httpClient |
||
45 | */ |
||
46 | 15 | public function __construct($key, \GuzzleHttp\ClientInterface $httpClient = null) |
|
55 | |||
56 | /** |
||
57 | * @param $key |
||
58 | */ |
||
59 | 15 | public function setKey($key) |
|
63 | |||
64 | /** |
||
65 | * @param ActionInterface $method |
||
66 | * @return \GuzzleHttp\Message\Request|\GuzzleHttp\Message\RequestInterface |
||
67 | */ |
||
68 | 15 | private function createRequest(ActionInterface $method) |
|
80 | |||
81 | /** |
||
82 | * @param ActionInterface $method |
||
83 | * @return mixed |
||
84 | */ |
||
85 | 12 | private function execute(ActionInterface $method) |
|
86 | { |
||
87 | 12 | $response = $this->http->send($this->createRequest($method)); |
|
88 | |||
89 | 12 | if ($response->getStatusCode() != 200) { |
|
90 | 12 | $json = json_decode($response->getBody()->getContents()); |
|
91 | 9 | if (isset($json->error->errors[0])) { |
|
92 | 6 | $this->assertInvalidKey($json); |
|
93 | 3 | $this->assertInvalidValue($json); |
|
94 | } // @codeCoverageIgnore |
||
95 | 3 | throw new GoogleUrlException($response->getBody()); |
|
96 | } |
||
97 | |||
98 | 3 | return $method->processResponse($response); |
|
99 | } |
||
100 | |||
101 | /** |
||
102 | * @param $response |
||
103 | * @throws InvalidKeyException |
||
104 | */ |
||
105 | 6 | private function assertInvalidKey($response) |
|
111 | |||
112 | /** |
||
113 | * @param $response |
||
114 | */ |
||
115 | 3 | private function assertInvalidValue($response) |
|
116 | { |
||
117 | if ( |
||
118 | 3 | $response->error->errors[0]->message == 'Invalid Value' && |
|
119 | 3 | $response->error->errors[0]->locationType == 'parameter' |
|
120 | 3 | ) { |
|
121 | 3 | throw new InvalidValueException($response->error->errors[0]->location); |
|
122 | } |
||
123 | } // @codeCoverageIgnore |
||
124 | |||
125 | /** |
||
126 | * @param $longUrl |
||
127 | * @return UrlResource |
||
128 | */ |
||
129 | 12 | public function shorten($longUrl) |
|
133 | } |
||
134 |