Completed
Push — master ( 771e5d...491b8d )
by Jeff
02:21
created

LeftoverFileCleaner::clean()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 9
nop 1
dl 0
loc 20
rs 8.8333
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\Config;
12
13
use App\Entity\Domain;
14
use Symfony\Component\Filesystem\Filesystem;
15
use Symfony\Component\Finder\Finder;
16
17
class LeftoverFileCleaner
18
{
19
    private $path;
20
    private $filesystem;
21
22
    public function __construct(string $path)
23
    {
24
        $this->path = $path;
25
        $this->filesystem = new Filesystem();
26
    }
27
28
    public function clean(Domain ...$domains): void
29
    {
30
        $finder = new Finder();
31
        $finder
32
            ->in($this->path)
33
            ->name('*.key')
34
            ->files();
35
36
        $except = [];
37
        foreach ($domains as $domain) {
38
            if ($domain->getDkimEnabled()
39
                && !empty($domain->getDkimPrivateKey())
40
                && !empty($domain->getDkimSelector())) {
41
                $except[] = \sprintf('%s.%s.key', $domain->getName(), $domain->getDkimSelector());
42
            }
43
        }
44
45
        foreach ($finder as $fileInfo) {
46
            if (!\in_array($fileInfo->getFilename(), $except, true)) {
47
                $this->filesystem->remove($fileInfo->getPathname());
48
            }
49
        }
50
    }
51
}
52