JsonRequest   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 46
ccs 17
cts 17
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A createBody() 0 21 3
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Nekhay <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Nekhay
8
 * @license https://github.com/sunrise-php/http-message/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-message
10
 */
11
12
namespace Sunrise\Http\Message\Request;
13
14
use JsonException;
15
use Psr\Http\Message\StreamInterface;
16
use Sunrise\Http\Message\Exception\InvalidArgumentException;
17
use Sunrise\Http\Message\Request;
18
use Sunrise\Http\Message\Stream\PhpTempStream;
19
20
use function json_encode;
21
use function sprintf;
22
23
use const JSON_THROW_ON_ERROR;
24
25
/**
26
 * @since 3.1.0
27
 */
28
final class JsonRequest extends Request
29
{
30
    /**
31
     * @param mixed $uri
32
     * @param mixed $data
33
     * @param int<1, max> $depth
34
     * @psalm-param int<1, 2147483647> $depth
35
     *
36
     * @throws InvalidArgumentException
37
     */
38 4
    public function __construct(string $method, $uri, $data, int $flags = 0, int $depth = 512)
39
    {
40 4
        parent::__construct($method, $uri);
41
42 4
        $this->setBody(self::createBody($data, $flags, $depth));
43 3
        $this->setHeader('Content-Type', 'application/json; charset=utf-8');
44
    }
45
46
    /**
47
     * @param mixed $data
48
     * @param int<1, max> $depth
49
     * @psalm-param int<1, 2147483647> $depth
50
     *
51
     * @throws InvalidArgumentException
52
     */
53 4
    private static function createBody($data, int $flags, int $depth): StreamInterface
54
    {
55 4
        if ($data instanceof StreamInterface) {
56 1
            return $data;
57
        }
58
59
        try {
60
            /** @var non-empty-string $json */
61 3
            $json = json_encode($data, $flags | JSON_THROW_ON_ERROR, $depth);
62 1
        } catch (JsonException $e) {
63 1
            throw new InvalidArgumentException(sprintf(
64 1
                'Unable to create the JSON request due to an invalid data: %s',
65 1
                $e->getMessage(),
66 1
            ), 0, $e);
67
        }
68
69 2
        $stream = new PhpTempStream('r+b');
70 2
        $stream->write($json);
71 2
        $stream->rewind();
72
73 2
        return $stream;
74
    }
75
}
76