Passed
Push — master ( 301768...50e705 )
by Ivan
11:01
created

RpcResponse::wrapContent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Boomdraw\RpcCore\Responses;
6
7
use Throwable;
8
9
class RpcResponse extends RpcBaseResponse
10
{
11
    /**
12
     * RpcResponse constructor.
13
     *
14
     * @param mixed $content
15
     */
16 16
    public function __construct($content = '')
17
    {
18 16
        $content = $this->transformContentToArray($content);
19 16
        $content = $this->wrapContent($content);
20 16
        $content = $this->structureContent($content);
21
22 16
        parent::__construct($content, 200, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
23 16
    }
24
25
    /**
26
     * Transform content to array.
27
     *
28
     * @param mixed $content
29
     * @return mixed[]
30
     */
31 16
    protected function transformContentToArray($content = ''): array
32
    {
33 16
        if (is_array($content)) {
34 3
            return $content;
35
        }
36
        try {
37 13
            return json_decode($content, true, 512, JSON_THROW_ON_ERROR);
38 11
        } catch (Throwable $exception) {
39 11
            return ['data' => $content];
40
        }
41
    }
42
43
    /**
44
     * Structure content according to JsonRPC specification.
45
     *
46
     * @param array $data
47
     * @return array
48
     */
49 16
    protected function structureContent(array $data): array
50
    {
51
        return [
52 16
            'jsonrpc' => '2.0',
53 16
            'result' => $data,
54 16
            'id' => context('requestId'),
55
        ];
56
    }
57
58
    /**
59
     * Wrap content.
60
     *
61
     * @param array $data
62
     * @return array
63
     */
64 16
    protected function wrapContent(array $data): array
65
    {
66 16
        if (! array_key_exists('data', $data)) {
67 2
            return compact('data');
68
        }
69
70 14
        return $data;
71
    }
72
}
73