Completed
Pull Request — master (#20)
by Vladimir
04:43 queued 02:05
created

FrontMatterObject::getPermalink()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7.0957

Importance

Changes 0
Metric Value
cc 7
eloc 16
nc 10
nop 0
dl 0
loc 31
rs 6.7272
c 0
b 0
f 0
ccs 14
cts 16
cp 0.875
crap 7.0957
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
     * The permalink for this object
82
     *
83
     * @var string
84
     */
85
    protected $permalink;
86
87
    /**
88
     * A filesystem object
89
     *
90
     * @var Filesystem
91
     */
92
    protected $fs;
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->permalink))
204 8
        {
205 8
            return $this->permalink;
206 1
        }
207 1
208 1
        if (!is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion())
209 1
        {
210
            throw new \Exception('The permalink for this item has not been set');
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
     * Returns true when the evaluated Front Matter has expanded values embeded
298 1
     *
299
     * @return bool
300
     */
301 27
    final public function hasExpandedFrontMatter ()
302 27
    {
303 1
        return (!is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion());
304 1
    }
305 1
306
    /**
307
     * Read the file, and parse its contents
308 26
     */
309 25
    final public function refreshFileContent ()
310
    {
311 25
        $rawFileContents = file_get_contents($this->filePath);
312 25
313 25
        $frontMatter = array();
314
        preg_match('/---(.*?)---(.*)/s', $rawFileContents, $frontMatter);
315 25
316 25 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...
317 25
        {
318 25
            throw new IOException(sprintf("'%s' is not a valid ContentItem",
319
                    $this->fs->getFileName($this->filePath))
320
            );
321
        }
322
323 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...
324
        {
325
            throw new IOException(sprintf('A ContentItem (%s) must have a body to render',
326
                    $this->fs->getFileName($this->filePath))
327
            );
328
        }
329
330
        $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...
331
        $this->bodyContent = trim($frontMatter[2]);
332
333
        $this->frontMatterEvaluated = false;
334
        $this->bodyContentEvaluated = false;
335
        $this->permalink = null;
336
337
        $this->handleSpecialFrontMatter();
338
        $this->findTwigDataDependencies('collections');
339
        $this->findTwigDataDependencies('data');
340
    }
341
342 7
    /**
343
     * Check whether this object has a reference to a collection or data item
344 7
     *
345 7
     * @param  string $namespace 'collections' or 'data'
346 1
     * @param  string $needle
347 1
     *
348
     * @return bool
349
     */
350 7
    final public function hasTwigDependency ($namespace, $needle)
351
    {
352 6
        return (in_array($needle, $this->dataDependencies[$namespace]));
353 6
    }
354
355
    /**
356
     * Evaluate an array of data for FrontMatter variables. This function will modify the array in place.
357
     *
358
     * @param  array $yaml An array of data containing FrontMatter variables
359
     *
360
     * @throws YamlVariableUndefinedException A FrontMatter variable used does not exist
361
     */
362
    final protected function evaluateYaml (&$yaml)
363
    {
364
        $this->frontMatterParser = new FrontMatterParser($yaml);
365
    }
366
367 7
    /**
368 7
     * Handle special front matter values that need special treatment or have special meaning to a Content Item
369 7
     */
370
    private function handleSpecialFrontMatter ()
371 7
    {
372
        if (isset($this->frontMatter['date']))
373
        {
374
            try
375 7
            {
376
                // Coming from a string variable
377 6
                $itemDate = new \DateTime($this->frontMatter['date']);
378
            }
379 6
            catch (\Exception $e)
380 6
            {
381 1
                // YAML has parsed them to Epoch time
382
                $itemDate = \DateTime::createFromFormat('U', $this->frontMatter['date']);
383
            }
384 5
385 6
            if (!$itemDate === false)
386
            {
387 6
                $this->frontMatter['year']  = $itemDate->format('Y');
388
                $this->frontMatter['month'] = $itemDate->format('m');
389
                $this->frontMatter['day']   = $itemDate->format('d');
390
            }
391
        }
392
    }
393
394
    /**
395 25
     * Get all of the references to either DataItems or ContentItems inside of given string
396 25
     *
397
     * @param string $filter 'collections' or 'data'
398
     */
399
    private function findTwigDataDependencies ($filter)
400 3
    {
401
        $regex = '/{[{%](?:.+)?(?:' . $filter . ')(?:\.|\[\')(\w+)(?:\'\])?.+[%}]}/';
402 3
        $results = array();
403
404
        preg_match_all($regex, $this->bodyContent, $results);
405 1
406
        $this->dataDependencies[$filter] = array_unique($results[1]);
407
    }
408 3
409 3
    /**
410 2
     * Get the permalink based off the location of where the file is relative to the website. This permalink is to be
411 2
     * used as a fallback in the case that a permalink is not explicitly specified in the Front Matter.
412 2
     *
413 2
     * @return string
414 3
     */
415 25
    private function getPathPermalink ()
416
    {
417
        // Remove the protocol of the path, if there is one and prepend a '/' to the beginning
418
        $cleanPath = preg_replace('/[\w|\d]+:\/\//', '', $this->filePath);
419
        $cleanPath = ltrim($cleanPath, DIRECTORY_SEPARATOR);
420
421
        // Check the first folder and see if it's a data folder (starts with an underscore) intended for stakx
422
        $folders = explode('/', $cleanPath);
423
424 25
        if (substr($folders[0], 0, 1) === '_')
425 25
        {
426
            array_shift($folders);
427 25
        }
428
429 25
        $cleanPath = implode(DIRECTORY_SEPARATOR, $folders);
430 25
431
        return $cleanPath;
432
    }
433
434
    /**
435
     * Sanitize a permalink to remove unsupported characters or multiple '/' and replace spaces with hyphens
436
     *
437
     * @param  string $permalink A permalink
438
     *
439
     * @return string $permalink The sanitized permalink
440
     */
441 3
    private function sanitizePermalink ($permalink)
442 3
    {
443
        // Remove multiple '/' together
444
        $permalink = preg_replace('/\/+/', '/', $permalink);
445 3
446
        // Replace all spaces with hyphens
447 3
        $permalink = str_replace(' ', '-', $permalink);
448 3
449 1
        // Remove all disallowed characters
450 1
        $permalink = preg_replace('/[^0-9a-zA-Z-_\/\.]/', '', $permalink);
451
452 3
        // Handle unnecessary extensions
453
        $extensionsToStrip = array('twig');
454 3
455
        if (in_array($this->fs->getExtension($permalink), $extensionsToStrip))
456
        {
457
            $permalink = $this->fs->removeExtension($permalink);
458
        }
459
460
        // Remove a special './' combination from the beginning of a path
461
        if (substr($permalink, 0, 2) === './')
462
        {
463
            $permalink = substr($permalink, 2);
464
        }
465
466
        // Convert permalinks to lower case
467 8
        $permalink = mb_strtolower($permalink, 'UTF-8');
468
469
        return $permalink;
470
    }
471
}