Passed
Push — master ( c2f764...cba0ea )
by Pol
02:10
created

Exporter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
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 6
cts 6
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
/**
14
 * Class Exporter.
15
 */
16
abstract class Exporter implements ExporterInterface
17
{
18
    /**
19
     * @var \Composer\Script\Event
20
     */
21
    private $event;
22
23
    /**
24
     * @var \Twig\Environment
25
     */
26
    private $twig;
27
28
    /**
29
     * Exporter constructor.
30
     *
31
     * @param \Composer\Script\Event $event
32
     */
33 2
    public function __construct(Event $event)
34
    {
35 2
        $this->twig = new Environment(
36 2
            new FilesystemLoader(__DIR__ . '/../../templates')
37
        );
38
39 2
        $this->twig->addExtension(new CamelCaseExtension());
40 2
        $this->twig->addExtension(new VarExportExtension());
41
42 2
        $this->event = $event;
43 2
    }
44
45
    /**
46
     * @param string $template
47
     * @param string $destination
48
     *
49
     * @throws \Twig\Error\LoaderError
50
     * @throws \Twig\Error\RuntimeError
51
     * @throws \Twig\Error\SyntaxError
52
     */
53 2
    public function exportToFile(string $template, string $destination): void
54
    {
55 2
        $data = $this->exportToArray() + [
56 2
            'generatedAt' => \time(),
57 2
            'rootPackageName' => $this->getEvent()->getComposer()->getPackage()->getName(),
58
        ];
59
60 2
        $installPathTmp = \sprintf(
61 2
            '%s_%s',
62 2
            $destination,
63 2
            \uniqid('tmp', true)
64
        );
65
66 2
        \file_put_contents(
67 2
            $installPathTmp,
68 2
            $this->twig->render(
69 2
                $template,
70 2
                $data
71
            )
72
        );
73 2
        \chmod($installPathTmp, 0664);
74 2
        \rename($installPathTmp, $destination);
75 2
    }
76
77
    /**
78
     * @return \Composer\Script\Event
79
     */
80 2
    protected function getEvent(): Event
81
    {
82 2
        return $this->event;
83
    }
84
}
85