Completed
Push — master ( 7aa624...fe99b2 )
by Kevin
02:25
created

HtmlTokenizer::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 22
ccs 16
cts 16
cp 1
rs 9.2
cc 3
eloc 14
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Kevintweber\HtmlTokenizer;
4
5
use Kevintweber\HtmlTokenizer\Tokens\TokenCollection;
6
use Kevintweber\HtmlTokenizer\Tokens\TokenFactory;
7
8
class HtmlTokenizer
9
{
10
    /** @var boolean */
11
    private $throwOnError;
12
13
    /** @var string */
14
    private static $allHtml = '';
15
16
    /**
17
     * Constructor
18
     */
19 7
    public function __construct($throwOnError = false)
20
    {
21 7
        $this->throwOnError = (boolean) $throwOnError;
22 7
    }
23
24
    /**
25
     * Will parse html into tokens.
26
     *
27
     * @param $html string The HTML to tokenize.
28
     *
29
     * @return TokenCollection
30
     */
31 7
    public function parse($html)
32
    {
33 7
        self::$allHtml = $html;
34 7
        $tokens = new TokenCollection();
35 7
        $remainingHtml = trim((string) $html);
36 7
        while (mb_strlen($remainingHtml) > 0) {
37 7
            $token = TokenFactory::buildFromHtml(
38 7
                $remainingHtml,
39 7
                null,
40 7
                $this->throwOnError
41 7
            );
42 7
            if ($token === false) {
43
                // Error has occurred, so we stop.
44 1
                break;
45
            }
46
47 7
            $remainingHtml = $token->parse($remainingHtml);
48 7
            $tokens[] = $token;
49 7
        }
50
51 7
        return $tokens;
52
    }
53
54 85
    public static function getPosition($partialHtml)
55
    {
56 85
        $position = mb_strrpos(self::$allHtml, $partialHtml);
57 85
        $parsedHtml = mb_substr(self::$allHtml, 0, $position);
58 85
        $line = mb_substr_count($parsedHtml, "\n");
59 85
        if ($line === 0) {
60
            return array(
61 85
                'line' => 0,
62
                'position' => $position
63 85
            );
64
        }
65
66 3
        $lastNewLinePosition = mb_strrpos($parsedHtml, "\n");
67
68
        return array(
69 3
            'line' => $line,
70 3
            'position' => mb_strlen(mb_substr($parsedHtml, $lastNewLinePosition))
71 3
        );
72
    }
73
}
74