PostsController::getAction()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 31

Duplication

Lines 8
Ratio 25.81 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
nc 7
nop 2
dl 8
loc 31
ccs 16
cts 16
cp 1
crap 5
rs 9.1128
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Entity\Post;
6
use App\Model\Link;
7
use App\Model\PaginationLinks;
8
use App\Model\PostsResponse;
9
use FOS\RestBundle\Controller\Annotations\QueryParam;
10
use FOS\RestBundle\Request\ParamFetcher;
11
use Nelmio\ApiDocBundle\Annotation\Model;
12
use Swagger\Annotations as SWG;
13
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
14
use Symfony\Component\Routing\Annotation\Route;
15
16
/**
17
 * @Route("/api/posts")
18
 */
19
class PostsController extends AbstractController
20
{
21
    /**
22
     * @Route("", name="get_posts", methods={"GET"})
23
     * @SWG\Response(
24
     *     response=200,
25
     *     description="Returns a collection of Posts",
26
     *     @SWG\Schema(
27
     *         type="array",
28
     *         @SWG\Items(ref=@Model(type=PostsResponse::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
     * @QueryParam(name="tag", description="You can receive posts by Tag slug, without Tag you will receive all posts")
40
     */
41 3
    public function cgetAction(ParamFetcher $paramFetcher)
42
    {
43 3
        $em = $this->getDoctrine()->getManager();
44
45 3
        $posts = $em->getRepository('App:Post')
46 3
            ->findAllOrByTag(
47 3
                $paramFetcher->get('limit'),
48 3
                ($paramFetcher->get('page')-1) * $paramFetcher->get('limit'),
49 3
                $paramFetcher->get('tag')
50
            )
51
        ;
52
53 3
        $postsTranslated = [];
54
55 3
        foreach ($posts as $post) {
56 3
            $post->setLocale($paramFetcher->get('locale'));
57 3
            $em->refresh($post);
58
59 3
            if ($post->getTranslations()) {
60 3
                $post->unsetTranslations();
61
            }
62
63 3
            $tags = $post->getTags();
64
65 3 View Code Duplication
            foreach ($tags as $tag) {
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...
66 3
                $tag->setLocale($paramFetcher->get('locale'));
67 3
                $em->refresh($tag);
68
69 3
                if ($tag->getTranslations()) {
70 3
                    $tag->unsetTranslations();
71
                }
72
            }
73
74 3
            $postsTranslated[] = $post;
75
        }
76
77 3
        $posts = $postsTranslated;
78
79 3
        $postsResponse = new PostsResponse();
80 3
        $postsResponse->setPosts($posts);
81 3
        $postsResponse->setTotalCount($this->getDoctrine()->getManager()->getRepository('App:Post')->getCount($paramFetcher->get('tag')));
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...
82 3
        $postsResponse->setPageCount(ceil($postsResponse->getTotalCount() / $paramFetcher->get('limit')));
83 3
        $postsResponse->setPage($paramFetcher->get('page'));
84
85 3
        $self = $this->generateUrl('get_posts', [
86 3
            'locale' => $paramFetcher->get('locale'),
87 3
            'limit' => $paramFetcher->get('limit'),
88 3
            'page' => $paramFetcher->get('page'),
89 3
            'tag' => $paramFetcher->get('tag'),
90 3
        ], 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...
91
        );
92
93 3
        $first = $this->generateUrl('get_posts', [
94 3
            'locale' => $paramFetcher->get('locale'),
95 3
            'limit' => $paramFetcher->get('limit'),
96 3
            'tag' => $paramFetcher->get('tag'),
97 3
        ], 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...
98
        );
99
100 3
        $nextPage = $paramFetcher->get('page') < $postsResponse->getPageCount() ?
101 3
            $this->generateUrl('get_posts', [
102 3
                'locale' => $paramFetcher->get('locale'),
103 3
                'limit' => $paramFetcher->get('limit'),
104 3
                'page' => $paramFetcher->get('page')+1,
105 3
                'tag' => $paramFetcher->get('tag'),
106 3
            ], 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 3
            'false';
109
110 3
        $previsiousPage = $paramFetcher->get('page') > 1 ?
111
            $this->generateUrl('get_posts', [
112
                'locale' => $paramFetcher->get('locale'),
113
                'limit' => $paramFetcher->get('limit'),
114
                'page' => $paramFetcher->get('page')-1,
115
                'tag' => $paramFetcher->get('tag'),
116
            ], 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...
117
            ) :
118 3
            'false';
119
120 3
        $last = $this->generateUrl('get_posts', [
121 3
            'locale' => $paramFetcher->get('locale'),
122 3
            'limit' => $paramFetcher->get('limit'),
123 3
            'page' => $postsResponse->getPageCount(),
124 3
            'tag' => $paramFetcher->get('tag'),
125 3
        ], 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 3
        $links = new PaginationLinks();
129
130 3
        $postsResponse->setLinks($links->setSelf(new Link($self)));
131 3
        $postsResponse->setLinks($links->setFirst(new Link($first)));
132 3
        $postsResponse->setLinks($links->setNext(new Link($nextPage)));
133 3
        $postsResponse->setLinks($links->setPrev(new Link($previsiousPage)));
134 3
        $postsResponse->setLinks($links->setLast(new Link($last)));
135
136 3
        return $postsResponse;
137
    }
138
139
    /**
140
     * @Route("/{slug}", name="get_post", methods={"GET"})
141
     * @SWG\Response(
142
     *     response=200,
143
     *     description="Returns an Post by unique property {slug}",
144
     *     @Model(type=Post::class)
145
     * )
146
     * @SWG\Response(
147
     *     response=404,
148
     *     description="Returns when Post by {slug} was not found",
149
     * )
150
     *
151
     * @QueryParam(name="locale", requirements="^[a-zA-Z]+", default="uk", description="Selects language of data you want to receive")
152
     */
153 1
    public function getAction(ParamFetcher $paramFetcher, $slug)
154
    {
155 1
        $em = $this->getDoctrine()->getManager();
156
157
        /** @var Post $post */
158 1
        $post = $em->getRepository('App:Post')->findOneByslug($slug);
159
160 1
        if (!$post) {
161 1
            throw $this->createNotFoundException('Unable to find '.$slug.' entity');
162
        }
163
164 1
        $post->setLocale($paramFetcher->get('locale'));
165 1
        $em->refresh($post);
166
167 1
        if ($post->getTranslations()) {
168 1
            $post->unsetTranslations();
169
        }
170
171 1
        $tags = $post->getTags();
172
173 1 View Code Duplication
        foreach ($tags as $tag) {
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...
174 1
            $tag->setLocale($paramFetcher->get('locale'));
175 1
            $em->refresh($tag);
176
177 1
            if ($tag->getTranslations()) {
178 1
                $tag->unsetTranslations();
179
            }
180
        }
181
182 1
        return $post;
183
    }
184
}
185