Completed
Pull Request — master (#30)
by
unknown
04:24
created

FormRequestController::addAction()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 43
Code Lines 30

Duplication

Lines 8
Ratio 18.6 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 8
loc 43
rs 8.5806
cc 4
eloc 30
nc 4
nop 2
1
<?php
2
3
namespace AppBundle\Controller\Api;
4
5
use AppBundle\Entity\FormRequest;
6
use Mcfedr\JsonFormBundle\Controller\JsonController;
7
use AppBundle\Exception\JsonHttpException;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\Routing\Annotation\Route;
12
use Symfony\Component\Validator\ConstraintViolation;
13
14
/**
15
 * @Route("/form-request", name="form_requests")
16
 */
17
class FormRequestController extends JsonController
18
{
19
    /**
20
     * @Route("/{status}", requirements={"status": "pending|past"})
21
     * @Method("GET")
22
     *
23
     * @return JsonResponse
24
     */
25
    public function listAction(Request $request, $status)
26
    {
27
        $requestForms = $this->get('knp_paginator')
28
            ->paginate(
29
                $this->getDoctrine()->getManager()->getRepository(FormRequest::class)->findBy([
30
                    'user' => $this->getUser(),
31
                    'status' => $status == 'pending' ? 'pending' : ['approved', 'rejected'],
32
                ]),
33
                $request->query->getInt('page', 1),
34
                10
35
            );
36
37
        return $this->json(['requestForms' => $requestForms]);
38
    }
39
40
    /**
41
     * @Route("/{type}", requirements={"type"= "sick-day|personal-day|overnight-guest"})
42
     * @Method("POST")
43
     *
44
     * @param $type
45
     * @param Request $request
46
     *
47
     * @return JsonResponse
48
     */
49
    public function addAction($type, Request $request)
50
    {
51
        if (!$request->getContent()) {
52
            throw new JsonHttpException(404, 'Request body is empty');
53
        }
54
        $em = $this->getDoctrine()->getManager();
55
56
        $formRequest = new FormRequest();
57
        $formRequest
58
            ->setType(str_replace('-', ' ', $type))
59
            ->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...
60
61
        $formRequest = $this->get('serializer')->deserialize(
62
            $request->getContent(),
63
            FormRequest::class,
64
            'json',
65
            ['object_to_populate' => $formRequest]
66
        );
67
        $errors = $this->get('validator')->validate($formRequest);
68 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...
69
            $outErrors = [];
70
            /** @var ConstraintViolation $error */
71
            foreach ($errors as $error) {
72
                $outErrors[$error->getPropertyPath()] = $error->getMessage();
73
            }
74
            throw new JsonHttpException(400, 'Bad Request', $outErrors);
75
        }
76
        $em->persist($formRequest);
77
        $em->flush();
78
79
        $this->get('app.email_notification')->sendNotification(
80
            $formRequest->getUser()->getEmail(),
81
            'Form request',
82
            'Hello, '.$formRequest->getUser()->getFirstName().'. Your form request was created.'
83
        );
84
85
        return $this->json([
86
            'success' => [
87
                'code' => 200,
88
                'message' => 'Request form created.',
89
            ],
90
        ], 200);
91
    }
92
}
93