1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Foundation; |
4
|
|
|
|
5
|
|
|
use ApiClients\Foundation\Hydrator\CommandBus\Command\ExtractFQCNCommand; |
6
|
|
|
use ApiClients\Foundation\Hydrator\CommandBus\Command\HydrateFQCNCommand; |
7
|
|
|
use ApiClients\Foundation\Resource\ResourceInterface; |
8
|
|
|
use ApiClients\Tools\CommandBus\CommandBusInterface; |
9
|
|
|
use InvalidArgumentException; |
10
|
|
|
use Psr\Container\ContainerInterface; |
11
|
|
|
use React\Promise\CancellablePromiseInterface; |
12
|
|
|
use function React\Promise\resolve; |
13
|
|
|
|
14
|
|
|
final class Client implements ClientInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var CommandBusInterface |
18
|
|
|
*/ |
19
|
|
|
private $commandBus; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param CommandBusInterface $commandBus |
23
|
|
|
*/ |
24
|
|
|
public function __construct(CommandBusInterface $commandBus) |
25
|
|
|
{ |
26
|
|
|
$this->commandBus = $commandBus; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param $command |
31
|
|
|
* @return CancellablePromiseInterface |
32
|
|
|
*/ |
33
|
|
|
public function handle($command): CancellablePromiseInterface |
34
|
|
|
{ |
35
|
|
|
return $this->commandBus->handle($command); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function hydrate(string $resource): CancellablePromiseInterface |
39
|
|
|
{ |
40
|
|
|
$resource = json_decode($resource, true); |
41
|
|
|
if (!isset($resource['class'], $resource['properties'])) { |
42
|
|
|
throw new InvalidArgumentException(); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (!class_exists($resource['class'])) { |
46
|
|
|
throw new InvalidArgumentException(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$class = $resource['class']; |
50
|
|
|
$json = $resource['properties']; |
51
|
|
|
|
52
|
|
|
return $this->handle(new HydrateFQCNCommand($class, $json)); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function extract(ResourceInterface $resource): CancellablePromiseInterface |
56
|
|
|
{ |
57
|
|
|
$class = get_class($resource); |
58
|
|
|
|
59
|
|
|
return $this->handle( |
60
|
|
|
new ExtractFQCNCommand($class, $resource) |
61
|
|
|
)->then(function ($json) use ($class) { |
62
|
|
|
return resolve(json_encode([ |
63
|
|
|
'class' => $class, |
64
|
|
|
'properties' => $json, |
65
|
|
|
])); |
66
|
|
|
}); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|