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

RegexMatcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
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
}