Passed
Push — master ( 1564fa...d2ad69 )
by Kacper
03:00 queued 15s
created

CommentMatcher::match()   C

Complexity

Conditions 7
Paths 28

Size

Total Lines 35
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 7

Importance

Changes 8
Bugs 1 Features 0
Metric Value
c 8
b 1
f 0
dl 0
loc 35
ccs 24
cts 24
cp 1
rs 6.7272
cc 7
eloc 20
nc 28
nop 2
crap 7
1
<?php
2
/**
3
 * Highlighter
4
 *
5
 * Copyright (C) 2015, Some right reserved.
6
 *
7
 * @author Kacper "Kadet" Donat <[email protected]>
8
 *
9
 * Contact with author:
10
 * Xmpp: [email protected]
11
 * E-mail: [email protected]
12
 *
13
 * From Kadet with love.
14
 */
15
16
namespace Kadet\Highlighter\Matcher;
17
18
19
use Kadet\Highlighter\Parser\Token;
20
use Kadet\Highlighter\Parser\TokenFactoryInterface;
21
22
class CommentMatcher implements MatcherInterface
23
{
24
    private $singleLine = [];
25
    private $multiLine  = [];
26
27
    /**
28
     * CommentMatcher constructor.
29
     *
30
     * @param array $singleLine
31
     * @param array $multiLine
32
     */
33 4
    public function __construct(array $singleLine, array $multiLine)
34
    {
35 4
        $this->singleLine = $singleLine;
36 4
        $this->multiLine = $multiLine;
37 4
    }
38
39
40
    /**
41
     * Matches all occurrences and returns token list
42
     *
43
     * @param string                $source Source to match tokens
44
     *
45
     * @param TokenFactoryInterface $factory
46
     *
47
     * @return array
48
     */
49 4
    public function match($source, TokenFactoryInterface $factory)
50
    {
51 4
        $result = [];
52 4
        $all = [];
53
54 4
        foreach ($this->multiLine as $name => $comment) {
55
            $comment = array_map(function ($e) { return preg_quote($e, '/'); }, $comment);
56
57 2
            $all[] = [$name, "/{$comment[0]}(.*?){$comment[1]}/ms"];
58 4
        }
59
60 4
        foreach ($this->singleLine as $name => $comment) {
61 2
            $comment = preg_quote($comment, '/');
62 2
            $all[] = [$name, "/{$comment}(.*)/"];
63 4
        }
64
65 4
        foreach ($all as $i => $comment) {
66 4
            $matches = [];
67
68 4
            $name = $comment[0];
69 4
            $name = is_string($name) ? $name : null;
70 4
            $regex = $comment[1];
71
72 4
            if (preg_match_all($regex, $source, $matches, PREG_OFFSET_CAPTURE)) {
73 4
                foreach ($matches[0] as $match) {
74 4
                    $token = $factory->create(['pos' => $match[1], 'length' => strlen($match[0]), 'index' => $i, $name]);
75 4
                    $result[spl_object_hash($token)] = $token;
76 4
                    $result[spl_object_hash($token->getEnd())] = $token->getEnd();
77 4
                }
78 4
            }
79 4
        }
80
81
82 4
        return $result;
83
    }
84
}