FormRequestController::addAction()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 48
Code Lines 32

Duplication

Lines 8
Ratio 16.67 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 8
loc 48
ccs 0
cts 29
cp 0
rs 8.551
c 1
b 0
f 0
cc 5
eloc 32
nc 5
nop 2
crap 30
1
<?php
2
3
namespace AppBundle\Controller\Api;
4
5
use AppBundle\Entity\FormRequest;
6
use Doctrine\Common\Collections\Criteria;
7
use Mcfedr\JsonFormBundle\Controller\JsonController;
8
use AppBundle\Exception\JsonHttpException;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\Routing\Annotation\Route;
13
use Symfony\Component\Validator\ConstraintViolation;
14
15
/**
16
 * @Route("/form-request", name="form_requests")
17
 */
18
class FormRequestController extends JsonController
19
{
20
    /**
21
     * @Route("/{status}", requirements={"status": "pending|past"})
22
     * @Method("GET")
23
     *
24
     * @return JsonResponse
25
     */
26
    public function listAction(Request $request, $status)
27
    {
28
        $requestForms = $this->get('knp_paginator')
29
            ->paginate(
30
                $this->getDoctrine()->getManager()->getRepository(FormRequest::class)->findBy([
31
                    'user' => $this->getUser(),
32
                    'status' => $status == 'pending' ? 'pending' : ['approved', 'rejected'],
33
                ], ['createdAt' => Criteria::DESC]),
34
                $request->query->getInt('page', 1),
35
                10
36
            );
37
38
        return $this->json(['requestForms' => $requestForms]);
39
    }
40
41
    /**
42
     * @Route("/{type}", requirements={"type"= "sick-day|personal-day|overnight-guest"})
43
     * @Method("POST")
44
     *
45
     * @param $type
46
     * @param Request $request
47
     *
48
     * @return JsonResponse
49
     */
50
    public function addAction($type, Request $request)
51
    {
52
        if (!$request->getContent()) {
53
            throw new JsonHttpException(404, 'Request body is empty');
54
        }
55
        $em = $this->getDoctrine()->getManager();
56
57
        $formRequest = new FormRequest();
58
        $formRequest
59
            ->setType(str_replace('-', ' ', $type))
60
            ->setUser($this->getUser());
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<AppBundle\Entity\User>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
61
62
        $formRequest = $this->get('serializer')->deserialize(
63
            $request->getContent(),
64
            FormRequest::class,
65
            'json',
66
            ['object_to_populate' => $formRequest]
67
        );
68
69
        if (is_null($formRequest->getDate())) {
70
            throw new JsonHttpException(404, 'Date is required');
71
        }
72
73
        $errors = $this->get('validator')->validate($formRequest);
74 View Code Duplication
        if ($errors->count()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
75
            $outErrors = [];
76
            /** @var ConstraintViolation $error */
77
            foreach ($errors as $error) {
78
                $outErrors[$error->getPropertyPath()] = $error->getMessage();
79
            }
80
            throw new JsonHttpException(400, 'Bad Request', $outErrors);
81
        }
82
        $em->persist($formRequest);
83
        $em->flush();
84
85
        $this->get('app.email_notification')->sendNotification(
86
            $formRequest->getUser()->getEmail(),
87
            'Form request',
88
            'Hello, '.$formRequest->getUser()->getFirstName().'. Your form request was created.'
89
        );
90
91
        return $this->json([
92
            'success' => [
93
                'code' => 200,
94
                'message' => 'Request form created.',
95
            ],
96
        ], 200);
97
    }
98
}
99