Completed
Pull Request — master (#2)
by Jeff
03:11
created

DKIMStatusService::getStatus()   A

Complexity

Conditions 6
Paths 17

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 16
nc 17
nop 1
dl 0
loc 27
rs 9.1111
c 0
b 0
f 0
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
    /** @var DomainKeyReaderService */
19
    private $domainKeyReaderService;
20
21
    /** @var FormatterService */
22
    private $formatterService;
23
24
    /** @var KeyGenerationService */
25
    private $keyGenerationService;
26
27
    public function __construct(
28
        DomainKeyReaderService $domainKeyReaderService,
29
        FormatterService $formatterService,
30
        KeyGenerationService $keyGenerationService
31
    ) {
32
        $this->domainKeyReaderService = $domainKeyReaderService;
33
        $this->formatterService = $formatterService;
34
        $this->keyGenerationService = $keyGenerationService;
35
    }
36
37
    public function getStatus(Domain $domain): DKIMStatus
38
    {
39
        if (empty($domain->getDkimPrivateKey()) || empty($domain->getDkimSelector())) {
40
            return new DKIMStatus($domain->getDkimEnabled(), false, false, '');
41
        }
42
43
        try {
44
            $key = $this->domainKeyReaderService->getDomainKey($domain->getName(), $domain->getDkimSelector());
45
            $parts = [];
46
47
            foreach ($key as $name => $value) {
48
                $parts[] = sprintf('%s=%s', $name, $value);
49
            }
50
51
            $dnsRecord = \implode('\; ', $parts);
52
            $generatedRecord = $this->formatterService->getTXTRecord(
53
                $this->keyGenerationService->extractPublicKey($domain->getDkimPrivateKey()),
54
                KeyGenerationService::DIGEST_ALGORITHM
55
            );
56
57
            if ($dnsRecord === $generatedRecord) {
58
                return new DKIMStatus($domain->getDkimEnabled(), true, true, $dnsRecord);
59
            }
60
61
            return new DKIMStatus($domain->getDkimEnabled(), true, false, $dnsRecord);
62
        } catch (DomainKeyNotFoundException $e) {
63
            return new DKIMStatus($domain->getDkimEnabled(), false, false, '');
64
        }
65
    }
66
}
67