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

ProfileRequest::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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
     * @param string $path
23
     * @param mixed  $profileSettings
24
     */
25 2
    public function __construct(string $path, $profileSettings)
26
    {
27 2
        parent::__construct($path);
28
29 2
        $this->profileSettings = $profileSettings;
30 2
    }
31
32
    /**
33
     * @param string|null $method
34
     *
35
     * @return RequestInterface
36
     */
37 2
    public function build(?string $method = null): RequestInterface
38
    {
39 2
        $request = $this->origin->withMethod($method);
40
41 2
        if ($method === 'get') {
42 1
            $uri = Uri::fromParts([
43 1
                'query' => $this->buildQuery(),
44
            ]);
45
46 1
            return $request->withUri($uri);
47
        }
48
49 1
        return $request->withBody(stream_for($this->buildBody()));
50
    }
51
52
    /**
53
     * @return string
54
     */
55 1
    public function buildBody(): string
56
    {
57 1
        $body = [];
58 1
        if ($this->profileSettings instanceof ProfileSettings) {
59 1
            $body = $this->profileSettings;
60
        } elseif (\is_array($this->profileSettings)) {
61
            $body = [
62
                'fields' => $this->profileSettings,
63
            ];
64
        }
65
66 1
        return json_encode($body);
67
    }
68
69
    /**
70
     * @return string
71
     */
72 1
    public function buildQuery(): string
73
    {
74 1
        if (\is_string($this->profileSettings)) {
75 1
            return http_build_query([
76 1
                'fields' => $this->profileSettings,
77
            ]);
78
        }
79
80
        return '';
81
    }
82
}
83