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

Api::isSuccessResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
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
    public function __construct(Client $client, string $accountId)
31
    {
32
        $this->client = $client;
33
        $this->accountId = $accountId;
34
    }
35
36
    protected function prepareUrl(string $url): string
37
    {
38
        if (false !== strpos($url, ':account_id:')) {
39
            $url = str_replace(':account_id:', $this->accountId, $url);
40
        }
41
42
        return trim($url, '/');
43
    }
44
45
    protected function sendGet($url, array $params = []): ApiResponse
46
    {
47
        $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
        return $this->makeRequest(self::GET, $this->prepareUrl($url), $options);
50
    }
51
52
    protected function sendPost($url, array $params = []): ApiResponse
53
    {
54
        $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
        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
    private function makeRequest($method, $url, array $options = []): ApiResponse
67
    {
68
        try {
69
            $response = $this->client->request($method, $url, $options);
70
        } catch (GuzzleException $e) {
71
            $response = new Response($e->getCode(), [], $e->getMessage());
72
        }
73
74
        return new ApiResponse($url, $options, $response);
75
    }
76
}
77