Completed
Pull Request — master (#48)
by Vladimir
02:36
created

Document::getPermalink()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7.0119

Importance

Changes 0
Metric Value
cc 7
eloc 18
nc 10
nop 0
dl 0
loc 33
ccs 15
cts 16
cp 0.9375
crap 7.0119
rs 6.7272
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright 2017 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\Document\JailedDocumentInterface;
11
use allejo\stakx\Exception\FileAwareException;
12
use allejo\stakx\Exception\InvalidSyntaxException;
13
use allejo\stakx\FrontMatter\Exception\YamlVariableUndefinedException;
14
use allejo\stakx\System\Filesystem;
15
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
16
use Symfony\Component\Filesystem\Exception\IOException;
17
use Symfony\Component\Finder\SplFileInfo;
18
use Symfony\Component\Yaml\Exception\ParseException;
19
use Symfony\Component\Yaml\Yaml;
20
21
abstract class Document implements
0 ignored issues
show
Coding Style introduced by
Document does not seem to conform to the naming convention (^Abstract|Factory$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
22
    \ArrayAccess,
23
    JailedDocumentInterface,
24
    WritableDocumentInterface
25
{
26
    const TEMPLATE = "---\n%s\n---\n\n%s";
27
28
    protected static $whiteListFunctions = array(
29
        'getPermalink', 'getRedirects', 'getTargetFile', 'getName', 'getFilePath', 'getRelativeFilePath', 'getContent',
30
        'getExtension', 'getFrontMatter'
31
    );
32
33
    /**
34
     * An array to keep track of collection or data dependencies used inside of a Twig template.
35
     *
36
     * $dataDependencies['collections'] = array()
37
     * $dataDependencies['data'] = array()
38
     *
39
     * @var array
40
     */
41
    protected $dataDependencies;
42
43
    /**
44
     * FrontMatter values that can be injected or set after the file has been parsed. Values in this array will take
45
     * precedence over values in $frontMatter.
46
     *
47
     * @var array
48
     */
49
    protected $writableFrontMatter;
50
51
    /**
52
     * A list of Front Matter values that should not be returned directly from the $frontMatter array. Values listed
53
     * here have dedicated functions that handle those Front Matter values and the respective functions should be called
54
     * instead.
55
     *
56
     * @var string[]
57
     */
58
    protected $frontMatterBlacklist;
59
60
    /**
61
     * Set to true if the front matter has already been evaluated with variable interpolation.
62
     *
63
     * @var bool
64
     */
65
    protected $frontMatterEvaluated;
66
67
    /**
68
     * @var Parser
69
     */
70
    protected $frontMatterParser;
71
72
    /**
73
     * An array containing the Yaml of the file.
74
     *
75
     * @var array
76
     */
77
    protected $frontMatter;
78
79
    /**
80
     * Set to true if the body has already been parsed as markdown or any other format.
81
     *
82
     * @var bool
83
     */
84
    protected $bodyContentEvaluated;
85
86
    /**
87
     * Only the body of the file, i.e. the content.
88
     *
89
     * @var string
90
     */
91
    protected $bodyContent;
92
93
    /**
94
     * The permalink for this object.
95
     *
96
     * @var string
97
     */
98
    protected $permalink;
99
100
    /**
101
     * A filesystem object.
102
     *
103
     * @var Filesystem
104
     */
105
    protected $fs;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $fs. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
106
107
    /**
108
     * The extension of the file.
109
     *
110
     * @var string
111
     */
112
    private $extension;
113
114
    /**
115
     * The number of lines that Twig template errors should offset.
116
     *
117
     * @var int
118
     */
119
    private $lineOffset;
120
121
    /**
122
     * A list URLs that will redirect to this object.
123
     *
124
     * @var string[]
125
     */
126
    private $redirects;
127
128
    /**
129
     * The original file path to the ContentItem.
130
     *
131
     * @var SplFileInfo
132
     */
133
    private $filePath;
134
135
    /**
136
     * ContentItem constructor.
137
     *
138
     * @param string $filePath The path to the file that will be parsed into a ContentItem
139
     *
140
     * @throws FileNotFoundException The given file path does not exist
141
     * @throws IOException           The file was not a valid ContentItem. This would meam there was no front matter or
142
     *                               no body
143
     */
144 116
    public function __construct($filePath)
145
    {
146 116
        $this->frontMatterBlacklist = array('permalink', 'redirects');
147 116
        $this->writableFrontMatter = array();
148
149 116
        $this->filePath = $filePath;
0 ignored issues
show
Documentation Bug introduced by
It seems like $filePath of type string is incompatible with the declared type object<Symfony\Component\Finder\SplFileInfo> of property $filePath.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
150 116
        $this->fs = new Filesystem();
151
152 116
        if (!$this->fs->exists($filePath))
153
        {
154 1
            throw new FileNotFoundException("The following file could not be found: ${filePath}");
155
        }
156
157
        $this->extension = strtolower($this->fs->getExtension($filePath));
158
159
        $this->refreshFileContent();
160
    }
161
162
    /**
163
     * Return the body of the Content Item.
164
     *
165
     * @return string
166
     */
167
    abstract public function getContent();
168
169
    /**
170
     * Get the extension of the current file.
171
     *
172
     * @return string
173
     */
174
    final public function getExtension()
175
    {
176 7
        return $this->extension;
177
    }
178
179
    /**
180
     * Get the original file path.
181
     *
182
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be SplFileInfo?

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...
183
     */
184
    final public function getFilePath()
185
    {
186 19
        return $this->filePath;
187
    }
188
189
    /**
190
     * The number of lines that are taken up by FrontMatter and white space.
191
     *
192
     * @return int
193
     */
194
    final public function getLineOffset()
195
    {
196
        return $this->lineOffset;
197
    }
198
199
    /**
200
     * Get the name of the item, which is just the file name without the extension.
201
     *
202
     * @return string
203
     */
204
    final public function getName()
205
    {
206 37
        return $this->fs->getBaseName($this->filePath);
207
    }
208
209
    /**
210
     * Get the relative path to this file relative to the root of the Stakx website.
211
     *
212
     * @return string
213
     */
214
    final public function getRelativeFilePath()
215
    {
216 65
        if ($this->filePath instanceof SplFileInfo)
217
        {
218 39
            return $this->filePath->getRelativePathname();
219
        }
220
221
        // TODO ensure that we always get SplFileInfo objects, even when handling VFS documents
222 28
        return $this->fs->getRelativePath($this->filePath);
223
    }
224
225
    /**
226
     * Get the destination of where this Content Item would be written to when the website is compiled.
227
     *
228
     * @return string
229
     */
230
    final public function getTargetFile()
231
    {
232 20
        $permalink = $this->getPermalink();
233 20
        $missingFile = (substr($permalink, -1) == '/');
234 20
        $permalink = str_replace('/', DIRECTORY_SEPARATOR, $permalink);
235
236 20
        if ($missingFile)
237
        {
238 12
            $permalink = rtrim($permalink, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'index.html';
239
        }
240
241 20
        return ltrim($permalink, DIRECTORY_SEPARATOR);
242
    }
243
244
    /**
245
     * Check whether this object has a reference to a collection or data item.
246
     *
247
     * @param string $namespace 'collections' or 'data'
248
     * @param string $needle
249
     *
250
     * @return bool
251
     */
252
    final public function hasTwigDependency($namespace, $needle)
253
    {
254
        return in_array($needle, $this->dataDependencies[$namespace]);
255
    }
256
257
    /**
258
     * Read the file, and parse its contents.
259
     */
260
    final public function refreshFileContent()
261
    {
262
        // This function can be called after the initial object was created and the file may have been deleted since the
263
        // creation of the object.
264 115 View Code Duplication
        if (!$this->fs->exists($this->filePath))
0 ignored issues
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...
265
        {
266 1
            throw new FileNotFoundException(null, 0, null, $this->filePath);
267
        }
268
269 115
        $rawFileContents = file_get_contents($this->filePath);
270 115
        $fileStructure = array();
271 115
        preg_match('/---\R(.*?\R)?---(\s+)(.*)/s', $rawFileContents, $fileStructure);
272
273 115
        if (count($fileStructure) != 4)
274
        {
275 9
            throw new InvalidSyntaxException('Invalid FrontMatter file', 0, null, $this->getRelativeFilePath());
276
        }
277
278 106
        if (empty(trim($fileStructure[3])))
279
        {
280 1
            throw new InvalidSyntaxException('FrontMatter files must have a body to render', 0, null, $this->getRelativeFilePath());
281
        }
282
283 105
        $this->lineOffset = substr_count($fileStructure[1], "\n") + substr_count($fileStructure[2], "\n");
284 105
        $this->bodyContent = $fileStructure[3];
285
286 105
        if (!empty(trim($fileStructure[1])))
287
        {
288 89
            $this->frontMatter = Yaml::parse($fileStructure[1], Yaml::PARSE_DATETIME);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Symfony\Component\Yaml\...l\Yaml::PARSE_DATETIME) 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...
289
290 89
            if (!empty($this->frontMatter) && !is_array($this->frontMatter))
291
            {
292 1
                throw new ParseException('The evaluated FrontMatter should be an array');
293
            }
294
        }
295
        else
296
        {
297 19
            $this->frontMatter = array();
298
        }
299
300 104
        $this->frontMatterEvaluated = false;
301 104
        $this->bodyContentEvaluated = false;
302 104
        $this->permalink = null;
303
304 104
        $this->findTwigDataDependencies('collections');
305 104
        $this->findTwigDataDependencies('data');
306 104
    }
307
308
    /**
309
     * Get all of the references to either DataItems or ContentItems inside of given string.
310
     *
311
     * @param string $filter 'collections' or 'data'
312
     */
313
    private function findTwigDataDependencies($filter)
314
    {
315 104
        $regex = '/{[{%](?:.+)?(?:' . $filter . ')(?:\.|\[\')(\w+)(?:\'\])?.+[%}]}/';
316 104
        $results = array();
317
318 104
        preg_match_all($regex, $this->bodyContent, $results);
319
320 104
        $this->dataDependencies[$filter] = array_unique($results[1]);
321 104
    }
322
323
    //
324
    // Permalink and redirect functionality
325
    //
326
327
    /**
328
     * Get the permalink of this Content Item.
329
     *
330
     * @throws \Exception
331
     *
332
     * @return string
333
     */
334
    final public function getPermalink()
335
    {
336 39
        if (!is_null($this->permalink))
337
        {
338 8
            return $this->permalink;
339
        }
340
341 37
        if (!is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion())
342
        {
343
            throw new \Exception('The permalink for this item has not been set');
344
        }
345
346 37
        $permalink = (is_array($this->frontMatter) && isset($this->frontMatter['permalink'])) ?
347 37
            $this->frontMatter['permalink'] : $this->getPathPermalink();
348
349 37
        if (is_array($permalink))
350
        {
351 19
            $this->permalink = $permalink[0];
352 19
            array_shift($permalink);
353 19
            $this->redirects = $permalink;
354
        }
355
        else
356
        {
357 24
            $this->permalink = $permalink;
358 24
            $this->redirects = array();
359
        }
360
361 37
        $this->permalink = $this->sanitizePermalink($this->permalink);
362 37
        $this->permalink = str_replace(DIRECTORY_SEPARATOR, '/', $this->permalink);
363 37
        $this->permalink = '/' . ltrim($this->permalink, '/'); // Permalinks should always use '/' and not be OS specific
364
365 37
        return $this->permalink;
366
    }
367
368
    /**
369
     * Get an array of URLs that will redirect to.
370
     *
371
     * @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...
372
     */
373
    final public function getRedirects()
374
    {
375 14
        if (is_null($this->redirects))
376
        {
377 3
            $this->getPermalink();
378
        }
379
380 14
        return $this->redirects;
381
    }
382
383
    /**
384
     * Get the permalink based off the location of where the file is relative to the website. This permalink is to be
385
     * used as a fallback in the case that a permalink is not explicitly specified in the Front Matter.
386
     *
387
     * @return string
388
     */
389
    private function getPathPermalink()
390
    {
391
        // Remove the protocol of the path, if there is one and prepend a '/' to the beginning
392 3
        $cleanPath = preg_replace('/[\w|\d]+:\/\//', '', $this->getRelativeFilePath());
393 3
        $cleanPath = ltrim($cleanPath, DIRECTORY_SEPARATOR);
394
395
        // Handle vfs:// paths by replacing their forward slashes with the OS appropriate directory separator
396 3
        if (DIRECTORY_SEPARATOR !== '/')
397
        {
398
            $cleanPath = str_replace('/', DIRECTORY_SEPARATOR, $cleanPath);
399
        }
400
401
        // Check the first folder and see if it's a data folder (starts with an underscore) intended for stakx
402 3
        $folders = explode(DIRECTORY_SEPARATOR, $cleanPath);
403
404 3
        if (substr($folders[0], 0, 1) === '_')
405
        {
406 1
            array_shift($folders);
407
        }
408
409 3
        $cleanPath = implode(DIRECTORY_SEPARATOR, $folders);
410
411 3
        return $cleanPath;
412
    }
413
414
    /**
415
     * Sanitize a permalink to remove unsupported characters or multiple '/' and replace spaces with hyphens.
416
     *
417
     * @param string $permalink A permalink
418
     *
419
     * @return string $permalink The sanitized permalink
420
     */
421
    private function sanitizePermalink($permalink)
422
    {
423
        // Remove multiple '/' together
424 37
        $permalink = preg_replace('/\/+/', '/', $permalink);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $permalink. This often makes code more readable.
Loading history...
425
426
        // Replace all spaces with hyphens
427 37
        $permalink = str_replace(' ', '-', $permalink);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $permalink. This often makes code more readable.
Loading history...
428
429
        // Remove all disallowed characters
430 37
        $permalink = preg_replace('/[^0-9a-zA-Z-_\/\\\.]/', '', $permalink);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $permalink. This often makes code more readable.
Loading history...
431
432
        // Handle unnecessary extensions
433 37
        $extensionsToStrip = array('twig');
434
435 37
        if (in_array($this->fs->getExtension($permalink), $extensionsToStrip))
436
        {
437 4
            $permalink = $this->fs->removeExtension($permalink);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $permalink. This often makes code more readable.
Loading history...
438
        }
439
440
        // Remove any special characters before a sane value
441 37
        $permalink = preg_replace('/^[^0-9a-zA-Z-_]*/', '', $permalink);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $permalink. This often makes code more readable.
Loading history...
442
443
        // Convert permalinks to lower case
444 37
        $permalink = mb_strtolower($permalink, 'UTF-8');
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $permalink. This often makes code more readable.
Loading history...
445
446 37
        return $permalink;
447
    }
448
449
    //
450
    // WritableFrontMatter Implementation
451
    //
452
453
    /**
454
     * {@inheritdoc}
455
     */
456
    final public function evaluateFrontMatter($variables = null)
457
    {
458 7
        if (!is_null($variables))
459
        {
460 7
            $this->frontMatter = array_merge($this->frontMatter, $variables);
461 7
            $this->evaluateYaml($this->frontMatter);
462
        }
463 7
    }
464
465
    /**
466
     * {@inheritdoc}
467
     */
468
    final public function getFrontMatter($evaluateYaml = true)
469
    {
470 29
        if (is_null($this->frontMatter))
471
        {
472
            $this->frontMatter = array();
473
        }
474 29
        elseif (!$this->frontMatterEvaluated && $evaluateYaml)
475
        {
476 23
            $this->evaluateYaml($this->frontMatter);
477
        }
478
479 28
        return $this->frontMatter;
480
    }
481
482
    /**
483
     * {@inheritdoc}
484
     */
485
    final public function hasExpandedFrontMatter()
486
    {
487 2
        return !is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion();
488
    }
489
490
    /**
491
     * {@inheritdoc.
492
     */
493
    final public function appendFrontMatter(array $frontMatter)
494
    {
495
        foreach ($frontMatter as $key => $value)
496
        {
497
            $this->writableFrontMatter[$key] = $value;
498
        }
499
    }
500
501
    /**
502
     * {@inheritdoc.
503
     */
504
    final public function deleteFrontMatter($key)
505
    {
506
        if (!isset($this->writableFrontMatter[$key]))
507
        {
508
            return;
509
        }
510
511
        unset($this->writableFrontMatter[$key]);
512
    }
513
514
    /**
515
     * {@inheritdoc.
516
     */
517
    final public function setFrontMatter(array $frontMatter)
518
    {
519 2
        if (!is_array($frontMatter))
520
        {
521
            throw new \InvalidArgumentException('An array is required for setting the writable FrontMatter');
522
        }
523
524 2
        $this->writableFrontMatter = $frontMatter;
525 2
    }
526
527
    /**
528
     * Evaluate an array of data for FrontMatter variables. This function will modify the array in place.
529
     *
530
     * @param array $yaml An array of data containing FrontMatter variables
531
     *
532
     * @throws YamlVariableUndefinedException A FrontMatter variable used does not exist
533
     */
534
    private function evaluateYaml(&$yaml)
535
    {
536
        try
537
        {
538 30
            $this->frontMatterParser = new Parser($yaml);
539 29
            $this->frontMatterEvaluated = true;
540
        }
541 1
        catch (\Exception $e)
542
        {
543 1
            throw FileAwareException::castException($e, $this->getRelativeFilePath());
544
        }
545 29
    }
546
547
    //
548
    // ArrayAccess Implementation
549
    //
550
551
    /**
552
     * {@inheritdoc}
553
     */
554
    public function offsetSet($offset, $value)
555
    {
556
        if (is_null($offset))
557
        {
558
            throw new \InvalidArgumentException('$offset cannot be null');
559
        }
560
561
        $this->writableFrontMatter[$offset] = $value;
562
    }
563
564
    /**
565
     * {@inheritdoc}
566
     */
567
    public function offsetExists($offset)
568
    {
569 31
        if (isset($this->writableFrontMatter[$offset]) || isset($this->frontMatter[$offset]))
570
        {
571 30
            return true;
572
        }
573
574 14
        $fxnCall = 'get' . ucfirst($offset);
575
576 14
        return method_exists($this, $fxnCall) && in_array($fxnCall, static::$whiteListFunctions);
577
    }
578
579
    /**
580
     * {@inheritdoc}
581
     */
582
    public function offsetUnset($offset)
583
    {
584
        unset($this->writableFrontMatter[$offset]);
585
    }
586
587
    /**
588
     * {@inheritdoc}
589
     */
590
    public function offsetGet($offset)
591
    {
592 48
        $fxnCall = 'get' . ucfirst($offset);
593
594 48
        if (in_array($fxnCall, self::$whiteListFunctions) && method_exists($this, $fxnCall))
595
        {
596 6
            return call_user_func_array(array($this, $fxnCall), array());
597
        }
598
599 42
        if (isset($this->writableFrontMatter[$offset]))
600
        {
601
            return $this->writableFrontMatter[$offset];
602
        }
603
604 42
        if (isset($this->frontMatter[$offset]))
605
        {
606 41
            return $this->frontMatter[$offset];
607
        }
608
609 5
        return null;
610
    }
611
}
612