TokenFactory::buildFromHtml()   B
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 9
cts 9
cp 1
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 14
nc 5
nop 3
crap 4
1
<?php
2
3
namespace Kevintweber\HtmlTokenizer\Tokens;
4
5
use Kevintweber\HtmlTokenizer\Exceptions\TokenMatchingException;
6
use Prophecy\Argument\Token\TokenInterface;
7
8
class TokenFactory
9
{
10
    /**
11
     * Factory method to build the correct token.
12
     *
13
     * @param string     $html
14
     * @param Token|null $parent
15
     * @param bool       $throwOnError
16
     *
17
     * @return TokenInterface|null
18
     * @throws TokenMatchingException
19
     */
20 36
    public static function buildFromHtml(string $html, Token $parent = null, bool $throwOnError = true)
21
    {
22
        $matchCriteria = array(
23 36
            'Php' => "/^\s*<\?(php)?\s/i",
24
            'Comment' => "/^\s*<!--/",
25
            'CData' => "/^\s*<!\[CDATA\[/",
26
            'DocType' => "/^\s*<!DOCTYPE /i",
27
            'Element' => "/^\s*<[a-z]/i",
28
            'Text' => "/^[^<]/"
29
        );
30 36
        foreach ($matchCriteria as $className => $regex) {
31 36
            if (preg_match($regex, $html) === 1) {
32 34
                $fullClassName = "Kevintweber\\HtmlTokenizer\\Tokens\\" . $className;
33
34 36
                return new $fullClassName($parent, $throwOnError);
35
            }
36
        }
37
38
        // Error condition
39 6
        if ($throwOnError) {
40 2
            throw new TokenMatchingException();
41
        }
42 4
    }
43
}
44