Completed
Push — master ( a2e807...f00d56 )
by Vladimir
02:27
created

FrontMatterParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 11
ccs 8
cts 8
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright 2016 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\FrontMatter;
9
10
use allejo\stakx\Utilities\ArrayUtilities;
11
12
class FrontMatterParser
13
{
14
    /**
15
     * The RegEx used to identify Front Matter variables
16
     */
17
    const VARIABLE_DEF = '/(?<!\\\\)%([a-zA-Z]+)/';
18
19
    /**
20
     * A list of special fields in the Front Matter that will support expansion
21
     *
22
     * @var string[]
23
     */
24
    private static $expandableFields = array('permalink');
25
26
    /**
27
     * Whether or not an field was expanded into several values
28
     *
29
     * Only fields specified in $expandableFields will cause this value to be set to true
30
     *
31
     * @var bool
32
     */
33
    private $expansionUsed;
34
35
    /**
36
     * The current depth of the recursion for evaluating nested arrays in the Front Matter
37
     *
38
     * @var int
39
     */
40
    private $nestingLevel;
41
42
    /**
43
     * The current hierarchy of the keys that are being evaluated
44
     *
45
     * Since arrays can be nested, we'll keep track of the keys up until the current depth. This information is used for
46
     * error reporting
47
     *
48
     * @var array
49
     */
50
    private $yamlKeys;
51
52
    /**
53
     * The entire Front Matter block; evaluation will happen in place
54
     *
55
     * @var array
56
     */
57
    private $frontMatter;
58
59
    /**
60
     * FrontMatterParser constructor
61
     *
62
     * @param array $rawFrontMatter
63
     */
64 18
    public function __construct(&$rawFrontMatter)
65
    {
66 18
        $this->expansionUsed = false;
67 18
        $this->nestingLevel = 0;
68 18
        $this->yamlKeys = array();
69
70 18
        $this->frontMatter = &$rawFrontMatter;
71
72 18
        $this->handleSpecialFrontMatter();
73 18
        $this->evaluateBlock($this->frontMatter);
74 12
    }
75
76
    /**
77
     * True if any fields were expanded in the Front Matter block
78
     *
79
     * @return bool
80
     */
81 5
    public function hasExpansion ()
82
    {
83 5
        return $this->expansionUsed;
84
    }
85
86
    //
87
    // Special FrontMatter fields
88
    //
89
90
    /**
91
     * Special treatment for some FrontMatter variables
92
     */
93 18
    private function handleSpecialFrontMatter ()
94
    {
95 18
        $this->handleDateField();
96 18
    }
97
98
    /**
99
     * Special treatment for the `date` field in FrontMatter that creates three new variables: year, month, day
100
     */
101 18
    private function handleDateField ()
102
    {
103 18
        if (!isset($this->frontMatter['date'])) { return; }
104
105 2
        $itemDate = \DateTime::createFromFormat('U', $this->frontMatter['date']);
106
107 2
        if (!$itemDate === false)
108 2
        {
109
            // Localize dates in FrontMatter based on the timezone set in the PHP configuration
110
            $timezone = new \DateTimeZone(date_default_timezone_get());
111
            $localizedDate = new \DateTime($itemDate->format('Y-m-d h:i:s'), $timezone);
112
113
            $this->frontMatter['date']  = $localizedDate->format('U');
114
            $this->frontMatter['year']  = $localizedDate->format('Y');
115
            $this->frontMatter['month'] = $localizedDate->format('m');
116
            $this->frontMatter['day']   = $localizedDate->format('d');
117
        }
118 2
    }
119
120
    //
121
    // Evaluation
122
    //
123
124
    /**
125
     * Evaluate an array as Front Matter
126
     *
127
     * @param array $yaml
128
     */
129 18
    private function evaluateBlock (&$yaml)
130
    {
131 18
        $this->nestingLevel++;
132
133 18
        foreach ($yaml as $key => &$value)
134
        {
135 18
            $this->yamlKeys[$this->nestingLevel] = $key;
136 18
            $keys = implode('.', $this->yamlKeys);
137
138 18
            if (in_array($key, self::$expandableFields, true))
139 18
            {
140 6
                $value = $this->evaluateExpandableField($keys, $value);
141 4
            }
142 17
            else if (is_array($value))
143 17
            {
144 6
                $this->evaluateBlock($value);
145 6
            }
146
            else
147
            {
148 17
                $value = $this->evaluateBasicType($keys, $value);
149
            }
150 15
        }
151
152 14
        $this->nestingLevel--;
153 14
        $this->yamlKeys = array();
154 14
    }
155
156
    /**
157
     * Evaluate an expandable field
158
     *
159
     * @param  string $key
160
     * @param  string $fmStatement
161
     *
162
     * @return array
163
     */
164 6
    private function evaluateExpandableField ($key, $fmStatement)
165
    {
166 6
        if (!is_array($fmStatement))
167 6
        {
168 5
            $fmStatement = array($fmStatement);
169 5
        }
170
171 6
        $wip = array();
172
173 6
        foreach ($fmStatement as $statement)
174
        {
175 6
            $value = $this->evaluateBasicType($key, $statement, true);
176
177
            // Only continue expansion if there are Front Matter variables remain in the string, this means there'll be
178
            // Front Matter variables referencing arrays
179 5
            $expandingVars = $this->getFrontMatterVariables($value);
180 5
            if (!empty($expandingVars))
181 5
            {
182 4
                $value = $this->evaluateArrayType($key, $value, $expandingVars);
183 3
            }
184
185 4
            $wip[] = $value;
186 4
        }
187
188 4
        return $wip;
189
    }
190
191
    /**
192
     * Convert a string or an array into an array of ExpandedValue objects created through "value expansion"
193
     *
194
     * @param  string $frontMatterKey     The current hierarchy of the Front Matter keys being used
195
     * @param  string $expandableValue    The Front Matter value that will be expanded
196
     * @param  array  $arrayVariableNames The Front Matter variable names that reference arrays
197
     *
198
     * @return array
199
     *
200
     * @throws YamlUnsupportedVariableException If a multidimensional array is given for value expansion
201
     */
202 4
    private function evaluateArrayType ($frontMatterKey, $expandableValue, $arrayVariableNames)
203
    {
204 4
        if (!is_array($expandableValue))
205 4
        {
206 4
            $expandableValue = array($expandableValue);
207 4
        }
208
209 4
        $this->expansionUsed = true;
210
211 4
        foreach ($arrayVariableNames as $variable)
212
        {
213 4
            if (ArrayUtilities::is_multidimensional($this->frontMatter[$variable]))
214 4
            {
215 1
                throw new YamlUnsupportedVariableException("Yaml array expansion is not supported with multidimensional arrays with `$variable` for key `$frontMatterKey`");
216
            }
217
218 3
            $wip = array();
219
220 3
            foreach ($expandableValue as &$statement)
221
            {
222 3
                foreach ($this->frontMatter[$variable] as $value)
223
                {
224 3
                    $evaluatedValue = ($statement instanceof ExpandedValue) ? clone($statement) : new ExpandedValue($statement);
225 3
                    $evaluatedValue->setEvaluated(str_replace('%' . $variable, $value, $evaluatedValue->getEvaluated()));
226 3
                    $evaluatedValue->setIterator($variable, $value);
227
228 3
                    $wip[] = $evaluatedValue;
229 3
                }
230 3
            }
231
232 3
            $expandableValue = $wip;
233 3
        }
234
235 3
        return $expandableValue;
236
    }
237
238
    /**
239
     * Evaluate an string for FrontMatter variables and replace them with the corresponding values
240
     *
241
     * @param  string $key          The key of the Front Matter value
242
     * @param  string $string       The string that will be evaluated
243
     * @param  bool   $ignoreArrays When set to true, an exception won't be thrown when an array is found with the
244
     *                              interpolation
245
     *
246
     * @return string The final string with variables evaluated
247
     *
248
     * @throws YamlUnsupportedVariableException A FrontMatter variable is not an int, float, or string
249
     */
250 18
    private function evaluateBasicType ($key, $string, $ignoreArrays = false)
251
    {
252 18
        $variables = $this->getFrontMatterVariables($string);
253
254 18
        foreach ($variables as $variable)
255
        {
256 15
            $value = $this->getVariableValue($key, $variable);
257
258 12
            if (is_array($value) || is_bool($value))
259 12
            {
260 6
                if ($ignoreArrays) { continue; }
261
262 2
                throw new YamlUnsupportedVariableException("Yaml variable `$variable` for `$key` is not a supported data type.");
263
            }
264
265 6
            $string = str_replace('%' . $variable, $value, $string);
266 15
        }
267
268 15
        return $string;
269
    }
270
271
    //
272
    // Variable management
273
    //
274
275
    /**
276
     * Get an array of FrontMatter variables in the specified string that need to be interpolated
277
     *
278
     * @param  string $string
279
     *
280
     * @return string[]
281
     */
282 18
    private function getFrontMatterVariables ($string)
283
    {
284 18
        $variables = array();
285
286 18
        preg_match_all(self::VARIABLE_DEF, $string, $variables);
287
288
        // Default behavior causes $variables[0] is the entire string that was matched. $variables[1] will be each
289
        // matching result individually.
290 18
        return $variables[1];
291
    }
292
293
    /**
294
     * Get the value of a FM variable or throw an exception
295
     *
296
     * @param  string $key
297
     * @param  string $varName
298
     *
299
     * @return mixed
300
     * @throws YamlVariableUndefinedException
301
     */
302 15
    private function getVariableValue ($key, $varName)
303
    {
304 15
        if (!isset($this->frontMatter[$varName]))
305 15
        {
306 3
            throw new YamlVariableUndefinedException("Yaml variable `$varName` is not defined for: $key");
307
        }
308
309 12
        return $this->frontMatter[$varName];
310
    }
311
}