Completed
Push — master ( 7c30e2...607b79 )
by Jeff
26s queued 11s
created

MapGenerator::generate()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 15
rs 9.6111
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\Config;
12
13
use App\Entity\Domain;
14
use Symfony\Component\Filesystem\Exception\IOException;
15
use Symfony\Component\Filesystem\Filesystem;
16
17
class MapGenerator
18
{
19
    private const MAP_FILENAME = 'dkim_selectors.map';
20
    private $path;
21
    private $filesystem;
22
23
    public function __construct(string $path)
24
    {
25
        $this->path = $path;
26
        $this->filesystem = new Filesystem();
27
    }
28
29
    public function generate(Domain ...$domains): void
30
    {
31
        $map = [];
32
33
        foreach ($domains as $domain) {
34
            if ($domain->getDkimEnabled()
35
                && !empty($domain->getDkimPrivateKey())
36
                && !empty($domain->getDkimSelector())) {
37
                $this->writePrivateKey($domain);
38
                $map[] = \sprintf('%s %s', $domain->getName(), $domain->getDkimSelector());
39
            }
40
        }
41
42
        $map[] = '';
43
        $this->writeFile(\sprintf('%s/%s', $this->path, static::MAP_FILENAME), \implode(\PHP_EOL, $map));
44
    }
45
46
    private function writePrivateKey(Domain $domain): void
47
    {
48
        $filename = \sprintf('%s/%s.%s.key', $this->path, $domain->getName(), $domain->getDkimSelector());
49
50
        $this->writeFile($filename, $domain->getDkimPrivateKey());
51
    }
52
53
    private function writeFile(string $filename, string $content): void
54
    {
55
        if (false === \file_put_contents($filename, $content)) {
56
            throw new \LogicException(\sprintf('Cannot write %s', $filename));
57
        }
58
59
        try {
60
            $this->filesystem->chmod($filename, 0666);
61
        } catch (IOException $e) {
62
            // Ignore if different owner.
63
        }
64
    }
65
}
66