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

LinkFormatter::getMatchFormatter()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

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