Completed
Pull Request — master (#1)
by
unknown
02:53
created

Api::makeCallRequest()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 16
nc 4
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AcquiroPay;
6
7
use Exception;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\Psr7\Request;
10
use Psr\Http\Message\StreamInterface;
11
use Psr\Log\LoggerInterface;
12
use AcquiroPay\Contracts\Cache;
13
use AcquiroPay\Exceptions\UnauthorizedException;
14
15
class Api
16
{
17
    protected $cache;
18
    protected $http;
19
    protected $logger;
20
21
    protected $url;
22
    protected $username;
23
    protected $password;
24
25
    public function __construct(Cache $cache, Client $http, LoggerInterface $logger = null)
26
    {
27
        $this->cache = $cache;
28
        $this->http = $http;
29
        $this->logger = $logger;
30
    }
31
32
    public function setUrl(string $url): Api
33
    {
34
        $this->url = $url;
35
36
        return $this;
37
    }
38
39
    public function setUsername(string $username): Api
40
    {
41
        $this->username = $username;
42
43
        return $this;
44
    }
45
46
    public function setPassword(string $password): Api
47
    {
48
        $this->password = $password;
49
50
        return $this;
51
    }
52
53
    public function callService(string $service, string $method, string $endpoint, array $parameters = null)
54
    {
55
        return $this->call($method, '/services/'.$service, ['Endpoint' => $endpoint], $parameters);
56
    }
57
58
    public function call(string $method, string $endpoint, array $headers = [], array $parameters = null)
59
    {
60
        $stream = $this->makeCallRequest($method, $endpoint, $headers, $parameters);
61
        $json = json_decode((string) $stream);
62
63
        if (json_last_error() === JSON_ERROR_NONE) {
64
            return $json;
65
        }
66
67
        return (string) $stream;
68
    }
69
70
    protected function makeCallRequest(
71
        string $method,
72
        string $endpoint,
73
        array $headers = [],
74
        array $parameters = null
75
    ): StreamInterface
76
    {
77
        $headers = array_merge([
78
            'Accept' => 'application/json',
79
            'Content-Type' => 'application/json',
80
            'Authorization' => 'Bearer '.$this->token(),
81
        ], $headers);
82
83
        if (!Str::startsWith($endpoint, ['http://', 'https://'])) {
84
            $endpoint = $this->url.'/'.ltrim($endpoint, '/');
85
        }
86
87
        $body = $parameters !== null ? json_encode($parameters) : null;
88
89
        $response = $this->http->send(new Request($method, $endpoint, $headers, $body));
90
91
        return $response->getBody();
92
    }
93
94
    /**
95
     * Authorize token for performing request.
96
     *
97
     * @param string $token
98
     * @param string $service
99
     * @param string $method
100
     * @param string $endpoint
101
     *
102
     * @return Consumer
103
     *
104
     * @throws UnauthorizedException
105
     */
106
    public function authorize(string $token, string $service, string $method, string $endpoint): Consumer
107
    {
108
        try {
109
            $headers = ['Content-Type' => 'application/json'];
110
111
            $url = $this->url.'/authorize';
112
113
            $body = json_encode(compact('token', 'service', 'method', 'endpoint'));
114
115
            $response = $this->http->send(new Request('POST', $url, $headers, $body));
116
117
            $json = \GuzzleHttp\json_decode((string) $response->getBody());
118
119
            if (!isset($json->authorized, $json->consumer_id) || $json->authorized !== true) {
120
                throw new UnauthorizedException;
121
            }
122
123
            return Consumer::create($json->consumer_id);
124
        } catch (Exception $exception) {
125
            if ($this->logger) {
126
                $this->logger->error($exception);
127
            }
128
129
            throw new UnauthorizedException('', 0, $exception);
130
        }
131
    }
132
133
    protected function token(): ?string
134
    {
135
        return $this->cache->remember('acquiropay_api_token_'.md5($this->url), 10, function () {
136
            $response = $this->http->post($this->url.'/login', ['form_params' => ['username' => $this->username, 'password' => $this->password]]);
137
138
            return (string) $response->getBody();
139
        });
140
    }
141
}
142