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 ContainerInterface |
18
|
|
|
*/ |
19
|
|
|
private $container; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var CommandBusInterface |
23
|
|
|
*/ |
24
|
|
|
private $commandBus; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param ContainerInterface $container |
28
|
|
|
*/ |
29
|
|
|
public function __construct(ContainerInterface $container) |
30
|
|
|
{ |
31
|
|
|
$this->container = $container; |
32
|
|
|
$this->commandBus = $this->container->get(CommandBusInterface::class); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @return ContainerInterface |
37
|
|
|
*/ |
38
|
|
|
public function getContainer(): ContainerInterface |
39
|
|
|
{ |
40
|
|
|
return $this->container; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @return mixed |
45
|
|
|
*/ |
46
|
|
|
public function getFromContainer(string $id) |
47
|
|
|
{ |
48
|
|
|
return $this->container->get($id); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param $command |
53
|
|
|
* @return CancellablePromiseInterface |
54
|
|
|
*/ |
55
|
|
|
public function handle($command): CancellablePromiseInterface |
56
|
|
|
{ |
57
|
|
|
return $this->commandBus->handle($command); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function hydrate(string $resource): CancellablePromiseInterface |
61
|
|
|
{ |
62
|
|
|
$resource = json_decode($resource, true); |
63
|
|
|
if (!isset($resource['class'], $resource['properties'])) { |
64
|
|
|
throw new InvalidArgumentException(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if (!class_exists($resource['class'])) { |
68
|
|
|
throw new InvalidArgumentException(); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
$class = $resource['class']; |
72
|
|
|
$json = $resource['properties']; |
73
|
|
|
return $this->handle(new HydrateFQCNCommand($class, $json)); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
public function extract(ResourceInterface $resource): CancellablePromiseInterface |
77
|
|
|
{ |
78
|
|
|
$class = get_class($resource); |
79
|
|
|
return $this->handle( |
80
|
|
|
new ExtractFQCNCommand($class, $resource) |
81
|
|
|
)->then(function ($json) use ($class) { |
82
|
|
|
return resolve(json_encode([ |
83
|
|
|
'class' => $class, |
84
|
|
|
'properties' => $json, |
85
|
|
|
])); |
86
|
|
|
}); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|