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

HtmlMapper::supports()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
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