JsonpHandler::getCallback()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\View;
13
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
17
18
/**
19
 * Implements a custom handler for JSONP leveraging the ViewHandler.
20
 *
21
 * @author Lukas K. Smith <[email protected]>
22
 */
23
final class JsonpHandler
24
{
25
    private $callbackParam;
26
27 6
    public function __construct(string $callbackParam)
28
    {
29 6
        $this->callbackParam = $callbackParam;
30 6
    }
31
32
    /**
33
     * Handles wrapping a JSON response into a JSONP response.
34
     */
35 6
    public function createResponse(ViewHandler $handler, View $view, Request $request, string $format): Response
36
    {
37 6
        $response = $handler->createResponse($view, $request, 'json');
38
39 6
        if ($response->isSuccessful()) {
40 6
            $callback = $this->getCallback($request);
41 4
            $response->setContent(sprintf('/**/%s(%s)', $callback, $response->getContent()));
42 4
            $response->headers->set('Content-Type', $request->getMimeType($format));
43
        }
44
45 4
        return $response;
46
    }
47
48 6
    private function getCallback(Request $request): string
49
    {
50 6
        $callback = $request->query->get($this->callbackParam);
51 6
        $validator = new \JsonpCallbackValidator();
52
53 6
        if (!$validator->validate($callback)) {
54 2
            throw new BadRequestHttpException('Invalid JSONP callback value');
55
        }
56
57 4
        return $callback;
58
    }
59
}
60