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

HttpClient::acceptRequest()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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