JsonHalMapper   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
c 2
b 0
f 0
dl 0
loc 35
ccs 0
cts 18
cp 0
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A processAliasing() 0 22 3
1
<?php
2
/**
3
 * @author Muhammed Akbulut <[email protected]>
4
 * @copyright Zicht Online <http://zicht.nl>
5
 */
6
7
namespace Zicht\Bundle\UrlBundle\Aliasing\Mapper;
8
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Zicht\Bundle\UrlBundle\Url\Rewriter;
11
12
/**
13
 * Class JsonHalMapper
14
 *
15
 * Helper to map urls in an JSON HAL string from internal to public aliasing or vice versa.
16
 *
17
 * @package Zicht\Bundle\UrlBundle\Aliasing
18
 */
19
class JsonHalMapper extends AbstractMapper
20
{
21
    /**
22
     * Constructor
23
     */
24
    public function __construct()
25
    {
26
        parent::__construct(['application/hal+json'], '/("href":")(.*)(")/U');
27
    }
28
29
    /**
30
     * {@inheritDoc}
31
     */
32
    public function processAliasing($content, $mode, Rewriter $rewriter)
33
    {
34
        $options = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
35
36
        // Json is escaped by default we remove the escaping to replace the url. The escaping is added after
37
        $content = json_encode(json_decode($content, false, 512, $options), JSON_UNESCAPED_SLASHES);
38
39
        if (!preg_match_all($this->pattern, $content, $matches, PREG_SET_ORDER)) {
40
            // early return: if there are no matches, no need for the rest of the processing.
41
            return $content;
42
        }
43
        $groups = [];
44
        foreach ($matches as $match) {
45
            $groups[$match[2]][] = $match;
46
        }
47
48
        $content = $rewriter->rewriteMatches($content, $mode, $groups);
49
50
        // Use the JsonResponse setData method so the content is escaped as we are expecting.
51
        $jsonResponse = new JsonResponse(json_decode($content));
52
53
        return $jsonResponse->getContent();
54
    }
55
}
56