Passed
Branch master (7c3f6c)
by Javi
02:38
created

MarkdownFileParser::parse()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 4
nop 2
1
<?php
2
3
namespace itsjavi\Flatdown\Markdown;
4
5
use cebe\markdown\GithubMarkdown;
6
use cebe\markdown\Markdown;
7
use cebe\markdown\MarkdownExtra;
8
use Symfony\Component\Yaml\Yaml;
9
10
class MarkdownFileParser
11
{
12
    /**
13
     * Parses the given Markdown file
14
     *
15
     * @param string $filename
16
     * @param array $options
17
     *
18
     * @return MarkdownFile
19
     */
20
    public function parse($filename, array $options)
21
    {
22
        $file = new MarkdownFile($filename);
23
24
        $content = $file->load()->content;
25
26
        $file->metadata = $this->parseMetadata($content, $options);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->parseMetadata($content, $options) can also be of type array or object<stdClass>. However, the property $metadata is declared as type string. 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...
27
        $file->html     = trim($this->createFlavoredParser($options)->parse($content));
28
        $parsedTitle    = $this->parseTitle($file->html);
29
        $file->title    = (isset($file->metadata['title']) && strlen($file->metadata['title']))
30
            ? $file->metadata['title'] : $parsedTitle;
31
32
        return $file;
33
    }
34
35
    /**
36
     * @param string $content
37
     * @param array $options
38
     *
39
     * @return array
40
     */
41
    private function parseMetadata(&$content, array $options)
42
    {
43
        $metadataLines = [];
44
        $contentLines  = explode("\n", $content);
45
        $delimiter     = isset($options['metadataDelimiter']) ? $options['metadataDelimiter'] : '---';
46
        $indentation   = isset($options['metadataIndentation']) ? $options['metadataIndentation'] : 4;
47
48
        if (empty($contentLines) || ($contentLines[0] !== $delimiter)) {
49
            return [];
50
        }
51
52
        array_shift($contentLines);
53
54
        $line = 0;
55
        while (isset($contentLines[$line]) && ($contentLines[$line] != $delimiter)) {
56
            $metadataLines[] = $indentation ?
57
                preg_replace('/^(\s{' . $indentation . '})/', '', $contentLines[$line]) :
58
                $contentLines[$line];
59
            $line++;
60
        }
61
62
        if ($contentLines[$line] == $delimiter) {
63
            $line++;
64
        }
65
66
        $content = [];
67
68
        for ($i = $line; $i < count($contentLines); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
69
            $content[] = $contentLines[$i];
70
        }
71
72
        $content  = implode("\n", $content);
73
        $metadata = implode("\n", $metadataLines);
74
75
        return Yaml::parse($metadata);
76
    }
77
78
    /**
79
     * @param string $html
80
     *
81
     * @return string
82
     */
83
    private function parseTitle(&$html)
84
    {
85
        $parts = explode('</h1>', $html, 2);
86
87
        if (count($parts) != 2) {
88
            return '';
89
        }
90
        $title = preg_replace('/(.*)(\<h1.*\>)(.*)/', '$3', $parts[0]);
91
        $html  = preg_replace('/(.*)(\<h1.*)/', '$1', $parts[0]) . $parts[1];
92
93
        return $title;
94
    }
95
96
    /**
97
     * @param array $options
98
     *
99
     * @return Markdown
100
     */
101
    private function createFlavoredParser(array $options)
102
    {
103
        $parser = null;
0 ignored issues
show
Unused Code introduced by
$parser is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
104
        $flavor = isset($options['flavor']) ? $options['flavor'] : 'extra';
105
106
        switch ($flavor) {
107
            case 'default':
108
                $parser = new Markdown();
109
                break;
110
            case 'extra':
111
                $parser = new MarkdownExtra();
112
                break;
113
            case 'github':
114
                $parser = new GithubMarkdown();
115
                break;
116
            default:
117
                throw new \InvalidArgumentException('Flavor not supported: ' . $flavor);
118
        }
119
120
        foreach ($options as $optName => $optValue) {
121
            $parser->$optName = $optValue;
122
        }
123
124
        return $parser;
125
    }
126
}
127