Completed
Pull Request — master (#18)
by Vladimir
02:06
created

FrontMatterObject::getRedirects()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
ccs 1
cts 1
cp 1
crap 2
1
<?php
2
3
namespace allejo\stakx\Object;
4
5
use allejo\stakx\System\Filesystem;
6
use allejo\stakx\Exception\YamlVariableUndefinedException;
7
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
8
use Symfony\Component\Filesystem\Exception\IOException;
9
use Symfony\Component\Yaml\Yaml;
10
11
abstract class FrontMatterObject
12
{
13
    /**
14
     * An array to keep track of collection or data dependencies used inside of a Twig template
15
     *
16
     * $dataDependencies['collections'] = array()
17
     * $dataDependencies['data'] = array()
18
     *
19
     * @var array
20
     */
21
    protected $dataDependencies;
22
23
    /**
24
     * A list of Front Matter values that should not be returned directly from the $frontMatter array. Values listed
25
     * here have dedicated functions that handle those Front Matter values and the respective functions should be called
26
     * instead.
27
     *
28
     * @var string[]
29
     */
30
    protected $frontMatterBlacklist;
31
32
    /**
33
     * Set to true if the front matter has already been evaluated with variable interpolation
34
     *
35
     * @var bool
36
     */
37
    protected $frontMatterEvaluated;
38
39
    /**
40
     * An array containing the Yaml of the file
41
     *
42
     * @var array
43
     */
44
    protected $frontMatter;
45
46
    /**
47
     * Set to true if the body has already been parsed as markdown or any other format
48
     *
49
     * @var bool
50
     */
51
    protected $bodyContentEvaluated;
52
53
    /**
54
     * Only the body of the file, i.e. the content
55
     *
56
     * @var string
57
     */
58
    protected $bodyContent;
59
60
    /**
61
     * The extension of the file
62
     *
63
     * @var string
64
     */
65
    protected $extension;
66
67
    /**
68
     * The original file path to the ContentItem
69
     *
70
     * @var string
71
     */
72
    protected $filePath;
73
74
    /**
75
     * A filesystem object
76
     *
77
     * @var Filesystem
78
     */
79
    protected $fs;
80
81
    /**
82
     * The permalink for this object
83
     *
84
     * @var string
85
     */
86
    private $permalink;
87
88
    /**
89
     * A list URLs that will redirect to this object
90
     *
91
     * @var string[]
92
     */
93
    private $redirects;
94
95
    /**
96
     * ContentItem constructor.
97 28
     *
98
     * @param string $filePath The path to the file that will be parsed into a ContentItem
99 28
     *
100
     * @throws FileNotFoundException The given file path does not exist
101 28
     * @throws IOException           The file was not a valid ContentItem. This would meam there was no front matter or
102 28
     *                               no body
103
     */
104 28
    public function __construct ($filePath)
105 28
    {
106 1
        $this->frontMatterBlacklist = array('permalink', 'redirects');
107
108
        $this->filePath  = $filePath;
109
        $this->fs        = new Filesystem();
110
111
        if (!$this->fs->exists($filePath))
112
        {
113
            throw new FileNotFoundException("The following file could not be found: ${filePath}");
114
        }
115
116
        $this->extension = strtolower($this->fs->getExtension($filePath));
117
118
        $this->refreshFileContent();
119
    }
120
121
    /**
122
     * The magic getter returns values from the front matter in order to make these values accessible to Twig templates
123
     * in a simple fashion
124 3
     *
125
     * @param  string $name The key in the front matter
126
     *
127
     * @return mixed|null
128
     */
129
    public function __get ($name)
130
    {
131
        return (array_key_exists($name, $this->frontMatter) ? $this->frontMatter[$name] : null);
132
    }
133
134
    /**
135
     * The magic getter returns true if the value exists in the Front Matter. This is used in conjunction with the __get
136
     * function
137 1
     *
138
     * @param  string $name The name of the Front Matter value being looked for
139
     *
140
     * @return bool
141
     */
142
    public function __isset ($name)
143
    {
144
        return (!in_array($name, $this->frontMatterBlacklist)) && array_key_exists($name, $this->frontMatter);
145
    }
146
147
    /**
148
     * Return the body of the Content Item
149
     *
150
     * @return string
151
     */
152 2
    abstract public function getContent ();
153 2
154 2
    /**
155 2
     * @param array|null $variables An array of YAML variables to use in evaluating the `$permalink` value
156 2
     */
157 2
    final public function evaluateFrontMatter ($variables = null)
158 2
    {
159
        if (!is_null($variables))
160
        {
161
            $this->frontMatter = array_merge($this->frontMatter, $variables);
162
            $this->handleSpecialFrontMatter();
163
            $this->evaluateYaml($this->frontMatter);
164
        }
165
    }
166
167
    /**
168
     * Get the Front Matter of a ContentItem as an array
169 6
     *
170 6
     * @param  bool $evaluateYaml When set to true, the YAML will be evaluated for variables
171 1
     *
172 1
     * @return array
173 5
     */
174 5
    final public function getFrontMatter ($evaluateYaml = true)
175 5
    {
176 4
        if ($this->frontMatter === null)
177 4
        {
178
            $this->frontMatter = array();
179 5
        }
180
        else if (!$this->frontMatterEvaluated && $evaluateYaml && !empty($evaluateYaml))
181
        {
182
            $this->evaluateYaml($this->frontMatter);
183
            $this->frontMatterEvaluated = true;
184
        }
185
186
        return $this->frontMatter;
187
    }
188
189 7
    /**
190 7
     * Get the permalink of this Content Item
191
     *
192
     * @return string
193
     */
194 7
    final public function getPermalink ()
195 7
    {
196
        if (!is_null($this->permalink))
197 7
        {
198 7
            return $this->permalink;
199
        }
200 7
201
        $permalink = (is_array($this->frontMatter) && array_key_exists('permalink', $this->frontMatter)) ?
202
            $this->frontMatter['permalink'] : $this->getPathPermalink();
203
204
        if (is_array($permalink))
205
        {
206
            $this->permalink = $permalink[0];
207
            array_shift($permalink);
208
            $this->redirects = $permalink;
209
        }
210 5
        else
211 5
        {
212
            $this->permalink = $permalink;
213 5
            $this->redirects = array();
214 5
        }
215 1
216 1
        $this->permalink = $this->sanitizePermalink($this->permalink);
217
218 5
        return $this->permalink;
219
    }
220
221
    /**
222
     * Get an array of URLs that will redirect to
223
     *
224
     * @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...
225
     */
226
    final public function getRedirects ()
227
    {
228 4
        if (is_null($this->redirects))
229
        {
230
            $this->getPermalink();
231
        }
232
233
        return $this->redirects;
234
    }
235
236
    /**
237
     * Get the destination of where this Content Item would be written to when the website is compiled
238 1
     *
239
     * @return string
240
     */
241
    final public function getTargetFile ()
242
    {
243
        $permalink  = $this->getPermalink();
244
        $extension  = $this->fs->getExtension($permalink);
245
246
        if (empty($extension))
247
        {
248 4
            $permalink = rtrim($permalink, '/') . '/index.html';
249
        }
250
251
        return ltrim($permalink, '/');
252
    }
253
254
    /**
255
     * Get the name of the item, which is just the file name without the extension
256 27
     *
257
     * @return string
258 27
     */
259 27
    final public function getName ()
260
    {
261 27
        return $this->fs->getBaseName($this->filePath);
262 27
    }
263 1
264 1
    /**
265 1
     * Get the original file path
266
     *
267
     * @return string
268 26
     */
269 26
    final public function getFilePath ()
270 1
    {
271 1
        return $this->filePath;
272 1
    }
273
274
    /**
275 25
     * Get the relative path to this file relative to the root of the Stakx website
276 24
     *
277
     * @return string
278 24
     */
279 24
    final public function getRelativeFilePath ()
280 24
    {
281
        return $this->fs->getRelativePath($this->filePath);
282 24
    }
283 24
284 24
    /**
285 24
     * Read the file, and parse its contents
286
     */
287
    final public function refreshFileContent ()
288
    {
289
        $rawFileContents = file_get_contents($this->filePath);
290
291
        $frontMatter = array();
292
        preg_match('/---(.*?)---(.*)/s', $rawFileContents, $frontMatter);
293
294 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...
295
        {
296
            throw new IOException(sprintf("'%s' is not a valid ContentItem",
297
                    $this->fs->getFileName($this->filePath))
298
            );
299
        }
300
301 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...
302
        {
303
            throw new IOException(sprintf('A ContentItem (%s) must have a body to render',
304
                    $this->fs->getFileName($this->filePath))
305
            );
306
        }
307
308
        $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...
309 7
        $this->bodyContent = trim($frontMatter[2]);
310
311 7
        $this->frontMatterEvaluated = false;
312 7
        $this->bodyContentEvaluated = false;
313 1
        $this->permalink = null;
314 1
315
        $this->handleSpecialFrontMatter();
316
        $this->findTwigDataDependencies('collections');
317 7
        $this->findTwigDataDependencies('data');
318
    }
319 6
320 6
    /**
321
     * Check whether this object has a reference to a collection or data item
322
     *
323
     * @param  string $namespace 'collections' or 'data'
324
     * @param  string $needle
325
     *
326
     * @return bool
327
     */
328
    final public function hasTwigDependency ($namespace, $needle)
329
    {
330
        return (in_array($needle, $this->dataDependencies[$namespace]));
331
    }
332
333
    /**
334 7
     * Evaluate an array of data for FrontMatter variables. This function will modify the array in place.
335 7
     *
336 7
     * @param  array $yaml An array of data containing FrontMatter variables
337
     *
338 7
     * @throws YamlVariableUndefinedException A FrontMatter variable used does not exist
339
     */
340
    final protected function evaluateYaml (&$yaml)
341
    {
342 7
        foreach ($yaml as $key => $value)
343
        {
344 6
            if (is_array($yaml[$key]))
345
            {
346 6
                $this->evaluateYaml($yaml[$key]);
347 6
            }
348 1
            else
349
            {
350
                $yaml[$key] = $this->evaluateYamlVar($value, $this->frontMatter);
351 5
            }
352 6
        }
353
    }
354 6
355
    /**
356
     * Evaluate an string for FrontMatter variables and replace them with the corresponding values
357
     *
358
     * @param  string $string The string that will be evaluated
359
     * @param  array  $yaml   The existing front matter from which the variable values will be pulled from
360
     *
361
     * @return string The final string with variables evaluated
362 24
     *
363 24
     * @throws YamlVariableUndefinedException A FrontMatter variable used does not exist
364
     */
365
    private function evaluateYamlVar ($string, $yaml)
366
    {
367 3
        $variables = array();
368
        $varRegex  = '/(%[a-zA-Z]+)/';
369 3
        $output    = $string;
370
371
        preg_match_all($varRegex, $string, $variables);
372 1
373
        // Default behavior causes $variables[0] is the entire string that was matched. $variables[1] will be each
374
        // matching result individually.
375 3
        foreach ($variables[1] as $variable)
376 3
        {
377 2
            $yamlVar = substr($variable, 1); // Trim the '%' from the YAML variable name
378 2
379 2
            if (!array_key_exists($yamlVar, $yaml))
380 2
            {
381 3
                throw new YamlVariableUndefinedException("Yaml variable `$variable` is not defined");
382 24
            }
383
384
            $output = str_replace($variable, $yaml[$yamlVar], $output);
385
        }
386
387
        return $output;
388
    }
389
390
    /**
391 24
     * Handle special front matter values that need special treatment or have special meaning to a Content Item
392 24
     */
393
    private function handleSpecialFrontMatter ()
394 24
    {
395
        if (isset($this->frontMatter['date']))
396 24
        {
397 24
            try
398
            {
399
                // Coming from a string variable
400
                $itemDate = new \DateTime($this->frontMatter['date']);
401
            }
402
            catch (\Exception $e)
403
            {
404
                // YAML has parsed them to Epoch time
405
                $itemDate = \DateTime::createFromFormat('U', $this->frontMatter['date']);
406
            }
407
408 3
            if (!$itemDate === false)
409 3
            {
410
                $this->frontMatter['year']  = $itemDate->format('Y');
411
                $this->frontMatter['month'] = $itemDate->format('m');
412 3
                $this->frontMatter['day']   = $itemDate->format('d');
413
            }
414 3
        }
415 3
    }
416 1
417 1
    /**
418
     * Get all of the references to either DataItems or ContentItems inside of given string
419 3
     *
420
     * @param string $filter 'collections' or 'data'
421 3
     */
422
    private function findTwigDataDependencies ($filter)
423
    {
424
        $regex = '/{[{%](?:.+)?(?:' . $filter . ')(?:\.|\[\')(\w+)(?:\'\])?.+[%}]}/';
425
        $results = array();
426
427
        preg_match_all($regex, $this->bodyContent, $results);
428
429
        $this->dataDependencies[$filter] = array_unique($results[1]);
430
    }
431
432
    /**
433
     * Get the permalink based off the location of where the file is relative to the website. This permalink is to be
434 7
     * used as a fallback in the case that a permalink is not explicitly specified in the Front Matter.
435
     *
436
     * @return string
437 7
     */
438
    private function getPathPermalink ()
439
    {
440 7
        // Remove the protocol of the path, if there is one and prepend a '/' to the beginning
441
        $cleanPath = preg_replace('/[\w|\d]+:\/\//', '', $this->filePath);
442
        $cleanPath = ltrim($cleanPath, DIRECTORY_SEPARATOR);
443 7
444
        // Check the first folder and see if it's a data folder (starts with an underscore) intended for stakx
445 7
        $folders = explode('/', $cleanPath);
446 7
447 3
        if (substr($folders[0], 0, 1) === '_')
448 3
        {
449
            array_shift($folders);
450
        }
451 7
452 7
        $cleanPath = implode(DIRECTORY_SEPARATOR, $folders);
453 1
454 1
        return $cleanPath;
455
    }
456
457 7
    /**
458
     * Sanitize a permalink to remove unsupported characters or multiple '/' and replace spaces with hyphens
459 7
     *
460
     * @param  string $permalink A permalink
461 1
     *
462
     * @return string $permalink The sanitized permalink
463
     */
464
    private function sanitizePermalink ($permalink)
465
    {
466
        // Remove multiple '/' together
467
        $permalink = preg_replace('/\/+/', '/', $permalink);
468
469
        // Replace all spaces with hyphens
470
        $permalink = str_replace(' ', '-', $permalink);
471
472
        // Remove all disallowed characters
473
        $permalink = preg_replace('/[^0-9a-zA-Z-_\/\.]/', '', $permalink);
474
475
        // Handle unnecessary extensions
476
        $extensionsToStrip = array('twig');
477
478
        if (in_array($this->fs->getExtension($permalink), $extensionsToStrip))
479
        {
480
            $permalink = $this->fs->removeExtension($permalink);
481
        }
482
483
        // Remove a special './' combination from the beginning of a path
484
        if (substr($permalink, 0, 2) === './')
485
        {
486
            $permalink = substr($permalink, 2);
487
        }
488
489
        // Convert permalinks to lower case
490
        $permalink = mb_strtolower($permalink, 'UTF-8');
491
492
        return $permalink;
493
    }
494
}