HistoryController::cgetAction()   B
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 79

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 43
CRAP Score 4.1075

Importance

Changes 0
Metric Value
cc 4
nc 8
nop 1
dl 0
loc 79
ccs 43
cts 53
cp 0.8113
crap 4.1075
rs 8.4581
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Entity\History;
6
use App\Model\HistoryResponse;
7
use App\Model\Link;
8
use App\Model\PaginationLinks;
9
use FOS\RestBundle\Request\ParamFetcher;
10
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
11
use FOS\RestBundle\Controller\Annotations\QueryParam;
12
use Nelmio\ApiDocBundle\Annotation\Model;
13
use Swagger\Annotations as SWG;
14
use Symfony\Component\Routing\Annotation\Route;
15
16
/**
17
 * @Route("/api/histories")
18
 */
19
class HistoryController extends AbstractController
20
{
21
    /**
22
     * @Route("", name="get_histories", methods={"GET"})
23
     * @SWG\Response(
24
     *     response=200,
25
     *     description="Returns a collection of History",
26
     *     @SWG\Schema(
27
     *         type="array",
28
     *         @SWG\Items(ref=@Model(type=HistoryResponse::class))
29
     *     )
30
     * )
31
     * @SWG\Response(
32
     *     response=404,
33
     *     description="Returns when the entities with given limit and offset are not found",
34
     * )
35
     *
36
     * @QueryParam(name="limit", requirements="\d+", default="10", description="Count entries at one page")
37
     * @QueryParam(name="page", requirements="\d+", default="1", description="Number of page to be shown")
38
     * @QueryParam(name="locale", requirements="^[a-zA-Z]+", default="uk", description="Selects language of data you want to receive")
39
     */
40 1
    public function cgetAction(ParamFetcher $paramFetcher)
41
    {
42 1
        $em = $this->getDoctrine()->getManager();
43
44 1
        $histories = $em->getRepository('App:History')
45 1
            ->findAllHistory(
46 1
                $paramFetcher->get('limit'),
47 1
                ($paramFetcher->get('page')-1) * $paramFetcher->get('limit')
48
            )
49
        ;
50
51 1
        $historyTranslated = [];
52
53
        /** @var History $history */
54 1
        foreach ($histories as $history) {
55 1
            $history->setLocale($paramFetcher->get('locale'));
56 1
            $em->refresh($history);
57
58 1
            $history->unsetTranslations();
59
60 1
            $historyTranslated[] = $history;
61
        }
62
63 1
        $histories = $historyTranslated;
64
65 1
        $historyResponse = new HistoryResponse();
66 1
        $historyResponse->setHistory($histories);
67 1
        $historyResponse->setTotalCount($this->getDoctrine()->getManager()->getRepository('App:History')->getCount());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getCount() does only exist in the following implementations of said interface: App\Repository\AbstractRepository, App\Repository\EmployeeRepository, App\Repository\HistoryRepository, App\Repository\PerformanceEventRepository, App\Repository\PerformanceRepository, App\Repository\PostRepository.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
68 1
        $historyResponse->setPageCount(ceil($historyResponse->getTotalCount() / $paramFetcher->get('limit')));
69 1
        $historyResponse->setPage($paramFetcher->get('page'));
70
71 1
        $self = $this->generateUrl('get_histories', [
72 1
            'locale' => $paramFetcher->get('locale'),
73 1
            'limit' => $paramFetcher->get('limit'),
74 1
            'page' => $paramFetcher->get('page'),
75 1
        ], true
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer.

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...
76
        );
77
78 1
        $first = $this->generateUrl('get_histories', [
79 1
            'locale' => $paramFetcher->get('locale'),
80 1
            'limit' => $paramFetcher->get('limit'),
81 1
        ], true
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer.

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...
82
        );
83
84 1
        $nextPage = $paramFetcher->get('page') < $historyResponse->getPageCount() ?
85
            $this->generateUrl('get_histories', [
86
                'locale' => $paramFetcher->get('locale'),
87
                'limit' => $paramFetcher->get('limit'),
88
                'page' => $paramFetcher->get('page')+1,
89
            ], true
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer.

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...
90
            ) :
91 1
            'false';
92
93 1
        $previsiousPage = $paramFetcher->get('page') > 1 ?
94
            $this->generateUrl('get_histories', [
95
                'locale' => $paramFetcher->get('locale'),
96
                'limit' => $paramFetcher->get('limit'),
97
                'page' => $paramFetcher->get('page')-1,
98
            ], true
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer.

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...
99
            ) :
100 1
            'false';
101
102 1
        $last = $this->generateUrl('get_histories', [
103 1
            'locale' => $paramFetcher->get('locale'),
104 1
            'limit' => $paramFetcher->get('limit'),
105 1
            'page' => $historyResponse->getPageCount(),
106 1
        ], true
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer.

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...
107
        );
108
109 1
        $links = new PaginationLinks();
110
111 1
        $historyResponse->setLinks($links->setSelf(new Link($self)));
112 1
        $historyResponse->setLinks($links->setFirst(new Link($first)));
113 1
        $historyResponse->setLinks($links->setNext(new Link($nextPage)));
114 1
        $historyResponse->setLinks($links->setPrev(new Link($previsiousPage)));
115 1
        $historyResponse->setLinks($links->setLast(new Link($last)));
116
117 1
        return $historyResponse;
118
    }
119
120
    /**
121
     * @Route("/{slug}", name="get_history", methods={"GET"})
122
     * @SWG\Response(
123
     *     response=200,
124
     *     description="Returns an History by unique property {slug}",
125
     *     @Model(type=History::class)
126
     * )
127
     * @SWG\Response(
128
     *     response=404,
129
     *     description="Returns when History by {slug} was not found",
130
     * )
131
     *
132
     * @QueryParam(name="locale", requirements="^[a-zA-Z]+", default="uk", description="Selects language of data you want to receive")
133
     */
134 1 View Code Duplication
    public function getAction(ParamFetcher $paramFetcher, $slug)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
135
    {
136 1
        $em = $this->getDoctrine()->getManager();
137
138
        $history = $em
139 1
            ->getRepository('App:History')->findOneByslug($slug);
140
141 1
        if (!$history) {
142 1
            throw $this->createNotFoundException('Unable to find '.$slug.' entity');
143
        }
144
145 1
        $history->setLocale($paramFetcher->get('locale'));
146 1
        $em->refresh($history);
147
148 1
        if ($history->getTranslations()) {
149 1
            $history->unsetTranslations();
150
        }
151
152 1
        return $history;
153
    }
154
}
155