Completed
Pull Request — master (#169)
by Serhii
04:50
created

PerformancesController   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 255
Duplicated Lines 13.73 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 95.45%

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 10
dl 35
loc 255
ccs 105
cts 110
cp 0.9545
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B getList() 10 90 6
A getAction() 0 13 2
B getRolesAction() 17 42 6
A getPerformanceEventsAction() 8 32 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 App\Controller\Api;
4
5
use App\Entity\Performance;
6
use App\Model\Link;
7
use App\Model\PaginationLinks;
8
use App\Model\PerformancesResponse;
9
use FOS\RestBundle\Controller\Annotations\QueryParam;
10
use FOS\RestBundle\Request\ParamFetcher;
11
use Nelmio\ApiDocBundle\Annotation\Model;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
13
use Swagger\Annotations as SWG;
14
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
15
use Symfony\Component\Routing\Annotation\Route;
16
17
/**
18
 * @Route("/api/performances")
19
 */
20
class PerformancesController extends AbstractController
21
{
22
    /**
23
     * @Route("", name="get_performances", methods={"GET"})
24
     * @SWG\Response(
25
     *     response=200,
26
     *     description="Returns when all parameters were correct",
27
     *     @SWG\Schema(
28
     *         type="array",
29
     *         @SWG\Items(ref=@Model(type=PerformancesResponse::class))
30
     *     )
31
     * )
32
     * @SWG\Response(
33
     *     response=404,
34
     *     description="Returns when the entity is not found",
35
     * )
36
     *
37
     * @QueryParam(name="limit", requirements="\d+", default="10", description="Count entries at one page")
38
     * @QueryParam(name="page", requirements="\d+", default="1", description="Number of page to be shown")
39
     * @QueryParam(name="locale", requirements="^[a-zA-Z]+", default="uk", description="Selects language of data you want to receive")
40
     */
41 2
    public function getList(ParamFetcher $paramFetcher)
42
    {
43 2
        $em = $this->getDoctrine()->getManager();
44
45
        $performances = $em
46 2
            ->getRepository('App:Performance')
47 2
            ->findBy(
48 2
                ['festival' => null],
49 2
                ['premiere' => 'DESC'],
50 2
                $paramFetcher->get('limit'),
51 2
                ($paramFetcher->get('page')-1) * $paramFetcher->get('limit')
52
            );
53
54 2
        $performancesTranslated = array();
55
56 2 View Code Duplication
        foreach ($performances as $performance) {
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...
57 2
            $performance->setLocale($paramFetcher->get('locale'));
58 2
            $em->refresh($performance);
59
60 2
            if ($performance->getTranslations()) {
61 2
                $performance->unsetTranslations();
62
            }
63
64 2
            $performancesTranslated[] = $performance;
65
        }
66
67 2
        $performances = $performancesTranslated;
68
69 2
        $performancesResponse = new PerformancesResponse();
70 2
        $performancesResponse->setPerformances($performances);
71 2
        $performancesResponse->setTotalCount($this->getDoctrine()->getManager()->getRepository('App:Performance')->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...
72 2
        $performancesResponse->setPageCount(ceil($performancesResponse->getTotalCount() / $paramFetcher->get('limit')));
73 2
        $performancesResponse->setPage($paramFetcher->get('page'));
74
75 2
        $self = $this->generateUrl('get_performances', [
76 2
            'locale' => $paramFetcher->get('locale'),
77 2
            'limit' => $paramFetcher->get('limit'),
78 2
            'page' => $paramFetcher->get('page'),
79 2
        ], 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...
80
        );
81
82 2
        $first = $this->generateUrl('get_performances', [
83 2
            'locale' => $paramFetcher->get('locale'),
84 2
            'limit' => $paramFetcher->get('limit'),
85 2
        ], 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...
86
        );
87
88 2
        $nextPage = $paramFetcher->get('page') < $performancesResponse->getPageCount() ?
89 1
            $this->generateUrl('get_performances', [
90 1
                'locale' => $paramFetcher->get('locale'),
91 1
                'limit' => $paramFetcher->get('limit'),
92 1
                'page' => $paramFetcher->get('page')+1,
93 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...
94
            ) :
95 2
            'false';
96
97 2
        $previsiousPage = $paramFetcher->get('page') > 1 ?
98
            $this->generateUrl('get_performances', [
99
                'locale' => $paramFetcher->get('locale'),
100
                'limit' => $paramFetcher->get('limit'),
101
                'page' => $paramFetcher->get('page')-1,
102
            ], 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...
103
            ) :
104 2
            'false';
105
106 2
        $last = $this->generateUrl('get_performances', [
107 2
            'locale' => $paramFetcher->get('locale'),
108 2
            'limit' => $paramFetcher->get('limit'),
109 2
            'page' => $performancesResponse->getPageCount(),
110 2
        ], 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...
111
        );
112
113 2
        $links = new PaginationLinks();
114
115 2
        $performancesResponse->setLinks($links->setSelf(new Link($self)));
116 2
        $performancesResponse->setLinks($links->setFirst(new Link($first)));
117 2
        $performancesResponse->setLinks($links->setNext(new Link($nextPage)));
118 2
        $performancesResponse->setLinks($links->setPrev(new Link($previsiousPage)));
119 2
        $performancesResponse->setLinks($links->setLast(new Link($last)));
120
121 2
        foreach ($performances as $performance) {
122 2
            $performance->setLinks([
123 2
                ['rel' => 'self', 'href' => $this->generateUrl('get_performance', ['slug' => $performance->getSlug()], 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...
124 2
                ['rel' => 'self.roles', 'href' => $this->generateUrl('get_performance_roles', ['slug' => $performance->getSlug()], 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...
125 2
                ['rel' => 'self.events', 'href' => $this->generateUrl('get_performanceevents', ['performance' => $performance->getSlug()], 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...
126
            ]);
127
        }
128
129 2
        return $performancesResponse;
130
    }
131
132
    /**
133
     * @Route("/{slug}", name="get_performance", methods={"GET"})
134
     * @Cache(
135
     *     lastModified="performance.getUpdatedAt()",
136
     *     Etag="'Post' ~ performance.getId() ~ performance.getUpdatedAt().getTimestamp()"
137
     * )
138
     * @SWG\Response(
139
     *     response=200,
140
     *     description="Returns Performance by unique property {slug}",
141
     *     @Model(type=Performance::class)
142
     * )
143
     * @SWG\Response(
144
     *     response=404,
145
     *     description="Returns when Performance was not found in database",
146
     * )
147
     *
148
     * @QueryParam(name="locale", requirements="^[a-zA-Z]+", default="uk", description="Selects language of data you want to receive")
149
     */
150 1
    public function getAction(ParamFetcher $paramFetcher, Performance $performance)
151
    {
152 1
        $em = $this->getDoctrine()->getManager();
153
154 1
        $performance->setLocale($paramFetcher->get('locale'));
155 1
        $em->refresh($performance);
156
157 1
        if ($performance->getTranslations()) {
158 1
            $performance->unsetTranslations();
159
        }
160
161 1
        return $performance;
162
    }
163
164
    /**
165
     * @Route("/{slug}/roles", name="get_performance_roles", methods={"GET"})
166
     * @SWG\Response(
167
     *     response=200,
168
     *     description="Returns Performance roles by his unique {slug}",
169
     *     @SWG\Schema(
170
     *         type="array",
171
     *         @SWG\Items(ref=@Model(type=Role::class))
172
     *     )
173
     * )
174
     * @SWG\Response(
175
     *     response=404,
176
     *     description="Returns when Performance by slug was not found in database",
177
     * )
178
     *
179
     * @QueryParam(name="locale", requirements="^[a-zA-Z]+", default="uk", description="Selects language of data you want to receive")
180
     */
181 1
    public function getRolesAction(ParamFetcher $paramFetcher, $slug)
182
    {
183 1
        $em = $this->getDoctrine()->getManager();
184
185
        $performance = $em
186 1
            ->getRepository('App:Performance')->findOneByslug($slug);
187
188 1
        if (!$performance) {
189 1
            throw $this->createNotFoundException('Unable to find '.$slug.' entity');
190
        }
191
192 1
        $performance->setLocale($paramFetcher->get('locale'));
193 1
        $em->refresh($performance);
194
195 1
        if ($performance->getTranslations()) {
196 1
            $performance->unsetTranslations();
197
        }
198
199 1
        $roles = $performance->getRoles();
200 1
        $rolesTrans = [];
201
202 1 View Code Duplication
        foreach ($roles as $role) {
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...
203 1
            $role->setLocale($paramFetcher->get('locale'));
204 1
            $em->refresh($role);
205
206 1
            if ($role->getTranslations()) {
207 1
                $role->unsetTranslations();
208
            }
209
210 1
            $role->getEmployee()->setLocale($paramFetcher->get('locale'));
211 1
            $em->refresh($role->getEmployee());
212
213 1
            if ($role->getEmployee()->getTranslations()) {
214 1
                $role->getEmployee()->unsetTranslations();
215
            }
216
217 1
            $rolesTrans[] = $role;
218
        }
219 1
        $roles = $rolesTrans;
220
221 1
        return $roles;
222
    }
223
224
    /**
225
     * @Route("/{slug}/performanceevents", name="get_performance_performance_events", methods={"GET"})
226
     * @SWG\Response(
227
     *     response=200,
228
     *     description="Returns Performance events by Performance {slug}",
229
     *     @SWG\Schema(
230
     *         type="array",
231
     *         @SWG\Items(ref=@Model(type=PerformanceEvent::class))
232
     *     )
233
     * )
234
     * @SWG\Response(
235
     *     response=404,
236
     *     description="Returns when Performance by {slug} was not found in database",
237
     * )
238
     * @SWG\Get(deprecated=true)
239
     *
240
     * @QueryParam(name="locale", requirements="^[a-zA-Z]+", default="uk", description="Selects language of data you want to receive")
241
     */
242 1
    public function getPerformanceEventsAction(ParamFetcher $paramFetcher, $slug)
243
    {
244 1
        $em = $this->getDoctrine()->getManager();
245
246 1
        $performance = $em->getRepository('App:Performance')->findOneByslug($slug);
247
248 1
        if (!$performance) {
249 1
            throw $this->createNotFoundException('Unable to find '.$slug.' entity');
250
        }
251
252 1
        $performance->setLocale($paramFetcher->get('locale'));
253 1
        $em->refresh($performance);
254
255 1
        if ($performance->getTranslations()) {
256 1
            $performance->unsetTranslations();
257
        }
258
259 1
        $performanceEvents = $performance->getPerformanceEvents();
260 1
        $performanceEventsTrans = [];
261
262 1 View Code Duplication
        foreach ($performanceEvents as $performanceEvent) {
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...
263 1
            $performanceEvent->setLocale($paramFetcher->get('locale'));
264 1
            $em->refresh($performanceEvent);
265 1
            if ($performanceEvent->getTranslations()) {
266 1
                $performanceEvent->unsetTranslations();
267
            }
268 1
            $performanceEventsTrans[] = $performanceEvent;
269
        }
270 1
        $performanceEvents = $performanceEventsTrans;
271
272 1
        return $performanceEvents;
273
    }
274
}
275