Passed
Pull Request — master (#3)
by Gombos
02:09
created

Api::sendPost()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Glorand\Drip\Api;
4
5
use Glorand\Drip\Api\Response\ApiResponse;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Exception\GuzzleException;
8
use GuzzleHttp\Psr7\Response;
9
10
abstract class Api
11
{
12
    const GET = 'get';
13
    const POST = 'post';
14
    const PUT = 'put';
15
    const DELETE = 'delete';
16
17
    /**
18
     * @var Client
19
     */
20
    protected $client;
21
    /** @var string */
22
    protected $accountId;
23
24
    /**
25
     * Api constructor.
26
     *
27
     * @param Client $client
28
     * @param string $accountId
29
     */
30 6
    public function __construct(Client $client, string $accountId)
31
    {
32 6
        $this->client = $client;
33 6
        $this->accountId = $accountId;
34 6
    }
35
36 6
    protected function prepareUrl(string $url): string
37
    {
38 6
        if (false !== strpos($url, ':account_id:')) {
39 4
            $url = str_replace(':account_id:', $this->accountId, $url);
40
        }
41
42 6
        return trim($url, '/');
43
    }
44
45 4
    protected function sendGet($url, array $params = []): ApiResponse
46
    {
47 4
        $options['query'] = $params;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.
Loading history...
48
49 4
        return $this->makeRequest(self::GET, $this->prepareUrl($url), $options);
50
    }
51
52 2
    protected function sendPost($url, array $params = []): ApiResponse
53
    {
54 2
        $options['body'] = is_array($params) ? json_encode($params) : $params;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.
Loading history...
introduced by
The condition is_array($params) is always true.
Loading history...
55
56 2
        return $this->makeRequest(self::POST, $this->prepareUrl($url), $options);
57
    }
58
59
    /**
60
     * @param       $method
61
     * @param       $url
62
     * @param array $options
63
     *
64
     * @return ApiResponse
65
     */
66 6
    private function makeRequest($method, $url, array $options = []): ApiResponse
67
    {
68
        try {
69 6
            $response = $this->client->request($method, $url, $options);
70 4
        } catch (GuzzleException $e) {
71 4
            $response = new Response($e->getCode(), [], $e->getMessage());
72
        }
73
74 6
        return new ApiResponse($url, $options, $response);
75
    }
76
}
77