Completed
Pull Request — master (#45)
by Vladimir
02:30
created

Document::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 17
ccs 8
cts 8
cp 1
crap 2
rs 9.4285
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 WritableDocumentInterface, JailedDocumentInterface, \ArrayAccess
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
{
23
    const TEMPLATE = "---\n%s\n---\n\n%s";
24
25
    protected static $whiteListFunctions = array(
26
        'getPermalink', 'getRedirects', 'getTargetFile', 'getName', 'getFilePath', 'getRelativeFilePath', 'getContent',
27
        'getExtension', 'getFrontMatter'
28
    );
29
30
    /**
31
     * An array to keep track of collection or data dependencies used inside of a Twig template.
32
     *
33
     * $dataDependencies['collections'] = array()
34
     * $dataDependencies['data'] = array()
35
     *
36
     * @var array
37
     */
38
    protected $dataDependencies;
39
40
    /**
41
     * FrontMatter values that can be injected or set after the file has been parsed. Values in this array will take
42
     * precedence over values in $frontMatter.
43
     *
44
     * @var array
45
     */
46
    protected $writableFrontMatter;
47
48
    /**
49
     * A list of Front Matter values that should not be returned directly from the $frontMatter array. Values listed
50
     * here have dedicated functions that handle those Front Matter values and the respective functions should be called
51
     * instead.
52
     *
53
     * @var string[]
54
     */
55
    protected $frontMatterBlacklist;
56
57
    /**
58
     * Set to true if the front matter has already been evaluated with variable interpolation.
59
     *
60
     * @var bool
61
     */
62
    protected $frontMatterEvaluated;
63
64
    /**
65
     * @var Parser
66
     */
67
    protected $frontMatterParser;
68
69
    /**
70
     * An array containing the Yaml of the file.
71
     *
72
     * @var array
73
     */
74
    protected $frontMatter;
75
76
    /**
77
     * Set to true if the body has already been parsed as markdown or any other format.
78
     *
79
     * @var bool
80
     */
81
    protected $bodyContentEvaluated;
82
83
    /**
84
     * Only the body of the file, i.e. the content.
85
     *
86
     * @var string
87
     */
88
    protected $bodyContent;
89
90
    /**
91
     * The permalink for this object.
92
     *
93
     * @var string
94
     */
95
    protected $permalink;
96
97
    /**
98
     * A filesystem object.
99
     *
100
     * @var Filesystem
101
     */
102
    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...
103
104
    /**
105
     * The extension of the file.
106
     *
107
     * @var string
108
     */
109
    private $extension;
110
111
    /**
112
     * The number of lines that Twig template errors should offset.
113
     *
114
     * @var int
115
     */
116
    private $lineOffset;
117
118
    /**
119
     * A list URLs that will redirect to this object.
120
     *
121
     * @var string[]
122
     */
123
    private $redirects;
124
125
    /**
126
     * The original file path to the ContentItem.
127
     *
128
     * @var SplFileInfo
129
     */
130
    private $filePath;
131
132
    /**
133
     * ContentItem constructor.
134
     *
135
     * @param string $filePath The path to the file that will be parsed into a ContentItem
136
     *
137
     * @throws FileNotFoundException The given file path does not exist
138
     * @throws IOException           The file was not a valid ContentItem. This would meam there was no front matter or
139
     *                               no body
140
     */
141 115
    public function __construct($filePath)
142
    {
143 115
        $this->frontMatterBlacklist = array('permalink', 'redirects');
144 115
        $this->writableFrontMatter = array();
145
146 115
        $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...
147 115
        $this->fs = new Filesystem();
148
149 115
        if (!$this->fs->exists($filePath))
150 115
        {
151 1
            throw new FileNotFoundException("The following file could not be found: ${filePath}");
152
        }
153
154
        $this->extension = strtolower($this->fs->getExtension($filePath));
155
156
        $this->refreshFileContent();
157
    }
158
159
    /**
160
     * Return the body of the Content Item.
161
     *
162
     * @return string
163
     */
164
    abstract public function getContent();
165
166
    /**
167
     * Get the extension of the current file.
168
     *
169
     * @return string
170
     */
171
    final public function getExtension()
172
    {
173 7
        return $this->extension;
174
    }
175
176
    /**
177
     * Get the original file path.
178
     *
179
     * @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...
180
     */
181
    final public function getFilePath()
182
    {
183 18
        return $this->filePath;
184
    }
185
186
    /**
187
     * The number of lines that are taken up by FrontMatter and white space.
188
     *
189
     * @return int
190
     */
191
    final public function getLineOffset()
192
    {
193
        return $this->lineOffset;
194
    }
195
196
    /**
197
     * Get the name of the item, which is just the file name without the extension.
198
     *
199
     * @return string
200
     */
201
    final public function getName()
202
    {
203 36
        return $this->fs->getBaseName($this->filePath);
204
    }
205
206
    /**
207
     * Get the relative path to this file relative to the root of the Stakx website.
208
     *
209
     * @return string
210
     */
211
    final public function getRelativeFilePath()
212
    {
213 64
        if ($this->filePath instanceof SplFileInfo)
214 64
        {
215 38
            return $this->filePath->getRelativePathname();
216
        }
217
218
        // TODO ensure that we always get SplFileInfo objects, even when handling VFS documents
219 27
        return $this->fs->getRelativePath($this->filePath);
220
    }
221
222
    /**
223
     * Get the destination of where this Content Item would be written to when the website is compiled.
224
     *
225
     * @return string
226
     */
227
    final public function getTargetFile()
228
    {
229 19
        $permalink = $this->getPermalink();
230 19
        $missingFile = (substr($permalink, -1) == '/');
231 19
        $permalink = str_replace('/', DIRECTORY_SEPARATOR, $permalink);
232
233
        if ($missingFile)
234 19
        {
235 11
            $permalink = rtrim($permalink, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'index.html';
236 11
        }
237
238 19
        return ltrim($permalink, DIRECTORY_SEPARATOR);
239
    }
240
241
    /**
242
     * Check whether this object has a reference to a collection or data item.
243
     *
244
     * @param string $namespace 'collections' or 'data'
245
     * @param string $needle
246
     *
247
     * @return bool
248
     */
249
    final public function hasTwigDependency($namespace, $needle)
250
    {
251
        return in_array($needle, $this->dataDependencies[$namespace]);
252
    }
253
254
    /**
255
     * Read the file, and parse its contents.
256
     */
257
    final public function refreshFileContent()
258
    {
259
        // This function can be called after the initial object was created and the file may have been deleted since the
260
        // creation of the object.
261 114
        if (!$this->fs->exists($this->filePath))
262 114
        {
263 1
            throw new FileNotFoundException(null, 0, null, $this->filePath);
264
        }
265
266 114
        $rawFileContents = file_get_contents($this->filePath);
267 114
        $fileStructure = array();
268 114
        preg_match('/---\R(.*?\R)?---(\s+)(.*)/s', $rawFileContents, $fileStructure);
269
270 114
        if (count($fileStructure) != 4)
271 114
        {
272 9
            throw new InvalidSyntaxException('Invalid FrontMatter file', 0, null, $this->getRelativeFilePath());
273
        }
274
275 105
        if (empty(trim($fileStructure[3])))
276 105
        {
277 1
            throw new InvalidSyntaxException('FrontMatter files must have a body to render', 0, null, $this->getRelativeFilePath());
278
        }
279
280 104
        $this->lineOffset = substr_count($fileStructure[1], "\n") + substr_count($fileStructure[2], "\n");
281 104
        $this->bodyContent = $fileStructure[3];
282
283 104
        if (!empty(trim($fileStructure[1])))
284 104
        {
285 88
            $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...
286
287 88
            if (!empty($this->frontMatter) && !is_array($this->frontMatter))
288 88
            {
289 1
                throw new ParseException('The evaluated FrontMatter should be an array');
290
            }
291 87
        }
292
        else
293
        {
294 19
            $this->frontMatter = array();
295
        }
296
297 103
        $this->frontMatterEvaluated = false;
298 103
        $this->bodyContentEvaluated = false;
299 103
        $this->permalink = null;
300
301 103
        $this->findTwigDataDependencies('collections');
302 103
        $this->findTwigDataDependencies('data');
303 103
    }
304
305
    /**
306
     * Get all of the references to either DataItems or ContentItems inside of given string.
307
     *
308
     * @param string $filter 'collections' or 'data'
309
     */
310
    private function findTwigDataDependencies($filter)
311
    {
312 103
        $regex = '/{[{%](?:.+)?(?:' . $filter . ')(?:\.|\[\')(\w+)(?:\'\])?.+[%}]}/';
313 103
        $results = array();
314
315 103
        preg_match_all($regex, $this->bodyContent, $results);
316
317 103
        $this->dataDependencies[$filter] = array_unique($results[1]);
318 103
    }
319
320
    //
321
    // Permalink and redirect functionality
322
    //
323
324
    /**
325
     * Get the permalink of this Content Item.
326
     *
327
     * @throws \Exception
328
     *
329
     * @return string
330
     */
331
    final public function getPermalink()
332
    {
333 38
        if (!is_null($this->permalink))
334 38
        {
335 8
            return $this->permalink;
336
        }
337
338 36
        if (!is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion())
339 36
        {
340
            throw new \Exception('The permalink for this item has not been set');
341
        }
342
343 36
        $permalink = (is_array($this->frontMatter) && isset($this->frontMatter['permalink'])) ?
344 36
            $this->frontMatter['permalink'] : $this->getPathPermalink();
345
346 36
        if (is_array($permalink))
347 36
        {
348 18
            $this->permalink = $permalink[0];
349 18
            array_shift($permalink);
350 18
            $this->redirects = $permalink;
351 18
        }
352
        else
353
        {
354 23
            $this->permalink = $permalink;
355 23
            $this->redirects = array();
356
        }
357
358 36
        $this->permalink = $this->sanitizePermalink($this->permalink);
359 36
        $this->permalink = str_replace(DIRECTORY_SEPARATOR, '/', $this->permalink);
360 36
        $this->permalink = '/' . ltrim($this->permalink, '/'); // Permalinks should always use '/' and not be OS specific
361
362 36
        return $this->permalink;
363
    }
364
365
    /**
366
     * Get an array of URLs that will redirect to.
367
     *
368
     * @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...
369
     */
370
    final public function getRedirects()
371
    {
372 13
        if (is_null($this->redirects))
373 13
        {
374 2
            $this->getPermalink();
375 2
        }
376
377 13
        return $this->redirects;
378
    }
379
380
    /**
381
     * Get the permalink based off the location of where the file is relative to the website. This permalink is to be
382
     * used as a fallback in the case that a permalink is not explicitly specified in the Front Matter.
383
     *
384
     * @return string
385
     */
386
    private function getPathPermalink()
387
    {
388
        // Remove the protocol of the path, if there is one and prepend a '/' to the beginning
389 3
        $cleanPath = preg_replace('/[\w|\d]+:\/\//', '', $this->getRelativeFilePath());
390 3
        $cleanPath = ltrim($cleanPath, DIRECTORY_SEPARATOR);
391
392
        // Handle vfs:// paths by replacing their forward slashes with the OS appropriate directory separator
393 3
        if (DIRECTORY_SEPARATOR !== '/')
394 3
        {
395
            $cleanPath = str_replace('/', DIRECTORY_SEPARATOR, $cleanPath);
396
        }
397
398
        // Check the first folder and see if it's a data folder (starts with an underscore) intended for stakx
399 3
        $folders = explode(DIRECTORY_SEPARATOR, $cleanPath);
400
401 3
        if (substr($folders[0], 0, 1) === '_')
402 3
        {
403 1
            array_shift($folders);
404 1
        }
405
406 3
        $cleanPath = implode(DIRECTORY_SEPARATOR, $folders);
407
408 3
        return $cleanPath;
409
    }
410
411
    /**
412
     * Sanitize a permalink to remove unsupported characters or multiple '/' and replace spaces with hyphens.
413
     *
414
     * @param string $permalink A permalink
415
     *
416
     * @return string $permalink The sanitized permalink
417
     */
418
    private function sanitizePermalink($permalink)
419
    {
420
        // Remove multiple '/' together
421 36
        $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...
422
423
        // Replace all spaces with hyphens
424 36
        $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...
425
426
        // Remove all disallowed characters
427 36
        $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...
428
429
        // Handle unnecessary extensions
430 36
        $extensionsToStrip = array('twig');
431
432 36
        if (in_array($this->fs->getExtension($permalink), $extensionsToStrip))
433 36
        {
434 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...
435 4
        }
436
437
        // Remove any special characters before a sane value
438 36
        $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...
439
440
        // Convert permalinks to lower case
441 36
        $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...
442
443 36
        return $permalink;
444
    }
445
446
    //
447
    // WritableFrontMatter Implementation
448
    //
449
450
    /**
451
     * {@inheritdoc}
452
     */
453
    final public function evaluateFrontMatter($variables = null)
454
    {
455 6
        if (!is_null($variables))
456 6
        {
457 6
            $this->frontMatter = array_merge($this->frontMatter, $variables);
458 6
            $this->evaluateYaml($this->frontMatter);
459 6
        }
460 6
    }
461
462
    /**
463
     * {@inheritdoc}
464
     */
465
    final public function getFrontMatter($evaluateYaml = true)
466
    {
467 28
        if (is_null($this->frontMatter))
468 28
        {
469
            $this->frontMatter = array();
470
        }
471 28
        elseif (!$this->frontMatterEvaluated && $evaluateYaml)
472
        {
473 23
            $this->evaluateYaml($this->frontMatter);
474 22
        }
475
476 27
        return $this->frontMatter;
477
    }
478
479
    /**
480
     * {@inheritdoc}
481
     */
482
    final public function hasExpandedFrontMatter()
483
    {
484 2
        return !is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion();
485
    }
486
487
    /**
488
     * {@inheritdoc.
489
     */
490
    final public function appendFrontMatter(array $frontMatter)
491
    {
492
        foreach ($frontMatter as $key => $value)
493
        {
494
            $this->writableFrontMatter[$key] = $value;
495
        }
496
    }
497
498
    /**
499
     * {@inheritdoc.
500
     */
501
    final public function deleteFrontMatter($key)
502
    {
503
        if (!isset($this->writableFrontMatter[$key]))
504
        {
505
            return;
506
        }
507
508
        unset($this->writableFrontMatter[$key]);
509
    }
510
511
    /**
512
     * {@inheritdoc.
513
     */
514
    final public function setFrontMatter(array $frontMatter)
515
    {
516 2
        if (!is_array($frontMatter))
517 2
        {
518
            throw new \InvalidArgumentException('An array is required for setting the writable FrontMatter');
519
        }
520
521 2
        $this->writableFrontMatter = $frontMatter;
522 2
    }
523
524
    /**
525
     * Evaluate an array of data for FrontMatter variables. This function will modify the array in place.
526
     *
527
     * @param array $yaml An array of data containing FrontMatter variables
528
     *
529
     * @throws YamlVariableUndefinedException A FrontMatter variable used does not exist
530
     */
531
    private function evaluateYaml(&$yaml)
532
    {
533
        try
534
        {
535 29
            $this->frontMatterParser = new Parser($yaml);
536 28
            $this->frontMatterEvaluated = true;
537
        }
538 29
        catch (\Exception $e)
539
        {
540 1
            throw FileAwareException::castException($e, $this->getRelativeFilePath());
541
        }
542 28
    }
543
544
    //
545
    // ArrayAccess Implementation
546
    //
547
548
    /**
549
     * {@inheritdoc}
550
     */
551
    public function offsetSet($offset, $value)
552
    {
553
        if (is_null($offset))
554
        {
555
            throw new \InvalidArgumentException('$offset cannot be null');
556
        }
557
558
        $this->writableFrontMatter[$offset] = $value;
559
    }
560
561
    /**
562
     * {@inheritdoc}
563
     */
564
    public function offsetExists($offset)
565
    {
566 31
        if (isset($this->writableFrontMatter[$offset]) || isset($this->frontMatter[$offset]))
567 31
        {
568 30
            return true;
569
        }
570
571 14
        $fxnCall = 'get' . ucfirst($offset);
572
573 14
        return method_exists($this, $fxnCall) && in_array($fxnCall, static::$whiteListFunctions);
574
    }
575
576
    /**
577
     * {@inheritdoc}
578
     */
579
    public function offsetUnset($offset)
580
    {
581
        unset($this->writableFrontMatter[$offset]);
582
    }
583
584
    /**
585
     * {@inheritdoc}
586
     */
587
    public function offsetGet($offset)
588
    {
589 47
        $fxnCall = 'get' . ucfirst($offset);
590
591 47
        if (in_array($fxnCall, self::$whiteListFunctions) && method_exists($this, $fxnCall))
592 47
        {
593 6
            return call_user_func_array(array($this, $fxnCall), array());
594
        }
595
596 41
        if (isset($this->writableFrontMatter[$offset]))
597 41
        {
598
            return $this->writableFrontMatter[$offset];
599
        }
600
601 41
        if (isset($this->frontMatter[$offset]))
602 41
        {
603 40
            return $this->frontMatter[$offset];
604
        }
605
606 4
        return null;
607
    }
608
}
609