Completed
Push — master ( 1b20ea...0b748b )
by Vladimir
02:26
created

FrontMatterParser::handleDateField()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 5
nop 0
dl 0
loc 27
ccs 15
cts 15
cp 1
crap 4
rs 8.5806
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 21
    public function __construct(&$rawFrontMatter)
65
    {
66 21
        $this->expansionUsed = false;
67 21
        $this->nestingLevel = 0;
68 21
        $this->yamlKeys = array();
69
70 21
        $this->frontMatter = &$rawFrontMatter;
71
72 21
        $this->handleSpecialFrontMatter();
73 21
        $this->evaluateBlock($this->frontMatter);
74 16
    }
75
76
    /**
77
     * True if any fields were expanded in the Front Matter block
78
     *
79
     * @return bool
80
     */
81 6
    public function hasExpansion ()
82
    {
83 6
        return $this->expansionUsed;
84
    }
85
86
    //
87
    // Special FrontMatter fields
88
    //
89
90
    /**
91
     * Special treatment for some FrontMatter variables
92
     */
93 21
    private function handleSpecialFrontMatter ()
94
    {
95 21
        $this->handleDateField();
96 21
    }
97
98
    /**
99
     * Special treatment for the `date` field in FrontMatter that creates three new variables: year, month, day
100
     */
101 21
    private function handleDateField ()
102
    {
103 21
        if (!isset($this->frontMatter['date'])) { return; }
104
105
        try
106
        {
107
            // Coming from a string variable
108 5
            $itemDate = new \DateTime($this->frontMatter['date']);
109
        }
110 5
        catch (\Exception $e)
111
        {
112
            // YAML has parsed them to Epoch time
113 1
            $itemDate = \DateTime::createFromFormat('U', $this->frontMatter['date']);
114
115
            // Localize dates in FrontMatter based on the timezone set in the PHP configuration
116 1
            $timezone = new \DateTimeZone(date_default_timezone_get());
117 1
            $itemDate = new \DateTime($itemDate->format('Y-m-d h:i:s'), $timezone);
118
        }
119
120 5
        if (!$itemDate === false)
121 5
        {
122 5
            $this->frontMatter['date']  = $itemDate->format('U');
123 5
            $this->frontMatter['year']  = $itemDate->format('Y');
124 5
            $this->frontMatter['month'] = $itemDate->format('m');
125 5
            $this->frontMatter['day']   = $itemDate->format('d');
126 5
        }
127 5
    }
128
129
    //
130
    // Evaluation
131
    //
132
133
    /**
134
     * Evaluate an array as Front Matter
135
     *
136
     * @param array $yaml
137
     */
138 21
    private function evaluateBlock (&$yaml)
139
    {
140 21
        $this->nestingLevel++;
141
142 21
        foreach ($yaml as $key => &$value)
143
        {
144 21
            $this->yamlKeys[$this->nestingLevel] = $key;
145 21
            $keys = implode('.', $this->yamlKeys);
146
147 21
            if (in_array($key, self::$expandableFields, true))
148 21
            {
149 6
                $value = $this->evaluateExpandableField($keys, $value);
150 5
            }
151 21
            else if (is_array($value))
152 21
            {
153 6
                $this->evaluateBlock($value);
154 6
            }
155
            else
156
            {
157 21
                $value = $this->evaluateBasicType($keys, $value);
158
            }
159 19
        }
160
161 18
        $this->nestingLevel--;
162 18
        $this->yamlKeys = array();
163 18
    }
164
165
    /**
166
     * Evaluate an expandable field
167
     *
168
     * @param  string $key
169
     * @param  string $fmStatement
170
     *
171
     * @return array
172
     */
173 6
    private function evaluateExpandableField ($key, $fmStatement)
174
    {
175 6
        if (!is_array($fmStatement))
176 6
        {
177 5
            $fmStatement = array($fmStatement);
178 5
        }
179
180 6
        $wip = array();
181
182 6
        foreach ($fmStatement as $statement)
183
        {
184 6
            $value = $this->evaluateBasicType($key, $statement, true);
185
186
            // Only continue expansion if there are Front Matter variables remain in the string, this means there'll be
187
            // Front Matter variables referencing arrays
188 6
            $expandingVars = $this->getFrontMatterVariables($value);
189 6
            if (!empty($expandingVars))
190 6
            {
191 4
                $value = $this->evaluateArrayType($key, $value, $expandingVars);
192 3
            }
193
194 5
            $wip[] = $value;
195 5
        }
196
197 5
        return $wip;
198
    }
