MapGenerator::generate()   A
last analyzed

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 LogicException;
15
use Symfony\Component\Filesystem\Exception\IOException;
16
use Symfony\Component\Filesystem\Filesystem;
17
18
class MapGenerator
19
{
20
    /**
21
     * @var string
22
     */
23
    private const MAP_FILENAME = 'dkim_selectors.map';
24
    private string $path;
25
    private Filesystem $filesystem;
26
27
    public function __construct(string $path)
28
    {
29
        $this->path = $path;
30
        $this->filesystem = new Filesystem();
31
    }
32
33
    public function generate(Domain ...$domains): void
34
    {
35
        $map = [];
36
37
        foreach ($domains as $domain) {
38
            if ($domain->getDkimEnabled()
39
                && !empty($domain->getDkimPrivateKey())
40
                && !empty($domain->getDkimSelector())) {
41
                $this->writePrivateKey($domain);
42
                $map[] = \sprintf('%s %s', $domain->getName(), $domain->getDkimSelector());
43
            }
44
        }
45
46
        $map[] = '';
47
        $this->writeFile(\sprintf('%s/%s', $this->path, static::MAP_FILENAME), \implode(\PHP_EOL, $map));
48
    }
49
50
    private function writePrivateKey(Domain $domain): void
51
    {
52
        $filename = \sprintf('%s/%s.%s.key', $this->path, $domain->getName(), $domain->getDkimSelector());
53
54
        $this->writeFile($filename, $domain->getDkimPrivateKey());
55
    }
56
57
    private function writeFile(string $filename, string $content): void
58
    {
59
        if (false === \file_put_contents($filename, $content)) {
60
            throw new LogicException(\sprintf('Cannot write %s', $filename));
61
        }
62
63
        try {
64
            $this->filesystem->chmod($filename, 0666);
65
        } catch (IOException $iOException) {
66
            // Ignore if different owner.
67
        }
68
    }
69
}
70