1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Maztech\HttpClients; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use InvalidArgumentException; |
7
|
|
|
use Exception; |
8
|
|
|
|
9
|
|
|
class HttpClientsFactory |
10
|
|
|
{ |
11
|
|
|
private function __construct() |
12
|
|
|
{ |
13
|
|
|
// a factory constructor should never be invoked |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* HTTP client generation. |
18
|
|
|
* |
19
|
|
|
* @param InstagramHttpClientInterface|Client|string|null $handler |
20
|
|
|
* |
21
|
|
|
* @throws Exception If the cURL extension or the Guzzle client aren't available (if required). |
22
|
|
|
* @throws InvalidArgumentException If the http client handler isn't "curl", "stream", "guzzle", or an instance of Instagram\HttpClients\InstagramHttpClientInterface. |
23
|
|
|
* |
24
|
|
|
* @return InstagramHttpClientInterface |
25
|
|
|
*/ |
26
|
|
|
public static function createHttpClient($handler) |
27
|
|
|
{ |
28
|
|
|
if (!$handler) { |
29
|
|
|
return self::detectDefaultClient(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if ($handler instanceof InstagramHttpClientInterface) { |
33
|
|
|
return $handler; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if ('stream' === $handler) { |
37
|
|
|
return new InstagramStreamHttpClient(); |
38
|
|
|
} |
39
|
|
|
if ('curl' === $handler) { |
40
|
|
|
if (!extension_loaded('curl')) { |
41
|
|
|
throw new Exception('The cURL extension must be loaded in order to use the "curl" handler.'); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return new InstagramCurlHttpClient(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
if ('guzzle' === $handler && !class_exists('GuzzleHttp\Client')) { |
48
|
|
|
throw new Exception('The Guzzle HTTP client must be included in order to use the "guzzle" handler.'); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if ($handler instanceof Client) { |
52
|
|
|
return new InstagramGuzzleHttpClient($handler); |
53
|
|
|
} |
54
|
|
|
if ('guzzle' === $handler) { |
55
|
|
|
return new InstagramGuzzleHttpClient(); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
throw new InvalidArgumentException('The http client handler must be set to "curl", "stream", "guzzle", be an instance of GuzzleHttp\Client or an instance of Instagram\HttpClients\InstagramHttpClientInterface'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Detect default HTTP client. |
63
|
|
|
* |
64
|
|
|
* @return InstagramHttpClientInterface |
65
|
|
|
*/ |
66
|
|
|
private static function detectDefaultClient() |
67
|
|
|
{ |
68
|
|
|
if (extension_loaded('curl')) { |
69
|
|
|
return new InstagramCurlHttpClient(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if (class_exists('GuzzleHttp\Client')) { |
73
|
|
|
return new InstagramGuzzleHttpClient(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return new InstagramStreamHttpClient(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|