Completed
Pull Request — develop (#33)
by Michael
02:17
created

LinkFormatter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 3
c 2
b 1
f 0
lcom 0
cbo 0
dl 0
loc 38
ccs 13
cts 13
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 7 1
A getMatchFormatter() 0 13 2
1
<?php
2
3
namespace Crummy\Phlack\Common\Formatter;
4
5
class LinkFormatter implements FormatterInterface
6
{
7
    const HTML = '/ <a (?:.*?) href=[\'"](.+)[\'"] (?:.*)> (.+?) <\/a> /x';
8
    const MARKDOWN = '/\[(.*?)\]\((.+?)\)/';
9
10
    /**
11
     * @param string $text
12
     *
13
     * @return string
14
     */
15 3
    public function format($text)
16
    {
17 3
        $text = preg_replace_callback(self::HTML, $this->getMatchFormatter(), $text);
18 3
        $text = preg_replace_callback(self::MARKDOWN, $this->getMatchFormatter(2, 1), $text);
19
20 3
        return $text;
21
    }
22
23
    /**
24
     * @param int $linkIdx  The index of the matches containing the resource link
25
     * @param int $labelIdx The index of the matches containing the label (if one exists)
26
     *
27
     * @return \Closure A callable to be passed to preg_replace_callback
28
     */
29
    protected function getMatchFormatter($linkIdx = 1, $labelIdx = 2)
30
    {
31 3
        return function (array $matches) use ($linkIdx, $labelIdx) {
32 3
            $out = '<';
33 3
            $out .= $matches[$linkIdx];
34 3
            if (!empty($matches[$labelIdx])) {
35 2
                $out .= '|'.$matches[$labelIdx];
36 2
            }
37 3
            $out .= '>';
38
39 3
            return $out;
40 3
        };
41
    }
42
}
43