HtmlMapper::processAliasing()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 4
eloc 7
c 2
b 2
f 0
nc 4
nop 3
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 4
rs 10
1
<?php
2
/**
3
 * @author Oskar van Velden <[email protected]>
4
 * @author Rik van der Kemp <[email protected]>
5
 * @copyright Zicht Online <http://zicht.nl>
6
 */
7
8
namespace Zicht\Bundle\UrlBundle\Aliasing\Mapper;
9
10
use Zicht\Bundle\UrlBundle\Url\Rewriter;
11
12
/**
13
 * Class HtmlMapper
14
 *
15
 * Helper to map urls in an HTML string from internal to public aliasing or vice versa.
16
 *
17
 * @package Zicht\Bundle\UrlBundle\Aliasing
18
 */
19
class HtmlMapper implements UrlMapperInterface
20
{
21
    /**
22
     * Map of [elementName => [attr1, attr2]] where URL's may occur
23
     *
24
     * @var array
25
     */
26
    protected $htmlAttributes;
27
28
    /**
29
     * HtmlMapper constructor.
30
     */
31 10
    public function __construct()
32
    {
33 10
        $this->htmlAttributes = [
34
            'a' => ['href', 'data-href'],
35
            'area' => ['href', 'data-href'],
36
            'option' => ['data-href'],
37
            'iframe' => ['src'],
38
            'form' => ['action'],
39
            'meta' => ['content'],
40
            'link' => ['href']
41
        ];
42 10
    }
43
44
45
    /**
46
     * @{inheritDoc}
47
     */
48 1
    public function supports($contentType)
49
    {
50 1
        return $contentType == 'text/html';
51
    }
52
53
54
    /**
55
     * @{inheritDoc}
56
     */
57 9
    public function processAliasing($html, $mode, Rewriter $rewriter)
58
    {
59 9
        $map = [];
60
61 9
        foreach ($this->htmlAttributes as $tagName => $attributes) {
62 9
            $pattern = sprintf('!(<%s\b[^>]+\b(?:%s)=")([^"]+)(")!', $tagName, join('|', $attributes));
63 9
            if (preg_match_all($pattern, $html, $matches, PREG_SET_ORDER)) {
64 8
                foreach ($matches as $match) {
65 9
                    $map[$match[2]][]= $match;
66
                }
67
            }
68
        }
69
70 9
        return $rewriter->rewriteMatches($html, $mode, $map);
71
    }
72
73
    /**
74
     * Merges given html attributes with the default attributes.
75
     *
76
     * See for a default defined set DependencyInjection/Configuration.php
77
     *
78
     * @param array $attributes
79
     */
80 2
    public function addAttributes($attributes)
81
    {
82 2
        $this->htmlAttributes = array_merge_recursive(
83 2
            $this->htmlAttributes,
84 2
            $attributes
85
        );
86 2
    }
87
}
88