HighlightFilter::highlight()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 18
rs 9.4285
c 2
b 0
f 0
cc 3
eloc 10
nc 2
nop 3
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: lrlopez
5
 * Date: 24/8/17
6
 * Time: 15:54
7
 */
8
9
namespace AppBundle\Twig;
10
11
12
class HighlightFilter extends \Twig_Extension
13
{
14
    public function getFilters()
15
    {
16
        return array(
17
            new \Twig_SimpleFilter('highlight', [$this, 'highlight'], ['pre_escape' => 'html', 'is_safe' => ['html']]),
18
        );
19
    }
20
21
    public function highlight($string, $needle, $class = 'highlight')
22
    {
23
        if (null === $needle || '' === $needle) {
24
            return $string;
25
        }
26
27
        $needle = preg_quote($needle, '/');
28
29
        $replacements = [
30
            'a' => '[áa]', 'e' => '[ée]', 'i' => '[íi]', 'o' => '[óo]', 'u' => '[úu]',
31
            'A' => '[ÁA]', 'E' => '[ÉE]', 'I' => '[ÍI]', 'O' => '[ÓO]', 'U' => '[ÚU]',
32
            'n' => '[ñn]', 'N' => '[ÑN]'
33
        ];
34
35
        $needle = str_replace(array_keys($replacements), $replacements, $needle);
36
37
        return preg_replace("/(".$needle.")/ui", '<span class="'.htmlentities($class).'">\\1</span>', $string);
38
    }
39
}
40