HttpClient   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 64
rs 10
c 0
b 0
f 0

4 Methods

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