Passed
Pull Request — 1.x (#53)
by Pavel
02:12
created

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