1 | <?php |
||
26 | class Http implements Driver |
||
27 | { |
||
28 | /** |
||
29 | * @var HttpAsyncClient |
||
30 | */ |
||
31 | private $client; |
||
32 | /** |
||
33 | * @var MessageFactory |
||
34 | */ |
||
35 | private $messageFactory; |
||
36 | /** |
||
37 | * @var UriFactory |
||
38 | */ |
||
39 | private $uriFactory; |
||
40 | /** |
||
41 | * @var string |
||
42 | */ |
||
43 | private $baseUri; |
||
44 | /** |
||
45 | * @var AnnotationReader |
||
46 | */ |
||
47 | private $reader; |
||
48 | |||
49 | 3 | public function __construct(HttpAsyncClient $client, MessageFactory $messageFactory, UriFactory $uriFactory, AnnotationReader $reader, $baseUri = 'http://localhost:5001/api/v0') |
|
50 | { |
||
51 | 3 | $this->client = $client; |
|
52 | 3 | $this->messageFactory = $messageFactory; |
|
53 | 3 | $this->uriFactory = $uriFactory; |
|
54 | 3 | $this->baseUri = $baseUri; |
|
55 | 3 | $this->reader = $reader; |
|
56 | 3 | } |
|
57 | |||
58 | 2 | public function execute(Command $command) |
|
59 | { |
||
60 | 2 | $request = $this->buildRequest($command, $this->getConfig($command)); |
|
61 | |||
62 | 2 | return $this->client->sendAsyncRequest($request)->then(function (ResponseInterface $response) { |
|
63 | return (string) $response->getBody()->getContents(); |
||
64 | 2 | })->wait(); |
|
65 | } |
||
66 | |||
67 | 2 | private function buildRequest(Command $command, $config): RequestInterface |
|
68 | { |
||
69 | 2 | $body = $this->buildBody($command); |
|
70 | |||
71 | 2 | return $this->messageFactory->createRequest( |
|
72 | 2 | $config['method'], |
|
73 | 2 | $this->buildUri($command, $config), |
|
74 | 2 | $this->buildHeaders($body), |
|
75 | 2 | $body->build() |
|
76 | ); |
||
77 | } |
||
78 | |||
79 | 2 | private function buildUri(Command $command, array $config): UriInterface |
|
80 | { |
||
81 | 2 | $uri = $this->uriFactory->createUri($this->baseUri . $config['path']); |
|
82 | 2 | $vars = []; |
|
83 | |||
84 | 2 | foreach ($command->getArguments() as $name => $value) { |
|
85 | 2 | if (is_string($value) && is_readable($value)) { |
|
86 | 1 | continue; |
|
87 | } |
||
88 | |||
89 | 2 | $vars[$name] = $value; |
|
90 | } |
||
91 | |||
92 | //fix arg1= arg2= to arg= weird but seems to be correct (doubled query variable names) |
||
93 | 2 | $query = preg_replace('/(\d+)=/', '=', http_build_query($vars)); |
|
94 | |||
95 | 2 | return $uri->withQuery($query); |
|
96 | } |
||
97 | |||
98 | 2 | private function buildBody(Command $command): MultipartStreamBuilder |
|
113 | |||
114 | 2 | private function buildHeaders(MultipartStreamBuilder $body): array |
|
115 | { |
||
116 | 2 | $emptyBody = '--' . $body->getBoundary() . "--\r\n"; |
|
123 | |||
124 | 2 | private function getConfig(Command $command): array |
|
140 | } |
||
141 |