Completed
Push — master ( 89bfcf...4ab803 )
by Vladimir
02:41
created

FrontMatterDocument   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 480
Duplicated Lines 3.13 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 77.69%

Importance

Changes 0
Metric Value
wmc 56
c 0
b 0
f 0
lcom 1
cbo 8
dl 15
loc 480
rs 6.5957
ccs 101
cts 130
cp 0.7769

25 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
getContent() 0 1 ?
A getImportDependencies() 0 4 1
A getLineOffset() 0 4 1
A getName() 0 4 1
A getObjectName() 0 4 1
A hasTwigDependency() 0 6 3
A hasImportDependency() 0 4 1
B refreshFileContent() 4 53 7
A findTwigDataDependencies() 0 12 1
A findTwigImportDependencies() 0 14 2
A isDraft() 0 4 1
A getIterator() 0 4 1
C buildPermalink() 11 27 7
A evaluateFrontMatter() 0 8 2
A getFrontMatter() 0 13 4
A hasExpandedFrontMatter() 0 4 2
A appendFrontMatter() 0 7 2
A deleteFrontMatter() 0 9 2
A setFrontMatter() 0 9 2
A evaluateYaml() 0 15 2
A offsetSet() 0 9 2
A offsetExists() 0 11 4
A offsetUnset() 0 4 1
B offsetGet() 0 21 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FrontMatterDocument often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FrontMatterDocument, and based on these observations, apply Extract Interface, too.

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\PermalinkDocument;
11
use allejo\stakx\Document\TrackableDocument;
12
use allejo\stakx\Document\TwigDocument;
13
use allejo\stakx\Exception\FileAwareException;
14
use allejo\stakx\Exception\InvalidSyntaxException;
15
use allejo\stakx\FrontMatter\Exception\YamlVariableUndefinedException;
16
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
17
use Symfony\Component\Filesystem\Exception\IOException;
18
use Symfony\Component\Yaml\Exception\ParseException;
19
use Symfony\Component\Yaml\Yaml;
20
21
abstract class FrontMatterDocument extends PermalinkDocument implements
22
    TrackableDocument,
23
    TwigDocument,
24
    WritableDocumentInterface
25
{
26
    const TEMPLATE = "---\n%s\n---\n\n%s";
27
28
    /**
29
     * The names of FrontMatter keys that are specially defined for all Documents
30
     *
31
     * @var array
32
     */
33
    public static $specialFrontMatterKeys = array(
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $specialFrontMatterKeys exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
34
        'filename', 'basename'
35
    );
36
37
    protected static $whiteListFunctions = array(
38
        'getPermalink', 'getRedirects', 'getTargetFile', 'getName', 'getFilePath', 'getRelativeFilePath', 'getContent',
39
        'getExtension', 'getFrontMatter'
40
    );
41
42
    /**
43
     * @var array
44
     */
45
    protected $importDependencies;
46
47
    /**
48
     * An array to keep track of collection or data dependencies used inside of a Twig template.
49
     *
50
     * $dataDependencies['collections'] = array()
51
     * $dataDependencies['data'] = array()
52
     *
53
     * @var array
54
     */
55
    protected $dataDependencies;
56
57
    /**
58
     * FrontMatter values that can be injected or set after the file has been parsed. Values in this array will take
59
     * precedence over values in $frontMatter.
60
     *
61
     * @var array
62
     */
63
    protected $writableFrontMatter;
64
65
    /**
66
     * A list of Front Matter values that should not be returned directly from the $frontMatter array. Values listed
67
     * here have dedicated functions that handle those Front Matter values and the respective functions should be called
68
     * instead.
69
     *
70
     * @var string[]
71
     */
72
    protected $frontMatterBlacklist;
73
74
    /**
75
     * Set to true if the front matter has already been evaluated with variable interpolation.
76
     *
77
     * @var bool
78
     */
79
    protected $frontMatterEvaluated;
80
81
    /**
82
     * @var Parser
83
     */
84
    protected $frontMatterParser;
85
86
    /**
87
     * An array containing the Yaml of the file.
88
     *
89
     * @var array
90
     */
91
    protected $frontMatter;
92
93
    /**
94
     * Set to true if the body has already been parsed as markdown or any other format.
95
     *
96
     * @var bool
97
     */
98
    protected $bodyContentEvaluated;
99
100
    /**
101
     * Only the body of the file, i.e. the content.
102
     *
103
     * @var string
104
     */
105
    protected $bodyContent;
106
107
    /**
108
     * The number of lines that Twig template errors should offset.
109
     *
110
     * @var int
111
     */
112
    private $lineOffset;
113
114
    /**
115
     * ContentItem constructor.
116
     *
117
     * @param string $filePath The path to the file that will be parsed into a ContentItem
118
     *
119
     * @throws FileNotFoundException The given file path does not exist
120
     * @throws IOException           The file was not a valid ContentItem. This would meam there was no front matter or
121
     *                               no body
122
     */
123 141
    public function __construct($filePath)
124
    {
125 141
        $this->frontMatterBlacklist = array('permalink', 'redirects');
126 141
        $this->writableFrontMatter = array();
127 141
        $this->importDependencies = array();
128
129 141
        parent::__construct($filePath);
130 129
    }
131
132
    /**
133
     * Return the body of the Content Item.
134
     *
135
     * @return string
136
     */
137
    abstract public function getContent();
138
139
    final public function getImportDependencies()
140
    {
141
        return $this->importDependencies;
142
    }
143
144
    /**
145
     * The number of lines that are taken up by FrontMatter and white space.
146
     *
147
     * @return int
148
     */
149
    final public function getLineOffset()
150
    {
151
        return $this->lineOffset;
152
    }
153
154
    /**
155
     * Get the name of the item, which is just the filename without the extension.
156
     *
157
     * @deprecated use getObjectName() instead
158
     * @return string
159
     */
160
    final public function getName()
161
    {
162
        return $this->getObjectName();
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168 46
    public function getObjectName()
169
    {
170 46
        return $this->getBaseName();
171
    }
172
173
    /**
174
     * Check whether this object has a reference to a collection or data item.
175
     *
176
     * @param string $namespace 'collections' or 'data'
177
     * @param string $needle
178
     *
179
     * @return bool
180
     */
181 21
    final public function hasTwigDependency($namespace, $needle)
182
    {
183
        return
184 21
            in_array($needle, $this->dataDependencies[$namespace]) ||
185 21
            (is_null($needle) && !empty($this->dataDependencies[$namespace]));
186
    }
187
188
    /**
189
     * Check whether this object has an "import" or "from" reference to a given path.
190
     *
191
     * @param  string $filePath
192
     *
193
     * @return bool
194
     */
195
    final public function hasImportDependency($filePath)
196
    {
197
        return (in_array($filePath, $this->importDependencies));
198
    }
199
200
    /**
201
     * Read the file, and parse its contents.
202
     */
203 141
    final public function refreshFileContent()
204
    {
205
        // This function can be called after the initial object was created and the file may have been deleted since the
206
        // creation of the object.
207 141 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...
208
        {
209 2
            throw new FileNotFoundException(null, 0, null, $this->filePath);
210
        }
211
212
        // $fileStructure[1] is the YAML
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
213
        // $fileStructure[2] is the amount of new lines after the closing `---` and the beginning of content
214
        // $fileStructure[3] is the body of the document
215 140
        $fileStructure = array();
216
217 140
        $rawFileContents = file_get_contents($this->filePath);
218 140
        preg_match('/---\R(.*?\R)?---(\s+)(.*)/s', $rawFileContents, $fileStructure);
219
220 140
        if (count($fileStructure) != 4)
221
        {
222 9
            throw new InvalidSyntaxException('Invalid FrontMatter file', 0, null, $this->getRelativeFilePath());
223
        }
224
225 131
        if (empty(trim($fileStructure[3])))
226
        {
227 1
            throw new InvalidSyntaxException('FrontMatter files must have a body to render', 0, null, $this->getRelativeFilePath());
228
        }
229
230
        // The hard coded 1 is the offset used to count the new line used after the first `---` that is not caught in the regex
231 130
        $this->lineOffset = substr_count($fileStructure[1], "\n") + substr_count($fileStructure[2], "\n") + 1;
232 130
        $this->bodyContent = $fileStructure[3];
233
234 130
        if (!empty(trim($fileStructure[1])))
235
        {
236 92
            $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...
237
238 92
            if (!empty($this->frontMatter) && !is_array($this->frontMatter))
239
            {
240 92
                throw new ParseException('The evaluated FrontMatter should be an array');
241
            }
242
        }
243
        else
244
        {
245 41
            $this->frontMatter = array();
246
        }
247
248 129
        $this->frontMatterEvaluated = false;
249 129
        $this->bodyContentEvaluated = false;
250 129
        $this->permalink = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $permalink.

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...
251
252 129
        $this->findTwigDataDependencies('collections');
253 129
        $this->findTwigDataDependencies('data');
254 129
        $this->findTwigImportDependencies();
255 129
    }
256
257
    /**
258
     * Get all of the references to either DataItems or ContentItems inside of given string.
259
     *
260
     * @param string $filter 'collections' or 'data'
261
     */
262 129
    private function findTwigDataDependencies($filter)
263
    {
264
        // To see what this regex should match and what shouldn't be see:
265
        //     tests/allejo/stakx/Test/FrontMatter/FrontMatterDocumentTest.php
266
267 129
        $regex = "/{[{%].*?(?:$filter)(?:\.|\[['\"])?([^_][^\W]+)?(?:\.|['\"]\])?[^_=]*?[%}]}/";
268 129
        $results = array();
269
270 129
        preg_match_all($regex, $this->bodyContent, $results);
271
272 129
        $this->dataDependencies[$filter] = array_unique($results[1]);
273 129
    }
274
275
    /**
276
     * Get all of the "import" and "from" dependencies from a Twig body.
277
     */
278 129
    private function findTwigImportDependencies()
279
    {
280 129
        $regex = "/{%\s?(?:import|from)\s?['\"](.+)['\"].+/";
281 129
        $results = array();
282
283 129
        preg_match_all($regex, $this->bodyContent, $results);
284
285 129
        if (empty($results[1]))
286
        {
287 129
            return;
288
        }
289
290
        $this->importDependencies = array_unique($results[1]);
291
    }
292
293 4
    public function isDraft()
294
    {
295 4
        return ($this['draft'] === true);
296
    }
297
298 19
    public function getIterator()
299
    {
300 19
        return (new \ArrayIterator($this->frontMatter));
301
    }
302
303
    //
304
    // Permalink and redirect functionality
305
    //
306
307 39
    final protected function buildPermalink()
308
    {
309 39
        if (!is_null($this->permalink))
310
        {
311 8
            return;
312
        }
313
314 37
        if (!is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion())
315
        {
316
            throw new \Exception('The permalink for this item has not been set');
317
        }
318
319 37
        $permalink = (is_array($this->frontMatter) && isset($this->frontMatter['permalink'])) ?
320 37
            $this->frontMatter['permalink'] : $this->getPathPermalink();
321
322 37 View Code Duplication
        if (is_array($permalink))
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...
323
        {
324 19
            $this->permalink = $permalink[0];
325 19
            array_shift($permalink);
326 19
            $this->redirects = $permalink;
327
        }
328
        else
329
        {
330 24
            $this->permalink = $permalink;
331 24
            $this->redirects = array();
332
        }
333 37
    }
334
335
    //
336
    // WritableFrontMatter Implementation
337
    //
338
339
    /**
340
     * {@inheritdoc}
341
     */
342 7
    final public function evaluateFrontMatter($variables = null)
343
    {
344 7
        if (!is_null($variables))
345
        {
346 7
            $this->frontMatter = array_merge($this->frontMatter, $variables);
347 7
            $this->evaluateYaml($this->frontMatter);
348
        }
349 7
    }
350
351
    /**
352
     * {@inheritdoc}
353
     */
354 29
    final public function getFrontMatter($evaluateYaml = true)
355
    {
356 29
        if (is_null($this->frontMatter))
357
        {
358
            $this->frontMatter = array();
359
        }
360 29
        elseif (!$this->frontMatterEvaluated && $evaluateYaml)
361
        {
362 23
            $this->evaluateYaml($this->frontMatter);
363
        }
364
365 28
        return $this->frontMatter;
366
    }
367
368
    /**
369
     * {@inheritdoc}
370
     */
371 2
    final public function hasExpandedFrontMatter()
372
    {
373 2
        return !is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion();
374
    }
375
376
    /**
377
     * {@inheritdoc.
378
     */
379
    final public function appendFrontMatter(array $frontMatter)
380
    {
381
        foreach ($frontMatter as $key => $value)
382
        {
383
            $this->writableFrontMatter[$key] = $value;
384
        }
385
    }
386
387
    /**
388
     * {@inheritdoc.
389
     */
390
    final public function deleteFrontMatter($key)
391
    {
392
        if (!isset($this->writableFrontMatter[$key]))
393
        {
394
            return;
395
        }
396
397
        unset($this->writableFrontMatter[$key]);
398
    }
399
400
    /**
401
     * {@inheritdoc.
402
     */
403 2
    final public function setFrontMatter(array $frontMatter)
404
    {
405 2
        if (!is_array($frontMatter))
406
        {
407
            throw new \InvalidArgumentException('An array is required for setting the writable FrontMatter');
408
        }
409
410 2
        $this->writableFrontMatter = $frontMatter;
411 2
    }
412
413
    /**
414
     * Evaluate an array of data for FrontMatter variables. This function will modify the array in place.
415
     *
416
     * @param array $yaml An array of data containing FrontMatter variables
417
     *
418
     * @throws YamlVariableUndefinedException A FrontMatter variable used does not exist
419
     */
420 30
    private function evaluateYaml(&$yaml)
421
    {
422
        try
423
        {
424 30
            $this->frontMatterParser = new Parser($yaml, array(
425 30
                'filename' => $this->getFileName(),
426 30
                'basename' => $this->getName(),
0 ignored issues
show
Deprecated Code introduced by
The method allejo\stakx\FrontMatter...tterDocument::getName() has been deprecated with message: use getObjectName() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
427
            ));
428 29
            $this->frontMatterEvaluated = true;
429
        }
430 1
        catch (\Exception $e)
431
        {
432 1
            throw FileAwareException::castException($e, $this->getRelativeFilePath());
433
        }
434 29
    }
435
436
    //
437
    // ArrayAccess Implementation
438
    //
439
440
    /**
441
     * {@inheritdoc}
442
     */
443
    public function offsetSet($offset, $value)
444
    {
445
        if (is_null($offset))
446
        {
447
            throw new \InvalidArgumentException('$offset cannot be null');
448
        }
449
450
        $this->writableFrontMatter[$offset] = $value;
451
    }
452
453
    /**
454
     * {@inheritdoc}
455
     */
456 34
    public function offsetExists($offset)
457
    {
458 34
        if (isset($this->writableFrontMatter[$offset]) || isset($this->frontMatter[$offset]))
459
        {
460 33
            return true;
461
        }
462
463 14
        $fxnCall = 'get' . ucfirst($offset);
464
465 14
        return method_exists($this, $fxnCall) && in_array($fxnCall, static::$whiteListFunctions);
466
    }
467
468
    /**
469
     * {@inheritdoc}
470
     */
471
    public function offsetUnset($offset)
472
    {
473
        unset($this->writableFrontMatter[$offset]);
474
    }
475
476
    /**
477
     * {@inheritdoc}
478
     */
479 51
    public function offsetGet($offset)
480
    {
481 51
        $fxnCall = 'get' . ucfirst($offset);
482
483 51
        if (in_array($fxnCall, self::$whiteListFunctions) && method_exists($this, $fxnCall))
484
        {
485 6
            return call_user_func_array(array($this, $fxnCall), array());
486
        }
487
488 45
        if (isset($this->writableFrontMatter[$offset]))
489
        {
490
            return $this->writableFrontMatter[$offset];
491
        }
492
493 45
        if (isset($this->frontMatter[$offset]))
494
        {
495 44
            return $this->frontMatter[$offset];
496
        }
497
498 5
        return null;
499
    }
500
}
501