199
200
    /**
201
     * Convert a string or an array into an array of ExpandedValue objects created through "value expansion"
202
     *
203
     * @param  string $frontMatterKey     The current hierarchy of the Front Matter keys being used
204
     * @param  string $expandableValue    The Front Matter value that will be expanded
205
     * @param  array  $arrayVariableNames The Front Matter variable names that reference arrays
206
     *
207
     * @return array
208
     *
209
     * @throws YamlUnsupportedVariableException If a multidimensional array is given for value expansion
210
     */
211 4
    private function evaluateArrayType ($frontMatterKey, $expandableValue, $arrayVariableNames)
212
    {
213 4
        if (!is_array($expandableValue))
214 4
        {
215 4
            $expandableValue = array($expandableValue);
216 4
        }
217
218 4
        $this->expansionUsed = true;
219
220 4
        foreach ($arrayVariableNames as $variable)
221
        {
222 4
            if (ArrayUtilities::is_multidimensional($this->frontMatter[$variable]))
223 4
            {
224 1
                throw new YamlUnsupportedVariableException("Yaml array expansion is not supported with multidimensional arrays with `$variable` for key `$frontMatterKey`");
225
            }
226
227 3
            $wip = array();
228
229 3
            foreach ($expandableValue as &$statement)
230
            {
231 3
                foreach ($this->frontMatter[$variable] as $value)
232
                {
233 3
                    $evaluatedValue = ($statement instanceof ExpandedValue) ? clone($statement) : new ExpandedValue($statement);
234 3
                    $evaluatedValue->setEvaluated(str_replace('%' . $variable, $value, $evaluatedValue->getEvaluated()));
235 3
                    $evaluatedValue->setIterator($variable, $value);
236
237 3
                    $wip[] = $evaluatedValue;
238 3
                }
239 3
            }
240
241 3
            $expandableValue = $wip;
242 3
        }
243
244 3
        return $expandableValue;
245
    }
246
247
    /**
248
     * Evaluate an string for FrontMatter variables and replace them with the corresponding values
249
     *
250
     * @param  string $key          The key of the Front Matter value
251
     * @param  string $string       The string that will be evaluated
252
     * @param  bool   $ignoreArrays When set to true, an exception won't be thrown when an array is found with the
253
     *                              interpolation
254
     *
255
     * @return string The final string with variables evaluated
256
     *
257
     * @throws YamlUnsupportedVariableException A FrontMatter variable is not an int, float, or string
258
     */
259 21
    private function evaluateBasicType ($key, $string, $ignoreArrays = false)
260
    {
261 21
        $variables = $this->getFrontMatterVariables($string);
262
263 21
        foreach ($variables as $variable)
264
        {
265 15
            $value = $this->getVariableValue($key, $variable);
266
267 13
            if (is_array($value) || is_bool($value))
268 13
            {
269 6
                if ($ignoreArrays) { continue; }
270
271 2
                throw new YamlUnsupportedVariableException("Yaml variable `$variable` for `$key` is not a supported data type.");
272
            }
273
274 7
            $string = str_replace('%' . $variable, $value, $string);
275 19
        }
276
277 19
        return $string;
278
    }
279
280
    //
281
    // Variable management
282
    //
283
284
    /**
285
     * Get an array of FrontMatter variables in the specified string that need to be interpolated
286
     *
287
     * @param  string $string
288
     *
289
     * @return string[]
290
     */
291 21
    private function getFrontMatterVariables ($string)
292
    {
293 21
        $variables = array();
294
295 21
        preg_match_all(self::VARIABLE_DEF, $string, $variables);
296
297
        // Default behavior causes $variables[0] is the entire string that was matched. $variables[1] will be each
298
        // matching result individually.
299 21
        return $variables[1];
300
    }
301
302
    /**
303
     * Get the value of a FM variable or throw an exception
304
     *
305
     * @param  string $key
306
     * @param  string $varName
307
     *
308
     * @return mixed
309
     * @throws YamlVariableUndefinedException
310
     */
311 15
    private function getVariableValue ($key, $varName)
312
    {
313 15
        if (!isset($this->frontMatter[$varName]))
314 15
        {
315 2
            throw new YamlVariableUndefinedException("Yaml variable `$varName` is not defined for: $key");
316
        }
317
318 13
        return $this->frontMatter[$varName];
319
    }
320
}