|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace ApiClients\Tools\Services\Client; |
|
4
|
|
|
|
|
5
|
|
|
use ApiClients\Foundation\Hydrator\Hydrator; |
|
6
|
|
|
use ApiClients\Foundation\Service\ServiceInterface; |
|
7
|
|
|
use ApiClients\Foundation\Transport\Service\RequestService; |
|
8
|
|
|
use React\Promise\CancellablePromiseInterface; |
|
9
|
|
|
use RingCentral\Psr7\Request; |
|
10
|
|
|
use Rx\Observable; |
|
11
|
|
|
use Rx\React\Promise; |
|
12
|
|
|
use function igorw\get_in; |
|
13
|
|
|
use function React\Promise\resolve; |
|
14
|
|
|
use function WyriHaximus\React\futureFunctionPromise; |
|
15
|
|
|
|
|
16
|
|
|
class FetchAndIterateService implements ServiceInterface |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @var RequestService |
|
20
|
|
|
*/ |
|
21
|
|
|
private $requestService; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var Hydrator |
|
25
|
|
|
*/ |
|
26
|
|
|
private $hydrator; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param RequestService $requestService |
|
30
|
|
|
* @param Hydrator $hydrator |
|
31
|
|
|
*/ |
|
32
|
|
|
public function __construct(RequestService $requestService, Hydrator $hydrator) |
|
33
|
|
|
{ |
|
34
|
|
|
$this->requestService = $requestService; |
|
35
|
|
|
$this->hydrator = $hydrator; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param string|null $path |
|
40
|
|
|
* @param string|null $index |
|
41
|
|
|
* @param string|null $hydrateClass |
|
42
|
|
|
* @return CancellablePromiseInterface |
|
43
|
|
|
*/ |
|
44
|
|
|
public function handle( |
|
45
|
|
|
string $path = null, |
|
46
|
|
|
string $index = null, |
|
47
|
|
|
string $hydrateClass = null |
|
48
|
|
|
): CancellablePromiseInterface { |
|
49
|
|
|
return resolve( |
|
50
|
|
|
Promise::toObservable( |
|
51
|
|
|
$this->requestService->handle( |
|
52
|
|
|
new Request('GET', $path) |
|
53
|
|
|
) |
|
54
|
|
|
)->flatMap(function ($response) use ($index) { |
|
55
|
|
|
return Observable::fromArray(get_in($response->getBody()->getJson(), explode('.', $index), [])); |
|
56
|
|
|
})->map(function ($json) use ($hydrateClass) { |
|
57
|
|
|
return $this->hydrator->hydrate( |
|
58
|
|
|
$hydrateClass, |
|
59
|
|
|
$json |
|
60
|
|
|
); |
|
61
|
|
|
}) |
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|