Completed
Pull Request — master (#20)
by Vladimir
02:54
created

FrontMatterObject::evaluateYamlVar()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 2
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
ccs 12
cts 12
cp 1
crap 3
1
<?php
2
3
namespace allejo\stakx\Object;
4
5
use allejo\stakx\FrontMatter\FrontMatterParser;
6
use allejo\stakx\FrontMatter\YamlVariableUndefinedException;
7
use allejo\stakx\System\Filesystem;
8
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
9
use Symfony\Component\Filesystem\Exception\IOException;
10
use Symfony\Component\Yaml\Yaml;
11
12
abstract class FrontMatterObject
13
{
14
    /**
15
     * An array to keep track of collection or data dependencies used inside of a Twig template
16
     *
17
     * $dataDependencies['collections'] = array()
18
     * $dataDependencies['data'] = array()
19
     *
20
     * @var array
21
     */
22
    protected $dataDependencies;
23
24
    /**
25
     * A list of Front Matter values that should not be returned directly from the $frontMatter array. Values listed
26
     * here have dedicated functions that handle those Front Matter values and the respective functions should be called
27
     * instead.
28
     *
29
     * @var string[]
30
     */
31
    protected $frontMatterBlacklist;
32
33
    /**
34
     * Set to true if the front matter has already been evaluated with variable interpolation
35
     *
36
     * @var bool
37
     */
38
    protected $frontMatterEvaluated;
39
40
    /**
41
     * @var FrontMatterParser
42
     */
43
    protected $frontMatterParser;
44
45
    /**
46
     * An array containing the Yaml of the file
47
     *
48
     * @var array
49
     */
50
    protected $frontMatter;
51
52
    /**
53
     * Set to true if the body has already been parsed as markdown or any other format
54
     *
55
     * @var bool
56
     */
57
    protected $bodyContentEvaluated;
58
59
    /**
60
     * Only the body of the file, i.e. the content
61
     *
62
     * @var string
63
     */
64
    protected $bodyContent;
65
66
    /**
67
     * The extension of the file
68
     *
69
     * @var string
70
     */
71
    protected $extension;
72
73
    /**
74
     * The original file path to the ContentItem
75
     *
76
     * @var string
77
     */
78
    protected $filePath;
79
80
    /**
81
     * A filesystem object
82
     *
83
     * @var Filesystem
84
     */
85
    protected $fs;
86
87
    /**
88
     * The permalink for this object
89
     *
90
     * @var string
91
     */
92
    private $permalink;
93
94
    /**
95
     * A list URLs that will redirect to this object
96
     *
97
     * @var string[]
98
     */
99
    private $redirects;
100
101
    /**
102
     * ContentItem constructor.
103
     *
104 29
     * @param string $filePath The path to the file that will be parsed into a ContentItem
105
     *
106 29
     * @throws FileNotFoundException The given file path does not exist
107
     * @throws IOException           The file was not a valid ContentItem. This would meam there was no front matter or
108 29
     *                               no body
109 29
     */
110
    public function __construct ($filePath)
111 29
    {
112 29
        $this->frontMatterBlacklist = array('permalink', 'redirects');
113 1
114
        $this->filePath  = $filePath;
115
        $this->fs        = new Filesystem();
116
117
        if (!$this->fs->exists($filePath))
118
        {
119
            throw new FileNotFoundException("The following file could not be found: ${filePath}");
120
        }
121
122
        $this->extension = strtolower($this->fs->getExtension($filePath));
123
124
        $this->refreshFileContent();
125
    }
126
127
    /**
128
     * The magic getter returns values from the front matter in order to make these values accessible to Twig templates
129
     * in a simple fashion
130
     *
131 3
     * @param  string $name The key in the front matter
132
     *
133
     * @return mixed|null
134
     */
135
    public function __get ($name)
136
    {
137
        return (array_key_exists($name, $this->frontMatter) ? $this->frontMatter[$name] : null);
138
    }
139
140
    /**
141
     * The magic getter returns true if the value exists in the Front Matter. This is used in conjunction with the __get
142
     * function
143
     *
144 1
     * @param  string $name The name of the Front Matter value being looked for
145
     *
146
     * @return bool
147
     */
148
    public function __isset ($name)
149
    {
150
        return (!in_array($name, $this->frontMatterBlacklist)) && array_key_exists($name, $this->frontMatter);
151
    }
152
153
    /**
154
     * Return the body of the Content Item
155
     *
156
     * @return string
157
     */
158
    abstract public function getContent ();
159 2
160 2
    /**
161 2
     * @param array|null $variables An array of YAML variables to use in evaluating the `$permalink` value
162 2
     */
163 2
    final public function evaluateFrontMatter ($variables = null)
164 2
    {
165 2
        if (!is_null($variables))
166
        {
167
            $this->frontMatter = array_merge($this->frontMatter, $variables);
168
            $this->handleSpecialFrontMatter();
169
            $this->evaluateYaml($this->frontMatter);
170
        }
171
    }
172
173
    /**
174
     * Get the Front Matter of a ContentItem as an array
175
     *
176 6
     * @param  bool $evaluateYaml When set to true, the YAML will be evaluated for variables
177 6
     *
178 1
     * @return array
179 1
     */
180 5
    final public function getFrontMatter ($evaluateYaml = true)
181 5
    {
182 5
        if (is_null($this->frontMatter))
183 4
        {
184 4
            $this->frontMatter = array();
185
        }
186 5
        else if (!$this->frontMatterEvaluated && $evaluateYaml)
187
        {
188
            $this->evaluateYaml($this->frontMatter);
189
            $this->frontMatterEvaluated = true;
190
        }
191
192
        return $this->frontMatter;
193
    }
194
195
    /**
196 8
     * Get the permalink of this Content Item
197 8
     *
198 1
     * @return string
199
     * @throws \Exception
200
     */
201 8
    final public function getPermalink ()
202 8
    {
203
        if (!is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion())
204 8
        {
205 8
            throw new \Exception(sprintf('%s::%s() should not be called on a repeater template', __CLASS__, __FUNCTION__));
206 1
        }
207 1
208 1
        if (!is_null($this->permalink))
209 1
        {
210
            return $this->permalink;
211
        }
212 7
213 7
        $permalink = (is_array($this->frontMatter) && isset($this->frontMatter['permalink'])) ?
214
            $this->frontMatter['permalink'] : $this->getPathPermalink();
215
216 8
        if (is_array($permalink))
217
        {
218 8
            $this->permalink = $permalink[0];
219
            array_shift($permalink);
220
            $this->redirects = $permalink;
221
        }
222
        else
223
        {
224
            $this->permalink = $permalink;
225
            $this->redirects = array();
226
        }
227
228 1
        $this->permalink = $this->sanitizePermalink($this->permalink);
229 1
230
        return $this->permalink;
231
    }
232
233 1
    /**
234
     * Get an array of URLs that will redirect to
235
     *
236
     * @return string[]
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string[]?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
237
     */
238
    final public function getRedirects ()
239
    {
240
        if (is_null($this->redirects))
241
        {
242
            $this->getPermalink();
243 6
        }
244 6
245
        return $this->redirects;
246 6
    }
247 6
248 2
    /**
249 2
     * Get the destination of where this Content Item would be written to when the website is compiled
250
     *
251 6
     * @return string
252
     */
253
    final public function getTargetFile ()
254
    {
255
        $permalink  = $this->getPermalink();
256
        $extension  = $this->fs->getExtension($permalink);
257
258
        if (empty($extension))
259
        {
260
            $permalink = rtrim($permalink, '/') . '/index.html';
261 4
        }
262
263
        return ltrim($permalink, '/');
264
    }
265
266
    /**
267
     * Get the name of the item, which is just the file name without the extension
268
     *
269
     * @return string
270
     */
271 1
    final public function getName ()
272
    {
273
        return $this->fs->getBaseName($this->filePath);
274
    }
275
276
    /**
277
     * Get the original file path
278
     *
279
     * @return string
280
     */
281 4
    final public function getFilePath ()
282
    {
283
        return $this->filePath;
284
    }
285
286
    /**
287
     * Get the relative path to this file relative to the root of the Stakx website
288
     *
289 28
     * @return string
290
     */
291 28
    final public function getRelativeFilePath ()
292 28
    {
293
        return $this->fs->getRelativePath($this->filePath);
294 28
    }
295 28
296 1
    /**
297 1
     * Read the file, and parse its contents
298 1
     */
299
    final public function refreshFileContent ()
300
    {
301 27
        $rawFileContents = file_get_contents($this->filePath);
302 27
303 1
        $frontMatter = array();
304 1
        preg_match('/---(.*?)---(.*)/s', $rawFileContents, $frontMatter);
305 1
306 View Code Duplication
        if (count($frontMatter) != 3)
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
307
        {
308 26
            throw new IOException(sprintf("'%s' is not a valid ContentItem",
309 25
                    $this->fs->getFileName($this->filePath))
310
            );
311 25
        }
312 25
313 25 View Code Duplication
        if (empty(trim($frontMatter[2])))
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
314
        {
315 25
            throw new IOException(sprintf('A ContentItem (%s) must have a body to render',
316 25
                    $this->fs->getFileName($this->filePath))
317 25
            );
318 25
        }
319
320
        $this->frontMatter = Yaml::parse($frontMatter[1]);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Symfony\Component\Yaml\...:parse($frontMatter[1]) can also be of type string or object<stdClass>. However, the property $frontMatter is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
321
        $this->bodyContent = trim($frontMatter[2]);
322
323
        $this->frontMatterEvaluated = false;
324
        $this->bodyContentEvaluated = false;
325
        $this->permalink = null;
326
327
        $this->handleSpecialFrontMatter();
328
        $this->findTwigDataDependencies('collections');
329
        $this->findTwigDataDependencies('data');
330
    }
331
332
    /**
333
     * Check whether this object has a reference to a collection or data item
334
     *
335
     * @param  string $namespace 'collections' or 'data'
336
     * @param  string $needle
337
     *
338
     * @return bool
339
     */
340
    final public function hasTwigDependency ($namespace, $needle)
341
    {
342 7
        return (in_array($needle, $this->dataDependencies[$namespace]));
343
    }
344 7
345 7
    /**
346 1
     * Evaluate an array of data for FrontMatter variables. This function will modify the array in place.
347 1
     *
348
     * @param  array $yaml An array of data containing FrontMatter variables
349
     *
350 7
     * @throws YamlVariableUndefinedException A FrontMatter variable used does not exist
351
     */
352 6
    final protected function evaluateYaml (&$yaml)
353 6
    {
354
        $this->frontMatterParser = new FrontMatterParser($yaml);
355
    }
356
357
    /**
358
     * Handle special front matter values that need special treatment or have special meaning to a Content Item
359
     */
360
    private function handleSpecialFrontMatter ()
361
    {
362
        if (isset($this->frontMatter['date']))
363
        {
364
            try
365
            {
366
                // Coming from a string variable
367 7
                $itemDate = new \DateTime($this->frontMatter['date']);
368 7
            }
369 7
            catch (\Exception $e)
370
            {
371 7
                // YAML has parsed them to Epoch time
372
                $itemDate = \DateTime::createFromFormat('U', $this->frontMatter['date']);
373
            }
374
375 7
            if (!$itemDate === false)
376
            {
377 6
                $this->frontMatter['year']  = $itemDate->format('Y');
378
                $this->frontMatter['month'] = $itemDate->format('m');
379 6
                $this->frontMatter['day']   = $itemDate->format('d');
380 6
            }
381 1
        }
382
    }
383
384 5
    /**
385 6
     * Get all of the references to either DataItems or ContentItems inside of given string
386
     *
387 6
     * @param string $filter 'collections' or 'data'
388
     */
389
    private function findTwigDataDependencies ($filter)
390
    {
391
        $regex = '/{[{%](?:.+)?(?:' . $filter . ')(?:\.|\[\')(\w+)(?:\'\])?.+[%}]}/';
392
        $results = array();
393
394
        preg_match_all($regex, $this->bodyContent, $results);
395 25
396 25
        $this->dataDependencies[$filter] = array_unique($results[1]);
397
    }
398
399
    /**
400 3
     * Get the permalink based off the location of where the file is relative to the website. This permalink is to be
401
     * used as a fallback in the case that a permalink is not explicitly specified in the Front Matter.
402 3
     *
403
     * @return string
404
     */
405 1
    private function getPathPermalink ()
406
    {
407
        // Remove the protocol of the path, if there is one and prepend a '/' to the beginning
408 3
        $cleanPath = preg_replace('/[\w|\d]+:\/\//', '', $this->filePath);
409 3
        $cleanPath = ltrim($cleanPath, DIRECTORY_SEPARATOR);
410 2
411 2
        // Check the first folder and see if it's a data folder (starts with an underscore) intended for stakx
412 2
        $folders = explode('/', $cleanPath);
413 2
414 3
        if (substr($folders[0], 0, 1) === '_')
415 25
        {
416
            array_shift($folders);
417
        }
418
419
        $cleanPath = implode(DIRECTORY_SEPARATOR, $folders);
420
421
        return $cleanPath;
422
    }
423
424 25
    /**
425 25
     * Sanitize a permalink to remove unsupported characters or multiple '/' and replace spaces with hyphens
426
     *
427 25
     * @param  string $permalink A permalink
428
     *
429 25
     * @return string $permalink The sanitized permalink
430 25
     */
431
    private function sanitizePermalink ($permalink)
432
    {
433
        // Remove multiple '/' together
434
        $permalink = preg_replace('/\/+/', '/', $permalink);
435
436
        // Replace all spaces with hyphens
437
        $permalink = str_replace(' ', '-', $permalink);
438
439
        // Remove all disallowed characters
440
        $permalink = preg_replace('/[^0-9a-zA-Z-_\/\.]/', '', $permalink);
441 3
442 3
        // Handle unnecessary extensions
443
        $extensionsToStrip = array('twig');
444
445 3
        if (in_array($this->fs->getExtension($permalink), $extensionsToStrip))
446
        {
447 3
            $permalink = $this->fs->removeExtension($permalink);
448 3
        }
449 1
450 1
        // Remove a special './' combination from the beginning of a path
451
        if (substr($permalink, 0, 2) === './')
452 3
        {
453
            $permalink = substr($permalink, 2);
454 3
        }
455
456
        // Convert permalinks to lower case
457
        $permalink = mb_strtolower($permalink, 'UTF-8');
458
459
        return $permalink;
460
    }
461
}