-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientFactory.php
More file actions
86 lines (73 loc) · 2.44 KB
/
ClientFactory.php
File metadata and controls
86 lines (73 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <mihail@kodeart.com>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*
*/
namespace Koded\Http\Client;
use Koded\Http\Interfaces\{ClientType, HttpMethod, HttpRequestClient};
use InvalidArgumentException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class ClientFactory
{
private ClientType $clientType;
public function __construct(ClientType $type = ClientType::CURL)
{
$this->clientType = $type;
}
public function get($uri, array $headers = []): HttpRequestClient
{
return $this->new(HttpMethod::GET, $uri, null, $headers);
}
public function post($uri, $body, array $headers = []): HttpRequestClient
{
return $this->new(HttpMethod::POST, $uri, $body, $headers);
}
public function put($uri, $body, array $headers = []): HttpRequestClient
{
return $this->new(HttpMethod::PUT, $uri, $body, $headers);
}
public function patch($uri, $body, array $headers = []): HttpRequestClient
{
return $this->new(HttpMethod::PATCH, $uri, $body, $headers);
}
public function delete($uri, array $headers = []): HttpRequestClient
{
return $this->new(HttpMethod::DELETE, $uri, null, $headers);
}
public function head($uri, array $headers = []): HttpRequestClient
{
return $this->new(HttpMethod::HEAD, $uri, null, $headers)->maxRedirects(0);
}
public function client(): HttpRequestClient
{
return $this->new(HttpMethod::HEAD, '');
}
// FIXME: implement this?
// public function sendRequest(RequestInterface $request): ResponseInterface
// {
// return $this->new(
// HttpMethod::tryFrom($request->getMethod()),
// $request->getUri(),
// $request->getBody()->getContents(),
// $request->getHeaders()
// )->read();
// }
protected function new(
HttpMethod $method,
$uri,
$body = null,
array $headers = []): HttpRequestClient
{
return match ($this->clientType) {
ClientType::CURL => new CurlClient($method, $uri, $body, $headers),
ClientType::PHP => new PhpClient($method, $uri, $body, $headers),
default => throw new InvalidArgumentException("{$this->clientType} is not a valid HTTP client"),
};
}
}