Complex classes like Client often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Client, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 25 | class Client implements ClientInterface |
||
| 26 | { |
||
| 27 | /** @var array Default request options */ |
||
| 28 | private $config; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * Clients accept an array of constructor parameters. |
||
| 32 | * |
||
| 33 | * Here's an example of creating a client using a base_uri and an array of |
||
| 34 | * default request options to apply to each request: |
||
| 35 | * |
||
| 36 | * $client = new Client([ |
||
| 37 | * 'base_uri' => 'http://www.foo.com/1.0/', |
||
| 38 | * 'timeout' => 0, |
||
| 39 | * 'allow_redirects' => false, |
||
| 40 | * 'proxy' => '192.168.16.1:10' |
||
| 41 | * ]); |
||
| 42 | * |
||
| 43 | * Client configuration settings include the following options: |
||
| 44 | * |
||
| 45 | * - handler: (callable) Function that transfers HTTP requests over the |
||
| 46 | * wire. The function is called with a Psr7\Http\Message\RequestInterface |
||
| 47 | * and array of transfer options, and must return a |
||
| 48 | * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a |
||
| 49 | * Psr7\Http\Message\ResponseInterface on success. "handler" is a |
||
| 50 | * constructor only option that cannot be overridden in per/request |
||
| 51 | * options. If no handler is provided, a default handler will be created |
||
| 52 | * that enables all of the request options below by attaching all of the |
||
| 53 | * default middleware to the handler. |
||
| 54 | * - base_uri: (string|UriInterface) Base URI of the client that is merged |
||
| 55 | * into relative URIs. Can be a string or instance of UriInterface. |
||
| 56 | * - **: any request option |
||
| 57 | * |
||
| 58 | * @param array $config Client configuration settings. |
||
| 59 | * |
||
| 60 | * @see \GuzzleHttp\RequestOptions for a list of available request options. |
||
| 61 | */ |
||
| 62 | public function __construct(array $config = []) |
||
| 63 | { |
||
| 64 | if (!isset($config['handler'])) { |
||
| 65 | $config['handler'] = HandlerStack::create(); |
||
| 66 | } |
||
| 67 | |||
| 68 | // Convert the base_uri to a UriInterface |
||
| 69 | if (isset($config['base_uri'])) { |
||
| 70 | $config['base_uri'] = Psr7\uri_for($config['base_uri']); |
||
| 71 | } |
||
| 72 | |||
| 73 | $this->configureDefaults($config); |
||
| 74 | } |
||
| 75 | |||
| 76 | public function __call($method, $args) |
||
| 77 | { |
||
| 78 | if (count($args) < 1) { |
||
| 79 | throw new \InvalidArgumentException('Magic request methods require a URI and optional options array'); |
||
| 80 | } |
||
| 81 | |||
| 82 | $uri = $args[0]; |
||
| 83 | $opts = isset($args[1]) ? $args[1] : []; |
||
| 84 | |||
| 85 | return substr($method, -5) === 'Async' |
||
| 86 | ? $this->requestAsync(substr($method, 0, -5), $uri, $opts) |
||
| 87 | : $this->request($method, $uri, $opts); |
||
| 88 | } |
||
| 89 | |||
| 90 | public function sendAsync(RequestInterface $request, array $options = []) |
||
| 91 | { |
||
| 92 | // Merge the base URI into the request URI if needed. |
||
| 93 | $options = $this->prepareDefaults($options); |
||
| 94 | |||
| 95 | return $this->transfer( |
||
| 96 | $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), |
||
| 97 | $options |
||
| 98 | ); |
||
| 99 | } |
||
| 100 | |||
| 101 | public function send(RequestInterface $request, array $options = []) |
||
| 102 | { |
||
| 103 | $options[RequestOptions::SYNCHRONOUS] = true; |
||
| 104 | return $this->sendAsync($request, $options)->wait(); |
||
| 105 | } |
||
| 106 | |||
| 107 | public function requestAsync($method, $uri = '', array $options = []) |
||
| 108 | { |
||
| 109 | $options = $this->prepareDefaults($options); |
||
| 110 | // Remove request modifying parameter because it can be done up-front. |
||
| 111 | $headers = isset($options['headers']) ? $options['headers'] : []; |
||
| 112 | $body = isset($options['body']) ? $options['body'] : null; |
||
| 113 | $version = isset($options['version']) ? $options['version'] : '1.1'; |
||
| 114 | // Merge the URI into the base URI. |
||
| 115 | $uri = $this->buildUri($uri, $options); |
||
| 116 | if (is_array($body)) { |
||
| 117 | $this->invalidBody(); |
||
| 118 | } |
||
| 119 | $request = new Psr7\Request($method, $uri, $headers, $body, $version); |
||
| 120 | // Remove the option so that they are not doubly-applied. |
||
| 121 | unset($options['headers'], $options['body'], $options['version']); |
||
| 122 | |||
| 123 | return $this->transfer($request, $options); |
||
| 124 | } |
||
| 125 | |||
| 126 | public function request($method, $uri = '', array $options = []) |
||
| 127 | { |
||
| 128 | $options[RequestOptions::SYNCHRONOUS] = true; |
||
| 129 | return $this->requestAsync($method, $uri, $options)->wait(); |
||
| 130 | } |
||
| 131 | |||
| 132 | public function getConfig($option = null) |
||
| 133 | { |
||
| 134 | return $option === null |
||
| 135 | ? $this->config |
||
| 136 | : (isset($this->config[$option]) ? $this->config[$option] : null); |
||
| 137 | } |
||
| 138 | |||
| 139 | private function buildUri($uri, array $config) |
||
| 140 | { |
||
| 141 | // for BC we accept null which would otherwise fail in uri_for |
||
| 142 | $uri = Psr7\uri_for($uri === null ? '' : $uri); |
||
| 143 | |||
| 144 | if (isset($config['base_uri'])) { |
||
| 145 | $uri = Psr7\UriResolver::resolve(Psr7\uri_for($config['base_uri']), $uri); |
||
| 146 | } |
||
| 147 | |||
| 148 | return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; |
||
| 149 | } |
||
| 150 | |||
| 151 | /** |
||
| 152 | * Configures the default options for a client. |
||
| 153 | * |
||
| 154 | * @param array $config |
||
| 155 | */ |
||
| 156 | private function configureDefaults(array $config) |
||
| 157 | { |
||
| 158 | $defaults = [ |
||
| 159 | 'allow_redirects' => RedirectMiddleware::$defaultSettings, |
||
| 160 | 'http_errors' => true, |
||
| 161 | 'decode_content' => true, |
||
| 162 | 'verify' => true, |
||
| 163 | 'cookies' => false |
||
| 164 | ]; |
||
| 165 | |||
| 166 | // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. |
||
| 167 | |||
| 168 | // We can only trust the HTTP_PROXY environment variable in a CLI |
||
| 169 | // process due to the fact that PHP has no reliable mechanism to |
||
| 170 | // get environment variables that start with "HTTP_". |
||
| 171 | if (php_sapi_name() == 'cli' && getenv('HTTP_PROXY')) { |
||
| 172 | $defaults['proxy']['http'] = getenv('HTTP_PROXY'); |
||
| 173 | } |
||
| 174 | |||
| 175 | if ($proxy = getenv('HTTPS_PROXY')) { |
||
| 176 | $defaults['proxy']['https'] = $proxy; |
||
| 177 | } |
||
| 178 | |||
| 179 | if ($noProxy = getenv('NO_PROXY')) { |
||
| 180 | $cleanedNoProxy = str_replace(' ', '', $noProxy); |
||
| 181 | $defaults['proxy']['no'] = explode(',', $cleanedNoProxy); |
||
| 182 | } |
||
| 183 | |||
| 184 | $this->config = $config + $defaults; |
||
| 185 | |||
| 186 | if (!empty($config['cookies']) && $config['cookies'] === true) { |
||
| 187 | $this->config['cookies'] = new CookieJar(); |
||
| 188 | } |
||
| 189 | |||
| 190 | // Add the default user-agent header. |
||
| 191 | if (!isset($this->config['headers'])) { |
||
| 192 | $this->config['headers'] = ['User-Agent' => default_user_agent()]; |
||
| 193 | } else { |
||
| 194 | // Add the User-Agent header if one was not already set. |
||
| 195 | foreach (array_keys($this->config['headers']) as $name) { |
||
| 196 | if (strtolower($name) === 'user-agent') { |
||
| 197 | return; |
||
| 198 | } |
||
| 199 | } |
||
| 200 | $this->config['headers']['User-Agent'] = default_user_agent(); |
||
| 201 | } |
||
| 202 | } |
||
| 203 | |||
| 204 | /** |
||
| 205 | * Merges default options into the array. |
||
| 206 | * |
||
| 207 | * @param array $options Options to modify by reference |
||
| 208 | * |
||
| 209 | * @return array |
||
| 210 | */ |
||
| 211 | private function prepareDefaults($options) |
||
| 212 | { |
||
| 213 | $defaults = $this->config; |
||
| 214 | |||
| 215 | if (!empty($defaults['headers'])) { |
||
| 216 | // Default headers are only added if they are not present. |
||
| 217 | $defaults['_conditional'] = $defaults['headers']; |
||
| 218 | unset($defaults['headers']); |
||
| 219 | } |
||
| 220 | |||
| 221 | // Special handling for headers is required as they are added as |
||
| 222 | // conditional headers and as headers passed to a request ctor. |
||
| 223 | if (array_key_exists('headers', $options)) { |
||
| 224 | // Allows default headers to be unset. |
||
| 225 | if ($options['headers'] === null) { |
||
| 226 | $defaults['_conditional'] = null; |
||
| 227 | unset($options['headers']); |
||
| 228 | } elseif (!is_array($options['headers'])) { |
||
| 229 | throw new \InvalidArgumentException('headers must be an array'); |
||
| 230 | } |
||
| 231 | } |
||
| 232 | |||
| 233 | // Shallow merge defaults underneath options. |
||
| 234 | $result = $options + $defaults; |
||
| 235 | |||
| 236 | // Remove null values. |
||
| 237 | foreach ($result as $k => $v) { |
||
| 238 | if ($v === null) { |
||
| 239 | unset($result[$k]); |
||
| 240 | } |
||
| 241 | } |
||
| 242 | |||
| 243 | return $result; |
||
| 244 | } |
||
| 245 | |||
| 246 | /** |
||
| 247 | * Transfers the given request and applies request options. |
||
| 248 | * |
||
| 249 | * The URI of the request is not modified and the request options are used |
||
| 250 | * as-is without merging in default options. |
||
| 251 | * |
||
| 252 | * @param RequestInterface $request |
||
| 253 | * @param array $options |
||
| 254 | * |
||
| 255 | * @return Promise\PromiseInterface |
||
| 256 | */ |
||
| 257 | private function transfer(RequestInterface $request, array $options) |
||
| 258 | { |
||
| 259 | // save_to -> sink |
||
| 260 | if (isset($options['save_to'])) { |
||
| 261 | $options['sink'] = $options['save_to']; |
||
| 262 | unset($options['save_to']); |
||
| 263 | } |
||
| 264 | |||
| 265 | // exceptions -> http_errors |
||
| 266 | if (isset($options['exceptions'])) { |
||
| 267 | $options['http_errors'] = $options['exceptions']; |
||
| 268 | unset($options['exceptions']); |
||
| 269 | } |
||
| 270 | |||
| 271 | $request = $this->applyOptions($request, $options); |
||
| 272 | $handler = $options['handler']; |
||
| 273 | |||
| 274 | try { |
||
| 275 | return Promise\promise_for($handler($request, $options)); |
||
| 276 | } catch (\Exception $e) { |
||
| 277 | return Promise\rejection_for($e); |
||
| 278 | } |
||
| 279 | } |
||
| 280 | |||
| 281 | /** |
||
| 282 | * Applies the array of request options to a request. |
||
| 283 | * |
||
| 284 | * @param RequestInterface $request |
||
| 285 | * @param array $options |
||
| 286 | * |
||
| 287 | * @return RequestInterface |
||
| 288 | */ |
||
| 289 | private function applyOptions(RequestInterface $request, array &$options) |
||
| 290 | { |
||
| 291 | $modify = []; |
||
| 292 | |||
| 293 | if (isset($options['form_params'])) { |
||
| 294 | if (isset($options['multipart'])) { |
||
| 295 | throw new \InvalidArgumentException('You cannot use ' |
||
| 296 | . 'form_params and multipart at the same time. Use the ' |
||
| 297 | . 'form_params option if you want to send application/' |
||
| 298 | . 'x-www-form-urlencoded requests, and the multipart ' |
||
| 299 | . 'option to send multipart/form-data requests.'); |
||
| 300 | } |
||
| 301 | $options['body'] = http_build_query($options['form_params'], '', '&'); |
||
| 302 | unset($options['form_params']); |
||
| 303 | $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; |
||
| 304 | } |
||
| 305 | |||
| 306 | if (isset($options['multipart'])) { |
||
| 307 | $options['body'] = new Psr7\MultipartStream($options['multipart']); |
||
| 308 | unset($options['multipart']); |
||
| 309 | } |
||
| 310 | |||
| 311 | if (isset($options['json'])) { |
||
| 312 | $options['body'] = \GuzzleHttp\json_encode($options['json']); |
||
| 313 | unset($options['json']); |
||
| 314 | $options['_conditional']['Content-Type'] = 'application/json'; |
||
| 315 | } |
||
| 316 | |||
| 317 | if (!empty($options['decode_content']) |
||
| 318 | && $options['decode_content'] !== true |
||
| 319 | ) { |
||
| 320 | $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; |
||
| 321 | } |
||
| 322 | |||
| 323 | if (isset($options['headers'])) { |
||
| 324 | if (isset($modify['set_headers'])) { |
||
| 325 | $modify['set_headers'] = $options['headers'] + $modify['set_headers']; |
||
| 326 | } else { |
||
| 327 | $modify['set_headers'] = $options['headers']; |
||
| 328 | } |
||
| 329 | unset($options['headers']); |
||
| 330 | } |
||
| 331 | |||
| 332 | if (isset($options['body'])) { |
||
| 333 | if (is_array($options['body'])) { |
||
| 334 | $this->invalidBody(); |
||
| 335 | } |
||
| 336 | $modify['body'] = Psr7\stream_for($options['body']); |
||
| 337 | unset($options['body']); |
||
| 338 | } |
||
| 339 | |||
| 340 | if (!empty($options['auth']) && is_array($options['auth'])) { |
||
| 341 | $value = $options['auth']; |
||
| 342 | $type = isset($value[2]) ? strtolower($value[2]) : 'basic'; |
||
| 343 | switch ($type) { |
||
| 344 | case 'basic': |
||
| 345 | $modify['set_headers']['Authorization'] = 'Basic ' |
||
| 346 | . base64_encode("$value[0]:$value[1]"); |
||
| 347 | break; |
||
| 348 | case 'digest': |
||
| 349 | // @todo: Do not rely on curl |
||
| 350 | $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; |
||
| 351 | $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]"; |
||
| 352 | break; |
||
| 353 | } |
||
| 354 | } |
||
| 355 | |||
| 356 | if (isset($options['query'])) { |
||
| 357 | $value = $options['query']; |
||
| 358 | if (is_array($value)) { |
||
| 359 | $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986); |
||
| 360 | } |
||
| 361 | if (!is_string($value)) { |
||
| 362 | throw new \InvalidArgumentException('query must be a string or array'); |
||
| 363 | } |
||
| 364 | $modify['query'] = $value; |
||
| 365 | unset($options['query']); |
||
| 366 | } |
||
| 367 | |||
| 368 | // Ensure that sink is not an invalid value. |
||
| 369 | if (isset($options['sink'])) { |
||
| 370 | // TODO: Add more sink validation? |
||
| 371 | if (is_bool($options['sink'])) { |
||
| 372 | throw new \InvalidArgumentException('sink must not be a boolean'); |
||
| 373 | } |
||
| 374 | } |
||
| 375 | |||
| 376 | $request = Psr7\modify_request($request, $modify); |
||
| 377 | if ($request->getBody() instanceof Psr7\MultipartStream) { |
||
| 378 | // Use a multipart/form-data POST if a Content-Type is not set. |
||
| 379 | $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' |
||
| 380 | . $request->getBody()->getBoundary(); |
||
| 381 | } |
||
| 382 | |||
| 383 | // Merge in conditional headers if they are not present. |
||
| 384 | if (isset($options['_conditional'])) { |
||
| 385 | // Build up the changes so it's in a single clone of the message. |
||
| 386 | $modify = []; |
||
| 387 | foreach ($options['_conditional'] as $k => $v) { |
||
| 388 | if (!$request->hasHeader($k)) { |
||
| 389 | $modify['set_headers'][$k] = $v; |
||
| 390 | } |
||
| 391 | } |
||
| 392 | $request = Psr7\modify_request($request, $modify); |
||
| 393 | // Don't pass this internal value along to middleware/handlers. |
||
| 394 | unset($options['_conditional']); |
||
| 395 | } |
||
| 396 | |||
| 397 | return $request; |
||
| 398 | } |
||
| 399 | |||
| 400 | private function invalidBody() |
||
| 401 | { |
||
| 402 | throw new \InvalidArgumentException('Passing in the "body" request ' |
||
| 403 | . 'option as an array to send a POST request has been deprecated. ' |
||
| 404 | . 'Please use the "form_params" request option to send a ' |
||
| 405 | . 'application/x-www-form-urlencoded request, or a the "multipart" ' |
||
| 406 | . 'request option to send a multipart/form-data request.'); |
||
| 407 | } |
||
| 408 | } |
||
| 409 |