-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConcurrentPhp.php
58 lines (49 loc) · 1.72 KB
/
ConcurrentPhp.php
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
<?php declare(strict_types=1);
namespace Hippiemedia\Agent\Client\Async;
use Hippiemedia\Agent\Client;
use Hippiemedia\Agent\Client\Response;
use Psr\Http\Message\RequestFactoryInterface;
use Concurrent\Http\HttpClient;
use Hippiemedia\Agent\Client\Body;
use Nyholm\Psr7\Stream;
final class ConcurrentPhp implements Client
{
private $client;
private $factory;
public function __construct(HttpClient $client, RequestFactoryInterface $factory)
{
$this->client = $client;
$this->factory = $factory;
}
public function __invoke(string $method, string $url, Body $body = null, array $headers = []): Response
{
$request = $this->factory->createRequest($method, $url)->withBody(Stream::create(strval($body)));
foreach ($headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
$response = $this->client->sendRequest($request);
return new class($response) implements Response {
private $response;
private $body;
public function __construct($response)
{
$this->response = $response;
}
public function statusCode(): int
{
return $this->response->getStatusCode();
}
public function getHeader(string $header): ?string
{
return $this->response->getHeader($header)[0] ?? null;
}
public function body(): ?Body
{
return $this->body ?: $this->body = Body::fromString(
$this->response->getBody()->getContents(),
$this->getHeader('content-type')
);
}
};
}
}