Completed
Push — master ( 5832ba...311c48 )
by nonanerz
11s
created

FormRequestController   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 81
Duplicated Lines 9.88 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 5
dl 8
loc 81
ccs 0
cts 38
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A listAction() 0 14 2
B addAction() 8 48 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
68
        if (is_null($formRequest->getDate())) {
69
            throw new JsonHttpException(404, 'Date is required');
70
        }
71
72
        $errors = $this->get('validator')->validate($formRequest);
73 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...
74
            $outErrors = [];
75
            /** @var ConstraintViolation $error */
76
            foreach ($errors as $error) {
77
                $outErrors[$error->getPropertyPath()] = $error->getMessage();
78
            }
79
            throw new JsonHttpException(400, 'Bad Request', $outErrors);
80
        }
81
        $em->persist($formRequest);
82
        $em->flush();
83
84
        $this->get('app.email_notification')->sendNotification(
85
            $formRequest->getUser()->getEmail(),
86
            'Form request',
87
            'Hello, '.$formRequest->getUser()->getFirstName().'. Your form request was created.'
88
        );
89
90
        return $this->json([
91
            'success' => [
92
                'code' => 200,
93
                'message' => 'Request form created.',
94
            ],
95
        ], 200);
96
    }
97
}
98