Exporter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 10
ccs 1
cts 1
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace drupol\ComposerPackages\Exporter;
6
7
use Composer\Script\Event;
8
use drupol\ComposerPackages\Twig\CamelCaseExtension;
9
use drupol\ComposerPackages\Twig\VarExportExtension;
10
use Twig\Environment;
11
use Twig\Loader\FilesystemLoader;
12
13
use function dirname;
14
15
abstract class Exporter implements ExporterInterface
16
{
17
    private Event $event;
18
19
    private Environment $twig;
20
21
    public function __construct(Event $event)
22
    {
23
        $this->twig = new Environment(
24
            new FilesystemLoader(dirname(__DIR__) . '/templates')
25
        );
26
27
        $this->twig->addExtension(new CamelCaseExtension());
28
        $this->twig->addExtension(new VarExportExtension());
29
30 2
        $this->event = $event;
31
    }
32 2
33 2
    /**
34
     * @throws \Twig\Error\LoaderError
35
     * @throws \Twig\Error\RuntimeError
36 2
     * @throws \Twig\Error\SyntaxError
37 2
     */
38
    public function exportToFile(string $template, string $destination): void
39 2
    {
40 2
        $data = $this->exportToArray() + [
41
            'generatedAt' => time(),
42
            'rootPackageName' => $this->getEvent()->getComposer()->getPackage()->getName(),
43
        ];
44
45
        $installPathTmp = sprintf(
46
            '%s_%s',
47
            $destination,
48
            uniqid('tmp', true)
49
        );
50 2
51
        file_put_contents(
52 2
            $installPathTmp,
53 2
            $this->twig->render(
54 2
                $template,
55
                $data
56
            )
57 2
        );
58 2
        chmod($installPathTmp, 0664);
59 2
        rename($installPathTmp, $destination);
60 2
    }
61
62
    protected function getEvent(): Event
63 2
    {
64 2
        return $this->event;
65 2
    }
66
}
67