Passed
Push — 1.x ( b11e7c...6ab60f )
by Pavel
01:56
created

DigiSign::deliveries()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DigitalCz\DigiSign;
6
7
use DigitalCz\DigiSign\Auth\ApiKeyCredentials;
8
use DigitalCz\DigiSign\Auth\CachedCredentials;
9
use DigitalCz\DigiSign\Auth\Credentials;
10
use DigitalCz\DigiSign\Endpoint\AccountEndpoint;
11
use DigitalCz\DigiSign\Endpoint\AuthEndpoint;
12
use DigitalCz\DigiSign\Endpoint\DeliveriesEndpoint;
13
use DigitalCz\DigiSign\Endpoint\EndpointInterface;
14
use DigitalCz\DigiSign\Endpoint\EnumsEndpoint;
15
use DigitalCz\DigiSign\Endpoint\EnvelopesEndpoint;
16
use DigitalCz\DigiSign\Endpoint\EnvelopeTemplatesEndpoint;
17
use DigitalCz\DigiSign\Endpoint\FilesEndpoint;
18
use DigitalCz\DigiSign\Endpoint\ImagesEndpoint;
19
use DigitalCz\DigiSign\Endpoint\WebhooksEndpoint;
20
use InvalidArgumentException;
21
use LogicException;
22
use Psr\Http\Message\ResponseInterface;
23
use Psr\SimpleCache\CacheInterface;
24
25
final class DigiSign implements EndpointInterface
26
{
27
    public const VERSION = '1.0.2';
28
    public const API_BASE = 'https://api.digisign.org';
29
    public const API_BASE_TESTING = 'https://api.digisign.digital.cz';
30
31
    /** @var string The base URL for requests */
32
    private $apiBase = self::API_BASE;
33
34
    /** @var Credentials The credentials used to authenticate to API */
35
    private $credentials;
36
37
    /** @var DigiSignClient The client used to send requests */
38
    private $client;
39
40
    /** @var array<string, string> */
41
    private $versions = [];
42
43
    /**
44
     * Available options:
45
     *  access_key      - string; ApiKey access key
46
     *  secret_key      - string; ApiKey secret key
47
     *  credentials     - DigitalCz\DigiSign\Auth\Credentials instance
48
     *  client          - DigitalCz\DigiSign\DigiSignClient instance with your custom PSR17/18 objects
49
     *  http_client     - Psr\Http\Client\ClientInterface instance of your custom PSR18 client
50
     *  cache           - Psr\SimpleCache\CacheInterface for caching Credentials auth Tokens
51
     *  testing         - bool; whether to use testing or production API
52
     *  api_base        - string; override the base API url
53
     *
54
     * @param mixed[] $options
55
     */
56
    public function __construct(array $options = [])
57
    {
58
        $httpClient = $options['http_client'] ?? null;
59
        $this->setClient($options['client'] ?? new DigiSignClient($httpClient));
60
        $this->useTesting($options['testing'] ?? false);
61
        $this->addVersion('digitalcz/digisign', self::VERSION);
62
        $this->addVersion('PHP', PHP_VERSION);
63
64
        if (isset($options['api_base'])) {
65
            if (!is_string($options['api_base'])) {
66
                throw new InvalidArgumentException('Invalid value for "api_base" option');
67
            }
68
69
            $this->setApiBase($options['api_base']);
70
        }
71
72
        if (isset($options['access_key'], $options['secret_key'])) {
73
            $this->setCredentials(new ApiKeyCredentials($options['access_key'], $options['secret_key']));
74
        }
75
76
        if (isset($options['credentials'])) {
77
            if (!$options['credentials'] instanceof Credentials) {
78
                throw new InvalidArgumentException('Invalid value for "credentials" option');
79
            }
80
81
            $this->setCredentials($options['credentials']);
82
        }
83
84
        // if cache is provided, wrap Credentials with cache decorator
85
        if (isset($options['cache'])) {
86
            if (!$options['cache'] instanceof CacheInterface) {
87
                throw new InvalidArgumentException('Invalid value for "cache" option');
88
            }
89
90
            $this->setCache($options['cache']);
91
        }
92
    }
93
94
    public function setCache(CacheInterface $cache): void
95
    {
96
        $credentials = $this->getCredentials();
97
98
        // if credentials are already decorated, do not double wrap, but get inner
99
        if ($credentials instanceof CachedCredentials) {
100
            $credentials = $credentials->getInner();
101
        }
102
103
        $this->setCredentials(new CachedCredentials($credentials, $cache));
104
    }
105
106
    public function getCredentials(): Credentials
107
    {
108
        if (!isset($this->credentials)) {
109
            throw new LogicException(
110
                'No credentials were provided, Please use setCredentials() ' .
111
                'or constructor options to set them.'
112
            );
113
        }
114
115
        return $this->credentials;
116
    }
117
118
    public function setCredentials(Credentials $credentials): void
119
    {
120
        $this->credentials = $credentials;
121
    }
122
123
    public function setClient(DigiSignClient $client): void
124
    {
125
        $this->client = $client;
126
    }
127
128
    public function useTesting(bool $bool = true): void
129
    {
130
        if ($bool) {
131
            $this->setApiBase(self::API_BASE_TESTING);
132
        } else {
133
            $this->setApiBase(self::API_BASE);
134
        }
135
    }
136
137
    public function setApiBase(string $apiBase): void
138
    {
139
        $this->apiBase = rtrim(trim($apiBase), '/');
140
    }
141
142
    public function addVersion(string $tool, string $version = ''): void
143
    {
144
        $this->versions[$tool] = $version;
145
    }
146
147
    public function removeVersion(string $tool): void
148
    {
149
        unset($this->versions[$tool]);
150
    }
151
152
    /** @inheritDoc */
153
    public function request(string $method, string $path = '', array $options = []): ResponseInterface
154
    {
155
        $options['user-agent'] = $this->createUserAgent();
156
157
        // disable authorization header if options[no_auth]=true
158
        if (($options['no_auth'] ?? false) !== true) {
159
            $options['auth_bearer'] = $this->createBearer();
160
        }
161
162
        return $this->client->request($method, $this->apiBase . $path, $options);
163
    }
164
165
    public function auth(): AuthEndpoint
166
    {
167
        return new AuthEndpoint($this);
168
    }
169
170
    public function account(): AccountEndpoint
171
    {
172
        return new AccountEndpoint($this);
173
    }
174
175
    public function envelopes(): EnvelopesEndpoint
176
    {
177
        return new EnvelopesEndpoint($this);
178
    }
179
180
    public function envelopeTemplates(): EnvelopeTemplatesEndpoint
181
    {
182
        return new EnvelopeTemplatesEndpoint($this);
183
    }
184
185
    public function deliveries(): DeliveriesEndpoint
186
    {
187
        return new DeliveriesEndpoint($this);
188
    }
189
190
    public function files(): FilesEndpoint
191
    {
192
        return new FilesEndpoint($this);
193
    }
194
195
    public function images(): ImagesEndpoint
196
    {
197
        return new ImagesEndpoint($this);
198
    }
199
200
    public function webhooks(): WebhooksEndpoint
201
    {
202
        return new WebhooksEndpoint($this);
203
    }
204
205
    public function enums(): EnumsEndpoint
206
    {
207
        return new EnumsEndpoint($this);
208
    }
209
210
    private function createUserAgent(): string
211
    {
212
        $userAgent = '';
213
214
        foreach ($this->versions as $tool => $version) {
215
            $userAgent .= $tool;
216
            $userAgent .= $version !== '' ? ":$version" : '';
217
            $userAgent .= ' ';
218
        }
219
220
        return $userAgent;
221
    }
222
223
    private function createBearer(): string
224
    {
225
        return $this->getCredentials()->provide($this)->getToken();
226
    }
227
}
228