Skip to content

Commit 9eb247f

Browse files
authored
Merge pull request #106 from apisearch-io/feature/async-test-client
Added AsyncTestClient
2 parents 655ef11 + 47b3467 commit 9eb247f

File tree

1 file changed

+118
-0
lines changed

1 file changed

+118
-0
lines changed

Http/AsyncTestClient.php

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Apisearch PHP Client.
5+
*
6+
* For the full copyright and license information, please view the LICENSE
7+
* file that was distributed with this source code.
8+
*
9+
* Feel free to edit as you please, and have fun.
10+
*
11+
* @author Marc Morera <yuhu@mmoreram.com>
12+
*/
13+
14+
declare(strict_types=1);
15+
16+
namespace Apisearch\Http;
17+
18+
use Clue\React\Block;
19+
use Symfony\Component\HttpFoundation\Request;
20+
use Symfony\Component\HttpKernel\AsyncKernel;
21+
22+
/**
23+
* Class AsyncTestClient.
24+
*/
25+
class AsyncTestClient extends Client implements HttpClient
26+
{
27+
/**
28+
* @var AsyncKernel
29+
*
30+
* Async kernel
31+
*/
32+
private $kernel;
33+
34+
/**
35+
* TestClient constructor.
36+
*
37+
* @param AsyncKernel $kernel
38+
* @param string $version
39+
* @param RetryMap $retryMap
40+
*/
41+
public function __construct(
42+
AsyncKernel $kernel,
43+
string $version,
44+
RetryMap $retryMap
45+
) {
46+
$this->kernel = $kernel;
47+
48+
parent::__construct(
49+
$version,
50+
$retryMap
51+
);
52+
}
53+
54+
/**
55+
* Get a response given some parameters.
56+
* Return an array with the status code and the body.
57+
*
58+
* @param string $url
59+
* @param string $method
60+
* @param array $query
61+
* @param array $body
62+
* @param array $server
63+
*
64+
* @return array
65+
*/
66+
public function get(
67+
string $url,
68+
string $method,
69+
array $query = [],
70+
array $body = [],
71+
array $server = []
72+
): array {
73+
$method = trim(strtolower($method));
74+
$requestParts = $this->buildRequestParts(
75+
$url,
76+
$query,
77+
$body,
78+
$server
79+
);
80+
81+
$headersFormatted = [];
82+
foreach ($server as $key => $value) {
83+
$headersFormatted['HTTP_'.str_replace('-', '_', $key)] = $value;
84+
}
85+
86+
$request = new Request(
87+
array_map('urldecode', $query),
88+
[],
89+
[],
90+
[],
91+
[],
92+
array_merge($headersFormatted, [
93+
'CONTENT_TYPE' => 'application/json',
94+
]),
95+
json_encode($requestParts->getParameters()['json'])
96+
);
97+
98+
$request->setMethod($method);
99+
$request->server->set('REQUEST_URI', $requestParts->getUrl());
100+
101+
$promise = $this
102+
->kernel
103+
->handleAsync($request);
104+
105+
$response = Block\await(
106+
$promise,
107+
$this
108+
->kernel
109+
->getContainer()
110+
->get('reactphp.event_loop')
111+
);
112+
113+
return [
114+
'code' => $response->getStatusCode(),
115+
'body' => json_decode($response->getContent(), true),
116+
];
117+
}
118+
}

0 commit comments

Comments
 (0)