ContextPacking::keys()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * Client packing of attachments
4
 * User: moyo
5
 * Date: 19/03/2018
6
 * Time: 9:53 PM
7
 */
8
9
namespace Carno\HRPC\Client\Handlers;
10
11
use Carno\Chain\Layered;
12
use Carno\Coroutine\Context;
13
use Carno\RPC\Protocol\Request;
14
use Throwable;
15
16
class ContextPacking implements Layered
17
{
18
    public const HTTP_HEADER = 'X-Trans-CTX';
19
20
    /**
21
     * @var array
22
     */
23
    protected $keys = [];
24
25
    /**
26
     * @param string ...$allowed
27
     */
28
    public function keys(string ...$allowed) : void
29
    {
30
        $this->keys = $allowed;
31
    }
32
33
    public function inbound($request, Context $ctx)
34
    {
35
        /**
36
         * @var Request $request
37
         */
38
39
        $attachments = [];
40
41
        foreach ($this->keys as $key) {
42
            $ctx->has($key) && $attachments[$key] = $ctx->get($key);
43
        }
44
45
        if ($attachments) {
46
            $dat = base64_encode(json_encode($attachments, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
47
            $request->opsExtra('h-headers', static function (&$headers) use ($dat) {
48
                $headers[self::HTTP_HEADER] = $dat;
49
            });
50
        }
51
52
        return $request;
53
    }
54
55
    public function outbound($response, Context $ctx)
56
    {
57
        return $response;
58
    }
59
60
    public function exception(Throwable $e, Context $ctx)
61
    {
62
        throw $e;
63
    }
64
}
65