Completed
Pull Request — master (#127)
by Alexandr
04:00
created

ProfileRequest::build()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 13
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Kerox\Messenger\Request;
6
7
use GuzzleHttp\Psr7\Uri;
8
use Kerox\Messenger\Model\ProfileSettings;
9
use Psr\Http\Message\RequestInterface;
10
use function GuzzleHttp\Psr7\stream_for;
11
12
class ProfileRequest extends AbstractRequest implements QueryRequestInterface, BodyRequestInterface
13
{
14
    /**
15
     * @var mixed
16
     */
17
    protected $profileSettings;
18
19
    /**
20
     * ProfileRequest constructor.
21
     *
22 2
     * @param string $path
23
     * @param mixed  $profileSettings
24 2
     */
25
    public function __construct(string $path, $profileSettings)
26 2
    {
27 2
        parent::__construct($path);
28
29
        $this->profileSettings = $profileSettings;
30
    }
31
32 2
    /**
33
     * @param string|null $method
34
     *
35 2
     * @return RequestInterface
36
     */
37
    public function build(?string $method = null): RequestInterface
38 2
    {
39
        $request = $this->origin->withMethod($method);
40
41
        if ($method === 'get') {
42
            $uri = Uri::fromParts([
43
                'query' => $this->buildQuery(),
44 2
            ]);
45
46 2
            return $request->withUri($uri);
47 2
        }
48 1
49 1
        return $request->withBody(stream_for($this->buildBody()));
50
    }
51
52
    /**
53
     * @return string
54
     */
55 2
    public function buildBody(): string
56
    {
57
        $body = [];
58
        if ($this->profileSettings instanceof ProfileSettings) {
59
            $body = $this->profileSettings;
60
        } elseif (\is_array($this->profileSettings)) {
61 2
            $body = [
62
                'fields' => $this->profileSettings,
63 2
            ];
64
        }
65 2
66
        return json_encode($body);
67 1
    }
68
69
    /**
70
     * @return string
71 2
     */
72
    public function buildQuery(): string
73
    {
74
        if (\is_string($this->profileSettings)) {
75
            return http_build_query([
76
                'fields' => $this->profileSettings,
77
            ]);
78
        }
79
80
        return '';
81
    }
82
}
83