summaryrefslogtreecommitdiff
path: root/src/HttpClient.php
blob: f31a9b5038cfcd3e5df4a6d1ed54b7710dbd092c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
/**
 * High-performance PHP process supervisor and load balancer written in Go
 *
 * @author Alex Bond
 */
declare(strict_types=1);

namespace Spiral\RoadRunner;

class HttpClient
{
    /** @var Worker */
    private $worker;

    /**
     * @param Worker $worker
     */
    public function __construct(Worker $worker)
    {
        $this->worker = $worker;
    }

    /**
     * @return Worker
     */
    public function getWorker(): Worker
    {
        return $this->worker;
    }

    /**
     * @return array|null Request information as ['ctx'=>[], 'body'=>string] or null if termination request or invalid context.
     */
    public function acceptRequest()
    {
        $body = $this->getWorker()->receive($ctx);
        if (empty($body) && empty($ctx)) {
            // termination request
            return null;
        }

        $ctx = json_decode($ctx, true);
        if (is_null($ctx)) {
            // invalid context
            return null;
        }

        return ['ctx' => $ctx, 'body' => $body];
    }

    /**
     * Send response to the application server.
     *
     * @param int        $status  Http status code
     * @param string     $body    Body of response
     * @param string[][] $headers An associative array of the message's headers. Each
     *                            key MUST be a header name, and each value MUST be an array of strings
     *                            for that header.
     */
    public function respond(int $status, string $body, array $headers = [])
    {
        if (empty($headers)) {
            // this is required to represent empty header set as map and not as array
            $headers = new \stdClass();
        }

        $this->getWorker()->send(
            $body,
            json_encode(['status' => $status, 'headers' => $headers])
        );
    }
}