aboutsummaryrefslogtreecommitdiff
path: root/src/Compiler/Compiler.php
blob: 28b60e4c697207b6fd26eec85954fb7a63fec2e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
declare(strict_types=1);

/**
 * @author: Alexander Kiryukhin <alexander@kiryukhin.su>
 * @license: MIT
 */

namespace NeonXP\Dotenv\Compiler;

use NeonXP\Dotenv\Exception\RuntimeException;

/**
 * Class Compiler
 * @package NeonXP\Dotenv\Compiler
 */
class Compiler implements CompilerInterface
{
    const REGEX_VARIABLE = '/\$\{(.+?)\}/';

    /**
     * @var array[]
     */
    protected $collection = [];

    /**
     * @var array[]
     */
    protected $cache = [];

    /**
     * @inheritdoc
     * @param array[] $collection
     */
    public function setRawCollection(array $collection): void
    {
        $this->collection = [];
        $this->cache = [];
        foreach ($collection as $array) {
            $this->collection[$array['key']] = $array;
        }
    }

    /**
     * @inheritdoc
     * @param array $array
     * @return array
     */
    public function compile(array $array): array
    {
        $newValue = preg_replace_callback(self::REGEX_VARIABLE, function ($variable) use ($array) {
            $variable = $variable[1];
            if ($variable === $array['key']) {
                throw new RuntimeException('Self referencing');
            }
            if (isset($this->cache[$variable])) {
                return $this->cache[$variable]['value'];
            } elseif (isset($this->collection[$variable]) && !$this->needToCompile($this->collection[$variable])) {
                return $this->collection[$variable]['value'];
            } elseif (isset($this->collection[$variable]) && $this->needToCompile($this->collection[$variable])) {
                return $this->compile($this->collection[$variable])['value'];
            }
            return "UNKNOWN VARIABLE {$variable}";
        }, $array['value']);
        $result = [
            'key' => $array['key'],
            'value' => $newValue
        ];
        $this->cache[$result['key']] = $result;

        return $result;
    }

    /**
     * @param array $array
     * @return bool
     */
    protected function needToCompile(array $array): bool
    {
        return !!preg_match(self::REGEX_VARIABLE, $array['value']);
    }
}