ApiErrorController::validationErrorsAction()   B
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 28
ccs 18
cts 18
cp 1
rs 8.8571
cc 3
eloc 18
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Seblegall\ApiValidatorBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
6
use Symfony\Component\HttpFoundation\JsonResponse;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\Serializer\Serializer;
10
use Symfony\Component\Serializer\Encoder\XmlEncoder;
11
use Symfony\Component\Serializer\Encoder\JsonEncoder;
12
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
13
14
class ApiErrorController extends Controller
15
{
16
    /**
17
     * Called when parameter bag isn't valid.
18
     * This controller returns an array of errors.
19
     *
20
     * @param Request $request
21
     *
22
     * @return JsonResponse|Response
23
     */
24 4
    public function validationErrorsAction(Request $request)
25
    {
26 4
        $format = $request->get('_format', 'json');
27 4
        $apiErrors = $request->attributes->get('_api_errors', array());
28
29
        switch ($format) {
30 4
            case 'xml':
31 1
                $encoders = array(new XmlEncoder('result'), new JsonEncoder());
32 1
                $normalizers = array(new GetSetMethodNormalizer());
33
34 1
                $serializer = new Serializer($normalizers, $encoders);
35 1
                $xml = $serializer->serialize(array('errors' => $apiErrors), 'xml');
36
37 1
                $response = new Response($xml, 400, array('Content-Type' => 'application/xml'));
38 1
                break;
39
40 3
            case 'json':
41 3
            default:
42 3
                $response = new JsonResponse(
43
                    array(
44 3
                        'errors' => $apiErrors,
45 3
                    ),
46
                    400
47 3
                );
48 3
        }
49
50 4
        return $response;
51
    }
52
}
53