summaryrefslogtreecommitdiff
path: root/src/PSR7Client.php
blob: 111ab6ceea08d51f2e9135cb3f3241a4fe234738 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
<?php
/**
 * High-performance PHP process supervisor and load balancer written in Go
 *
 * @author Wolfy-J
 */

namespace Spiral\RoadRunner;

use Http\Factory\Diactoros;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileFactoryInterface;

/**
 * Manages PSR-7 request and response.
 */
class PSR7Client
{
    /**
     * @var Worker
     */
    private $worker;

    /**
     * @var ServerRequestFactoryInterface
     */
    private $requestFactory;

    /**
     * @var StreamFactoryInterface
     */
    private $streamFactory;

    /**
     * @var UploadedFileFactoryInterface
     */
    private $uploadsFactory;

    /**
     * @param Worker                             $worker
     * @param ServerRequestFactoryInterface|null $requestFactory
     * @param StreamFactoryInterface|null        $streamFactory
     * @param UploadedFileFactoryInterface|null  $uploadsFactory
     */
    public function __construct(
        Worker $worker,
        ServerRequestFactoryInterface $requestFactory = null,
        StreamFactoryInterface $streamFactory = null,
        UploadedFileFactoryInterface $uploadsFactory = null
    ) {
        $this->worker = $worker;
        $this->requestFactory = $requestFactory ?? new Diactoros\ServerRequestFactory();
        $this->streamFactory = $streamFactory ?? new Diactoros\StreamFactory();
        $this->uploadsFactory = $uploadsFactory ?? new Diactoros\UploadedFileFactory();
    }

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

    /**
     * @return ServerRequestInterface|null
     */
    public function acceptRequest()
    {
        $body = $this->worker->receive($ctx);
        if (empty($body) && empty($ctx)) {
            // termination request
            return null;
        }

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

        $_SERVER = $this->configureServer($ctx);

        $request = $this->requestFactory->createServerRequest(
            $ctx['method'],
            $ctx['uri'],
            $_SERVER
        );

        parse_str($ctx['rawQuery'], $query);

        $request = $request
            ->withCookieParams($ctx['cookies'])
            ->withProtocolVersion($ctx['protocol'])
            ->withQueryParams($query)
            ->withUploadedFiles($this->wrapUploads($ctx['uploads']));

        foreach ($ctx['attributes'] as $name => $value) {
            $request = $request->withAttribute($name, $value);
        }

        foreach ($ctx['headers'] as $name => $value) {
            $request = $request->withHeader($name, $value);
        }

        if ($body !== null) {
            $bodyStream = $this->streamFactory->createStream($body);
            $bodyStream->write($body);

            $request = $request->withBody($bodyStream);
        }

        if ($ctx['parsed']) {
            $request = $request->withParsedBody(json_decode($body, true));
        }

        return $request;
    }

    /**
     * Send response to the application server.
     *
     * @param ResponseInterface $response
     */
    public function respond(ResponseInterface $response)
    {
        $headers = $response->getHeaders();
        if (empty($headers)) {
            // this is required to represent empty header set as map and not as array
            $headers = new \stdClass();
        }

        $this->worker->send($response->getBody(), json_encode([
            'status'  => $response->getStatusCode(),
            'headers' => $headers
        ]));
    }

   /**
     * Returns altered copy of _SERVER variable. Sets ip-address,
     * request-time and other values.
     *
     * @param array $ctx
     * @return array
     */
    protected function configureServer(array $ctx): array
    {
        $server = $_SERVER;
        $server['REQUEST_TIME'] = time();
        $server['REQUEST_TIME_FLOAT'] = microtime(true);
        $server['REMOTE_ADDR'] = $ctx['attributes']['ipAddress'] ?? $ctx['remoteAddr'] ?? '127.0.0.1';

        return $server;
    }

    /**
     * Wraps all uploaded files with UploadedFile.
     *
     * @param array $files
     *
     * @return array
     */
    private function wrapUploads($files): array
    {
        if (empty($files)) {
            return [];
        }

        $result = [];
        foreach ($files as $index => $f) {
            if (!isset($f['name'])) {
                $result[$index] = $this->wrapUploads($f);
                continue;
            }

            $result[$index] = $this->uploadsFactory->createUploadedFile(
                $this->streamFactory->createStreamFromFile($f['tmpName']),
                $f['size'],
                $f['error'],
                $f['name'],
                $f['mime']
            );
        }

        return $result;
    }
}