Completed
Branch master (8e0976)
by Adam
04:13
created

Template::parse()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 6
nop 1
dl 0
loc 23
rs 8.9297
c 0
b 0
f 0
1
<?php
2
3
namespace Coyote\Services\Parser\Parsers;
4
5
use Coyote\Repositories\Contracts\WikiRepositoryInterface as WikiRepository;
6
7
class Template implements ParserInterface
8
{
9
    const TEMPLATE_REGEXP = "{{Template:(.*?)(\|(.*))*}}";
10
11
    /**
12
     * @var WikiRepository
13
     */
14
    protected $wiki;
15
16
    /**
17
     * Template constructor.
18
     * @param WikiRepository $wiki
19
     */
20
    public function __construct(WikiRepository $wiki)
21
    {
22
        $this->wiki = $wiki;
23
    }
24
25
    /**
26
     * @param string $text
27
     * @return string
28
     */
29
    public function parse($text)
30
    {
31
        if (!preg_match_all('/' . self::TEMPLATE_REGEXP . '/i', $text, $matches)) {
32
            return $text;
33
        }
34
35
        for ($i = 0, $count = count($matches[0]); $i < $count; $i++) {
36
            $path = str_replace(' ', '_', $matches[1][$i]);
37
            $args = $matches[3][$i] ? explode('|', $matches[3][$i]) : [];
38
39
            $wiki = $this->wiki->findByPath($path);
40
41
            if ($wiki) {
42
                foreach ($args as $key => $value) {
43
                    $wiki->text = str_replace('{{' . ($key + 1) . '}}', $value, $wiki->text);
44
                }
45
46
                $text = str_replace($matches[0][$i], $wiki->text, $text);
47
            }
48
        }
49
50
        return $text;
51
    }
52
}
53