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 Psr\Http\Message\ResponseInterface; |
9
|
|
|
use React\Promise\CancellablePromiseInterface; |
10
|
|
|
use RingCentral\Psr7\Request; |
11
|
|
|
use Rx\Observable; |
12
|
|
|
use function igorw\get_in; |
13
|
|
|
use function React\Promise\resolve; |
14
|
|
|
use function WyriHaximus\React\futureFunctionPromise; |
15
|
|
|
|
16
|
|
|
class FetchAndHydrateService 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 $this->requestService->handle( |
50
|
|
|
new Request('GET', $path) |
51
|
|
|
)->then(function (ResponseInterface $response) use ($hydrateClass, $index) { |
52
|
|
|
return $this->hydrator->hydrate( |
53
|
|
|
$hydrateClass, |
54
|
|
|
get_in($response->getBody()->getJson(), explode('.', $index), []) |
|
|
|
|
55
|
|
|
); |
56
|
|
|
}); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: