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 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 |
||
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( |
||
|
|||
34 | 'filename', 'basename' |
||
35 | ); |
||
36 | |||
37 | protected static $whiteListFunctions = array( |
||
38 | 'getPermalink', 'getRedirects', 'getTargetFile', 'getName', 'getFilePath', 'getRelativeFilePath', 'getContent', |
||
39 | 'getExtension', 'getFrontMatter', 'getBasename' |
||
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) |
|
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() |
||
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() |
||
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() |
||
164 | |||
165 | /** |
||
166 | * {@inheritdoc} |
||
167 | */ |
||
168 | 47 | public function getObjectName() |
|
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) |
|
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) |
||
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)) |
208 | 141 | { |
|
209 | 2 | throw new FileNotFoundException(null, 0, null, $this->filePath); |
|
210 | } |
||
211 | |||
212 | // $fileStructure[1] is the YAML |
||
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 | 140 | { |
|
222 | 9 | throw new InvalidSyntaxException('Invalid FrontMatter file', 0, null, $this->getRelativeFilePath()); |
|
223 | } |
||
224 | |||
225 | 131 | if (empty(trim($fileStructure[3]))) |
|
226 | 131 | { |
|
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 | 130 | { |
|
236 | 92 | $this->frontMatter = Yaml::parse($fileStructure[1], Yaml::PARSE_DATETIME); |
|
237 | |||
238 | 92 | if (!empty($this->frontMatter) && !is_array($this->frontMatter)) |
|
239 | 92 | { |
|
240 | 1 | throw new ParseException('The evaluated FrontMatter should be an array'); |
|
241 | } |
||
242 | 91 | } |
|
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; |
|
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) |
|
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 | 129 | { |
|
287 | 129 | return; |
|
288 | } |
||
289 | |||
290 | $this->importDependencies = array_unique($results[1]); |
||
291 | } |
||
292 | |||
293 | 4 | public function isDraft() |
|
297 | |||
298 | 19 | public function getIterator() |
|
302 | |||
303 | // |
||
304 | // Permalink and redirect functionality |
||
305 | // |
||
306 | |||
307 | 42 | final public function buildPermalink($force = false) |
|
308 | { |
||
309 | 42 | if (!is_null($this->permalink) && !$force) |
|
310 | 42 | { |
|
311 | 8 | return; |
|
312 | } |
||
313 | |||
314 | 40 | if (!is_null($this->frontMatterParser) && $this->frontMatterParser->hasExpansion()) |
|
315 | 40 | { |
|
316 | throw new \Exception('The permalink for this item has not been set'); |
||
317 | } |
||
318 | |||
319 | 40 | $permalink = (is_array($this->frontMatter) && isset($this->frontMatter['permalink'])) ? |
|
320 | 40 | $this->frontMatter['permalink'] : $this->getPathPermalink(); |
|
321 | |||
322 | 40 | View Code Duplication | if (is_array($permalink)) |
323 | 40 | { |
|
324 | 22 | $this->permalink = $permalink[0]; |
|
325 | 22 | array_shift($permalink); |
|
326 | 22 | $this->redirects = $permalink; |
|
327 | 22 | } |
|
328 | else |
||
329 | { |
||
330 | 24 | $this->permalink = $permalink; |
|
331 | 24 | $this->redirects = array(); |
|
332 | } |
||
333 | 40 | } |
|
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 | 7 | { |
|
346 | 7 | $this->frontMatter = array_merge($this->frontMatter, $variables); |
|
347 | 7 | $this->evaluateYaml($this->frontMatter); |
|
348 | 7 | } |
|
349 | 7 | } |
|
350 | |||
351 | /** |
||
352 | * {@inheritdoc} |
||
353 | */ |
||
354 | 30 | final public function getFrontMatter($evaluateYaml = true) |
|
355 | { |
||
356 | 30 | if (is_null($this->frontMatter)) |
|
357 | 30 | { |
|
358 | $this->frontMatter = array(); |
||
359 | } |
||
360 | 30 | elseif (!$this->frontMatterEvaluated && $evaluateYaml) |
|
361 | { |
||
362 | 24 | $this->evaluateYaml($this->frontMatter); |
|
363 | 23 | } |
|
364 | |||
365 | 29 | return $this->frontMatter; |
|
366 | } |
||
367 | |||
368 | /** |
||
369 | * {@inheritdoc} |
||
370 | */ |
||
371 | 2 | final public function hasExpandedFrontMatter() |
|
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 | 2 | { |
|
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 | 31 | private function evaluateYaml(&$yaml) |
|
421 | { |
||
422 | try |
||
423 | { |
||
424 | 31 | $this->frontMatterParser = new Parser($yaml, array( |
|
425 | 31 | 'filename' => $this->getFileName(), |
|
426 | 31 | 'basename' => $this->getObjectName(), |
|
427 | 31 | )); |
|
428 | 30 | $this->frontMatterEvaluated = true; |
|
429 | } |
||
430 | 31 | catch (\Exception $e) |
|
431 | { |
||
432 | 1 | throw FileAwareException::castException($e, $this->getRelativeFilePath()); |
|
433 | } |
||
434 | 30 | } |
|
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 | 34 | { |
|
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) |
||
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 | 51 | { |
|
485 | 6 | return call_user_func_array(array($this, $fxnCall), array()); |
|
486 | } |
||
500 | } |
||
501 |
Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.