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

RegexMatcher   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 95%

Importance

Changes 9
Bugs 1 Features 0
Metric Value
wmc 5
c 9
b 1
f 0
lcom 1
cbo 2
dl 0
loc 52
ccs 19
cts 20
cp 0.95
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B match() 0 25 4
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
use Kadet\Highlighter\Parser\Token;
19
use Kadet\Highlighter\Parser\TokenFactoryInterface;
20
21
class RegexMatcher implements MatcherInterface
22
{
23
    private $regex;
24
    private $groups;
25
26
    /**
27
     * RegexMatcher constructor.
28
     *
29
     * @param            $regex
30
     * @param array|null $groups
31
     */
32 7
    public function __construct($regex, array $groups = [1 => null])
33
    {
34 7
        $this->regex = $regex;
35 7
        $this->groups = $groups;
36 7
    }
37
38
    /**
39
     * Matches all occurrences and returns token list
40
     *
41
     * @param string                $source Source to match tokens
42
     *
43
     * @param TokenFactoryInterface $factory
44
     *
45
     * @return array
46
     */
47 7
    public function match($source, TokenFactoryInterface $factory)
48
    {
49 7
        preg_match_all($this->regex, $source, $matches, PREG_OFFSET_CAPTURE);
50 7
        $matches = array_intersect_key($matches, $this->groups);
51
52 7
        $result = [];
53 7
        foreach ($matches as $id => $group) {
54 7
            $name = $this->groups[$id];
55
56 7
            foreach ($group as $match) {
57 7
                if ($match[1] === -1) {
58
                    continue;
59
                }
60
61
                /** @var Token $token */
62 7
                $token = $factory->create([$name, 'pos' => $match[1], 'length' => strlen($match[0])]);
63
64 7
                $end = $token->getEnd();
65 7
                $result[spl_object_hash($token)] = $token;
66 7
                $result[spl_object_hash($end)]   = $end;
67 7
            }
68 7
        }
69
70 7
        return $result;
71
    }
72
}