Account::exists()   A
last analyzed

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
namespace Rogierw\RwAcme\Endpoints;
4
5
use Rogierw\RwAcme\DTO\AccountData;
6
use Rogierw\RwAcme\Exceptions\LetsEncryptClientException;
7
use Rogierw\RwAcme\Http\Response;
8
use Rogierw\RwAcme\Support\JsonWebSignature;
9
10
class Account extends Endpoint
11
{
12
    public function exists(): bool
13
    {
14
        return $this->client->localAccount()->exists();
15
    }
16
17
    public function create(): AccountData
18
    {
19
        $this->client->localAccount()->generateNewKeys();
20
21
        $payload = [
22
            'termsOfServiceAgreed' => true,
23
        ];
24
25
        $response = $this->postToAccountUrl($payload);
26
27
        if ($response->getHttpResponseCode() === 201 && $response->hasHeader('location')) {
28
            return AccountData::fromResponse($response);
29
        }
30
31
        $this->throwError($response, 'Creating account failed');
32
    }
33
34
    public function get(): AccountData
35
    {
36
        if (!$this->exists()) {
37
            throw new LetsEncryptClientException('Local account keys not found.');
38
        }
39
40
        // Use the newAccountUrl to get the account data based on the key.
41
        // See https://datatracker.ietf.org/doc/html/rfc8555#section-7.3.1
42
        $payload = ['onlyReturnExisting' => true];
43
        $response = $this->postToAccountUrl($payload);
44
45
        if ($response->getHttpResponseCode() === 200) {
46
            return AccountData::fromResponse($response);
47
        }
48
49
        $this->throwError($response, 'Retrieving account failed');
50
    }
51
52
    private function signPayload(array $payload): array
53
    {
54
        return JsonWebSignature::generate(
55
            $payload,
56
            $this->client->directory()->newAccount(),
57
            $this->client->nonce()->getNew(),
58
            $this->client->localAccount()->getPrivateKey(),
59
        );
60
    }
61
62
    private function postToAccountUrl(array $payload): Response
63
    {
64
        return $this->client->getHttpClient()->post(
65
            $this->client->directory()->newAccount(),
66
            $this->signPayload($payload)
67
        );
68
    }
69
70
    protected function throwError(Response $response, string $defaultMessage): never
71
    {
72
        $message = $response->getBody()['details'] ?? $defaultMessage;
73
        $this->logResponse('error', $message, $response);
74
75
        throw new LetsEncryptClientException($message);
76
    }
77
}
78