Passed
Push — feature/depend-on-metadata-inf... ( ef854e...953c11 )
by
unknown
39:13 queued 32:26
created

HtmlMapper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 66
ccs 0
cts 34
cp 0
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

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