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

ProfileRequest::build()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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