UrlEncodedRequest::createBody()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 2
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 Psr\Http\Message\StreamInterface;
15
use Sunrise\Http\Message\Exception\InvalidArgumentException;
16
use Sunrise\Http\Message\Request;
17
use Sunrise\Http\Message\Stream\PhpTempStream;
18
19
use function http_build_query;
20
21
use const PHP_QUERY_RFC1738;
22
use const PHP_QUERY_RFC3986;
23
24
/**
25
 * @since 3.1.0
26
 */
27
final class UrlEncodedRequest extends Request
28
{
29
    public const ENCODING_TYPE_RFC1738 = PHP_QUERY_RFC1738;
30
    public const ENCODING_TYPE_RFC3986 = PHP_QUERY_RFC3986;
31
32
    /**
33
     * @param mixed $uri
34
     * @param mixed $data
35
     * @param self::ENCODING_TYPE_* $encodingType
36
     *
37
     * @throws InvalidArgumentException
38
     */
39 5
    public function __construct(string $method, $uri, $data, int $encodingType = self::ENCODING_TYPE_RFC1738)
40
    {
41 5
        parent::__construct($method, $uri);
42
43 5
        $this->setBody(self::createBody($data, $encodingType));
44 5
        $this->setHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
45
    }
46
47
    /**
48
     * @param mixed $data
49
     * @param self::ENCODING_TYPE_* $encodingType
50
     */
51 5
    private static function createBody($data, int $encodingType): StreamInterface
52
    {
53 5
        if ($data instanceof StreamInterface) {
54 1
            return $data;
55
        }
56
57 4
        $query = http_build_query((array) $data, '', '&', $encodingType);
58
59 4
        $stream = new PhpTempStream('r+b');
60 4
        $stream->write($query);
61 4
        $stream->rewind();
62
63 4
        return $stream;
64
    }
65
}
66