RequestBuilder::moveArgsToSentargs()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 10
ccs 8
cts 8
cp 1
crap 4
rs 10
1
<?php
2
3
namespace Yabacon\Paystack\Http;
4
5
use \Yabacon\Paystack\Contracts\RouteInterface;
6
use \Yabacon\Paystack\Helpers\Router;
7
use \Yabacon\Paystack;
8
9
class RequestBuilder
10
{
11
    protected $paystackObj;
12
    protected $interface;
13
    protected $request;
14
15
    public $payload = [ ];
16
    public $sentargs = [ ];
17
18 3
    public function __construct($paystackObj, $interface, array $payload = [ ], array $sentargs = [ ])
19
    {
20 3
        $this->request = new Request($paystackObj);
21 3
        $this->paystackObj = $paystackObj;
22 3
        $this->interface = $interface;
23 3
        $this->payload = $payload;
24 3
        $this->sentargs = $sentargs;
25 3
    }
26
27 1
    public function build()
28
    {
29 1
        $this->request->headers["Authorization"] = "Bearer " . $this->paystackObj->secret_key;
30 1
        $this->request->headers["User-Agent"] = "Paystack/v1 PhpBindings/" . Paystack::VERSION;
31 1
        $this->request->endpoint = Router::PAYSTACK_API_ROOT . $this->interface[RouteInterface::ENDPOINT_KEY];
32 1
        $this->request->method = $this->interface[RouteInterface::METHOD_KEY];
33 1
        $this->moveArgsToSentargs();
34 1
        $this->putArgsIntoEndpoint($this->request->endpoint);
35 1
        $this->packagePayload();
36 1
        return $this->request;
37
    }
38
39 1
    public function packagePayload()
40
    {
41 1
        if (is_array($this->payload) && count($this->payload)) {
42 1
            if ($this->request->method === RouteInterface::GET_METHOD) {
43 1
                $this->request->endpoint = $this->request->endpoint . '?' . http_build_query($this->payload);
44 1
            } else {
45 1
                $this->request->body = json_encode($this->payload);
46
            }
47 1
        }
48 1
    }
49
50 2
    public function putArgsIntoEndpoint(&$endpoint)
51
    {
52 2
        foreach ($this->sentargs as $key => $value) {
53 2
            $endpoint = str_replace('{' . $key . '}', $value, $endpoint);
54 2
        }
55 2
    }
56
57 2
    public function moveArgsToSentargs()
58
    {
59 2
        if (!array_key_exists(RouteInterface::ARGS_KEY, $this->interface)) {
60 1
            return;
61
        }
62 2
        $args = $this->interface[RouteInterface::ARGS_KEY];
63 2
        foreach ($this->payload as $key => $value) {
64 1
            if (in_array($key, $args)) {
65 1
                $this->sentargs[$key] = $value;
66 1
                unset($this->payload[$key]);
67 1
            }
68 2
        }
69 2
    }
70
}
71