Passed
Push — master ( 05df7e...26e065 )
by Jeff
02:40
created

AppSecretGeneratorCompilerPass::createSecret()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 11
rs 10
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\DependencyInjection\Compiler;
12
13
use RuntimeException;
14
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
15
use Symfony\Component\DependencyInjection\ContainerBuilder;
16
17
class AppSecretGeneratorCompilerPass implements CompilerPassInterface
18
{
19
    public function process(ContainerBuilder $container): void
20
    {
21
        $projectDir = $container->getParameter('kernel.project_dir');
22
        $secretPath = sprintf('%s/var/app.secret', $projectDir);
23
        $secret = null;
24
25
        if (is_readable($secretPath)) {
26
            $secret = file_get_contents($secretPath);
27
28
            if (!$secret || strlen($secret) < 8) {
29
                $secret = null;
30
            }
31
        }
32
33
        if (!$secret) {
34
            $secret = $this->createSecret($secretPath);
35
        }
36
37
        $container->setParameter('env(APP_SECRET)', $secret);
38
    }
39
40
    private function createSecret(string $secretPath): string
41
    {
42
        $secret = random_bytes(128);
43
        $secret = sha1($secret);
44
        $secret = substr($secret, 0, 9);
45
46
        if (!file_put_contents($secretPath, $secret)) {
47
            throw new RuntimeException(sprintf('Cannot write APP_SECRET file: %s', $secretPath));
48
        }
49
50
        return $secret;
51
    }
52
}
53