DKIMStatusService::getStatus()   A
last analyzed

Complexity

Conditions 6
Paths 17

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 16
c 1
b 0
f 0
nc 17
nop 1
dl 0
loc 27
rs 9.1111
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * This file is part of the mailserver-admin package.
6
 * (c) Jeffrey Boehm <https://github.com/jeboehm/mailserver-admin>
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace App\Service\DKIM;
12
13
use App\Entity\Domain;
14
use App\Exception\DKIM\DomainKeyNotFoundException;
15
16
class DKIMStatusService
17
{
18
    private DomainKeyReaderService $domainKeyReaderService;
19
20
    private FormatterService $formatterService;
21
22
    private KeyGenerationService $keyGenerationService;
23
24
    public function __construct(
25
        DomainKeyReaderService $domainKeyReaderService,
26
        FormatterService $formatterService,
27
        KeyGenerationService $keyGenerationService
28
    ) {
29
        $this->domainKeyReaderService = $domainKeyReaderService;
30
        $this->formatterService = $formatterService;
31
        $this->keyGenerationService = $keyGenerationService;
32
    }
33
34
    public function getStatus(Domain $domain): DKIMStatus
35
    {
36
        if (empty($domain->getDkimPrivateKey()) || empty($domain->getDkimSelector())) {
37
            return new DKIMStatus($domain->getDkimEnabled(), false, false, '');
38
        }
39
40
        try {
41
            $key = $this->domainKeyReaderService->getDomainKey($domain->getName(), $domain->getDkimSelector());
42
            $parts = [];
43
44
            foreach ($key as $name => $value) {
45
                $parts[] = sprintf('%s=%s', $name, $value);
46
            }
47
48
            $dnsRecord = \implode('\; ', $parts);
49
            $generatedRecord = $this->formatterService->getTXTRecord(
50
                $this->keyGenerationService->extractPublicKey($domain->getDkimPrivateKey()),
51
                KeyGenerationService::DIGEST_ALGORITHM
52
            );
53
54
            if ($dnsRecord === $generatedRecord) {
55
                return new DKIMStatus($domain->getDkimEnabled(), true, true, $dnsRecord);
56
            }
57
58
            return new DKIMStatus($domain->getDkimEnabled(), true, false, $dnsRecord);
59
        } catch (DomainKeyNotFoundException $domainKeyNotFoundException) {
60
            return new DKIMStatus($domain->getDkimEnabled(), false, false, '');
61
        }
62
    }
63
}
64