Completed
Pull Request — master (#106)
by Alex
01:45
created

HttpClient::getWorker()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Spiral\RoadRunner;
5
6
class HttpClient
7
{
8
    /** @var Worker */
9
    private $worker;
10
11
    /**
12
     * @param Worker $worker
13
     */
14
    public function __construct(Worker $worker)
15
    {
16
        $this->worker = $worker;
17
    }
18
19
    /**
20
     * @return Worker
21
     */
22
    public function getWorker(): Worker
23
    {
24
        return $this->worker;
25
    }
26
27
    /**
28
     * @return array|null Request information as ['ctx'=>[], 'body'=>string] or null if termination request or invalid context.
29
     */
30
    public function acceptRequest()
31
    {
32
        $body = $this->getWorker()->receive($ctx);
33
        if (empty($body) && empty($ctx)) {
34
            // termination request
35
            return null;
36
        }
37
38
        if (empty($ctx = json_decode($ctx, true))) {
39
            // invalid context
40
            return null;
41
        }
42
43
        return ['ctx' => $ctx, 'body' => $body];
44
    }
45
46
    /**
47
     * Send response to the application server.
48
     *
49
     * @param int $status Http status code
50
     * @param string $body Body of response
51
     * @param string[][] $headers An associative array of the message's headers. Each
52
     *     key MUST be a header name, and each value MUST be an array of strings
53
     *     for that header.
54
     */
55
    public function respond(int $status, string $body, $headers = [])
56
    {
57
        if (empty($headers)) {
58
            // this is required to represent empty header set as map and not as array
59
            $headers = new \stdClass();
60
        }
61
62
        $this->getWorker()->send(
63
            $body,
64
            json_encode(['status' => $status, 'headers' => $headers])
65
        );
66
    }
67
}
68