Completed
Push — master ( 33ec04...ed9cfc )
by Bart
11s
created

Data::toYaml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Models;
4
5
use Exception;
6
use craft\base\Model;
7
use Symfony\Component\Yaml\Yaml;
8
9
/**
10
 * Schematic Data Model.
11
 *
12
 * Encapsulates data that has been exported via schematic.
13
 *
14
 * @author    Nerds & Company
15
 * @copyright Copyright (c) 2015-2018, Nerds & Company
16
 * @license   MIT
17
 *
18
 * @see      http://www.nerds.company
19
 */
20
class Data extends Model
21
{
22
    /**
23
     * Parse a yaml file.
24
     *
25
     * @param string $yaml
26
     * @param string $overrideYaml
27
     *
28
     * @return array
29
     */
30 5
    public static function fromYaml($yaml, $overrideYaml): array
31
    {
32 5
        $data = Yaml::parse($yaml);
33 5
        if (!empty($overrideYaml)) {
34 5
            $overrideYaml = static::replaceEnvVariables($overrideYaml);
35 4
            $overrideData = Yaml::parse($overrideYaml);
36 4
            if (null != $overrideData) {
37 4
                $data = array_replace_recursive($data, $overrideData);
38
            }
39
        }
40
41 4
        return $data;
42
    }
43
44
    /**
45
     * Replace placeholders with enviroment variables.
46
     *
47
     * Placeholders start with % and end with %. This will be replaced by the
48
     * environment variable with the name SCHEMATIC_{PLACEHOLDER}. If the
49
     * environment variable is not set an exception will be thrown.
50
     *
51
     * @param string $yaml
52
     *
53
     * @return string
54
     *
55
     * @throws Exception
56
     */
57 5
    public static function replaceEnvVariables($yaml): string
58
    {
59 5
        $matches = null;
60 5
        preg_match_all('/%\w+%/', $yaml, $matches);
61 5
        $originalValues = $matches[0];
62 5
        $replaceValues = [];
63 5
        foreach ($originalValues as $match) {
64 5
            $envVariable = strtoupper(substr($match, 1, -1));
65 5
            $envVariable = 'SCHEMATIC_'.$envVariable;
66 5
            $envValue = getenv($envVariable);
67 5
            if (!$envValue) {
68 1
                throw new Exception("Schematic environment variable not set: {$envVariable}");
69
            }
70 4
            $replaceValues[] = $envValue;
71
        }
72
73 4
        return str_replace($originalValues, $replaceValues, $yaml);
74
    }
75
76
    /**
77
     * Convert array to yaml.
78
     *
79
     * @param array $data
80
     *
81
     * @return string
82
     */
83 2
    public static function toYaml(array $data): string
84
    {
85 2
        return Yaml::dump($data, 12, 2);
86
    }
87
}
88