Test Failed
Pull Request — master (#34)
by Anatoly
04:34
created

JsonRequest::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 5
dl 0
loc 6
rs 10
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
    public function __construct(string $method, $uri, $data, int $flags = 0, int $depth = 512)
39
    {
40
        parent::__construct($method, $uri);
41
42
        $this->setBody(self::createBody($data, $flags, $depth));
43
        $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
    private static function createBody($data, int $flags, int $depth): StreamInterface
54
    {
55
        if ($data instanceof StreamInterface) {
56
            return $data;
57
        }
58
59
        try {
60
            $json = json_encode($data, $flags | JSON_THROW_ON_ERROR, $depth);
61
        } catch (JsonException $e) {
62
            throw new InvalidArgumentException(sprintf(
63
                'Unable to create the JSON request due to an invalid data: %s',
64
                $e->getMessage(),
65
            ), 0, $e);
66
        }
67
68
        $stream = new PhpTempStream('r+b');
69
        $stream->write($json);
70
        $stream->rewind();
71
72
        return $stream;
73
    }
74
}
75