BlogController   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 320
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 13
dl 0
loc 320
rs 10
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
B indexAction() 0 29 3
A feedAction() 0 6 1
A newAction() 0 4 1
A newPostAction() 0 4 1
A settingsAction() 0 15 1
B settingsPostAction() 0 27 2
B categoryAction() 0 42 3
A articlesAction() 0 9 1
A deleteAction() 0 18 3
A getPageSettingsType() 0 4 1
A getPageCategoryType() 0 4 1
A getNewPageType() 0 4 1
A getNewPage() 0 4 1
A getBaseTemplatePath() 0 4 1
A getBlog() 0 14 2
1
<?php
2
3
namespace Victoire\Bundle\BlogBundle\Controller;
4
5
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
13
use Victoire\Bundle\BlogBundle\Entity\Blog;
14
use Victoire\Bundle\BlogBundle\Form\BlogCategoryType;
15
use Victoire\Bundle\BlogBundle\Form\BlogSettingsType;
16
use Victoire\Bundle\BlogBundle\Form\BlogType;
17
use Victoire\Bundle\BlogBundle\Form\ChooseBlogType;
18
use Victoire\Bundle\BlogBundle\Repository\BlogRepository;
19
use Victoire\Bundle\PageBundle\Controller\BasePageController;
20
use Victoire\Bundle\PageBundle\Entity\BasePage;
21
22
/**
23
 * Blog Controller.
24
 *
25
 * @Route("/victoire-dcms/blog")
26
 */
27
class BlogController extends BasePageController
28
{
29
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$blogId" missing
Loading history...
introduced by
Doc comment for parameter "$tab" missing
Loading history...
30
     * List all Blogs.
31
     *
32
     * @Route("/index/{blogId}/{tab}", name="victoire_blog_index", defaults={"blogId" = null, "tab" = "articles"})
33
     *
34
     * @param Request $request
35
     *
36
     * @return JsonResponse
37
     */
38
    public function indexAction(Request $request, $blogId = null, $tab = 'articles')
39
    {
40
        $blog = $this->getBlog($request, $blogId);
41
        $template = $this->getBaseTemplatePath().':index.html.twig';
42
        $chooseBlogForm = $this->createForm(ChooseBlogType::class, null, [
43
            'blog'   => $blog,
44
            'locale' => $request->getLocale(),
45
        ]);
46
47
        $chooseBlogForm->handleRequest($request);
48
        if ($chooseBlogForm->isValid()) {
49
            $template = $this->getBaseTemplatePath().':_blogItem.html.twig';
50
        }
51
52
        return new JsonResponse(
53
            [
54
                'html' => $this->container->get('templating')->render(
55
                    $template,
56
                    [
57
                        'blog'               => $blog,
58
                        'currentTab'         => $tab,
59
                        'tabs'               => ['articles', 'settings', 'category'],
60
                        'chooseBlogForm'     => $chooseBlogForm->createView(),
61
                        'businessProperties' => $blog ? $this->getBusinessProperties($blog) : null,
62
                    ]
63
                ),
64
            ]
65
        );
66
    }
67
68
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$blog" missing
Loading history...
69
     * Display Blogs RSS feed.
70
     *
71
     * @Route("/feed/{id}.rss", name="victoire_blog_rss", defaults={"_format" = "rss"})
72
     *
73
     * @param Request $request
74
     * @Template("VictoireBlogBundle:Blog:feed.rss.twig")
75
     *
76
     * @return array
77
     */
78
    public function feedAction(Request $request, Blog $blog)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
79
    {
80
        return [
81
            'blog' => $blog,
82
        ];
83
    }
84
85
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$isHomepage" missing
Loading history...
86
     * Display a form to create a new Blog.
87
     *
88
     * @Route("/new", name="victoire_blog_new")
89
     * @Method("GET")
90
     * @Template()
91
     *
92
     * @return JsonResponse
93
     */
94
    public function newAction(Request $request, $isHomepage = false)
95
    {
96
        return new JsonResponse(parent::newAction($request));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...::newAction($request)); (Symfony\Component\HttpFoundation\JsonResponse) is incompatible with the return type of the parent method Victoire\Bundle\PageBund...geController::newAction of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
97
    }
98
99
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
100
     * Create a new Blog.
101
     *
102
     * @Route("/new", name="victoire_blog_new_post")
103
     * @Method("POST")
104
     * @Template()
105
     *
106
     * @return JsonResponse
107
     */
108
    public function newPostAction(Request $request)
109
    {
110
        return new JsonResponse(parent::newPostAction($request));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...wPostAction($request)); (Symfony\Component\HttpFoundation\JsonResponse) is incompatible with the return type of the parent method Victoire\Bundle\PageBund...ntroller::newPostAction of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
111
    }
112
113
    /**
114
     * Display a form to edit Blog settings.
115
     *
116
     * @param Request  $request
117
     * @param BasePage $blog
118
     *
119
     * @Route("/{id}/settings", name="victoire_blog_settings")
120
     * @Method("GET")
121
     * @ParamConverter("blog", class="VictoirePageBundle:BasePage")
122
     *
123
     * @return JsonResponse
124
     */
125
    public function settingsAction(Request $request, BasePage $blog)
126
    {
127
        $form = $this->createForm($this->getPageSettingsType(), $blog);
128
129
        $form->handleRequest($request);
130
131
        return new Response($this->container->get('templating')->render(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...perties' => array()))); (Symfony\Component\HttpFoundation\Response) is incompatible with the return type of the parent method Victoire\Bundle\PageBund...troller::settingsAction of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
132
            $this->getBaseTemplatePath().':Tabs/_settings.html.twig',
133
            [
134
                'blog'               => $blog,
135
                'form'               => $form->createView(),
136
                'businessProperties' => [],
137
            ]
138
        ));
139
    }
140
141
    /**
142
     * Save Blog settings.
143
     *
144
     * @Route("/{id}/settings", name="victoire_blog_settings_post")
145
     * @Method("POST")
146
     * @ParamConverter("blog", class="VictoirePageBundle:BasePage")
147
     *
148
     * @return JsonResponse
149
     */
150
    protected function settingsPostAction(Request $request, BasePage $blog)
151
    {
152
        $entityManager = $this->getDoctrine()->getManager();
153
        $form = $this->createForm($this->getPageSettingsType(), $blog);
154
155
        $form->handleRequest($request);
156
157
        if ($form->isValid()) {
158
            $entityManager->persist($blog);
159
            $entityManager->flush();
160
161
            return new JsonResponse($this->getViewReferenceRedirect($request, $blog));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...rect($request, $blog)); (Symfony\Component\HttpFoundation\JsonResponse) is incompatible with the return type of the parent method Victoire\Bundle\PageBund...ler::settingsPostAction of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
162
        }
163
164
        return new JsonResponse([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...erties' => array())))); (Symfony\Component\HttpFoundation\JsonResponse) is incompatible with the return type of the parent method Victoire\Bundle\PageBund...ler::settingsPostAction of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
165
            'success' => false,
166
            'message' => $this->get('victoire_form.error_helper')->getRecursiveReadableErrors($form),
167
            'html'    => $this->container->get('templating')->render(
168
                $this->getBaseTemplatePath().':Tabs/_settings.html.twig',
169
                [
170
                    'blog'               => $blog,
171
                    'form'               => $form->createView(),
172
                    'businessProperties' => [],
173
                ]
174
            ),
175
        ]);
176
    }
177
178
    /**
179
     * List Blog Categories.
180
     *
181
     * @param Request  $request
182
     * @param BasePage $blog
183
     *
184
     * @Route("/{id}/category", name="victoire_blog_category")
185
     * @ParamConverter("blog", class="VictoirePageBundle:BasePage")
186
     *
187
     * @return Response
188
     */
189
    public function categoryAction(Request $request, BasePage $blog)
0 ignored issues
show
introduced by
Declare public methods first,then protected ones and finally private ones
Loading history...
190
    {
191
        $entityManager = $this->getDoctrine()->getManager();
192
        $form = $this->createForm($this->getPageCategoryType(), $blog);
193
        $businessProperties = $this->getBusinessProperties($blog);
194
195
        $form->handleRequest($request);
196
197
        if ($form->isValid()) {
198
            $entityManager->persist($blog);
199
            $entityManager->flush();
200
201
            return new JsonResponse([
202
                'success' => true,
203
                'url'     => $this->generateUrl('victoire_core_page_show', ['_locale' => $blog->getCurrentLocale(), 'url' => $blog->getUrl()]), ]);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 16.
Loading history...
204
        }
205
        //we display the form
206
        $errors = $this->get('victoire_form.error_helper')->getRecursiveReadableErrors($form);
207
        if ($errors != '') {
208
            return new JsonResponse(['html' => $this->container->get('templating')->render(
209
                        $this->getBaseTemplatePath().':Tabs/_category.html.twig',
210
                            [
211
                                'blog'               => $blog,
212
                                'form'               => $form->createView(),
213
                                'businessProperties' => $businessProperties,
214
                            ]
215
                        ),
216
                        'message' => $errors,
217
                    ]
218
                );
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 16.
Loading history...
219
        }
220
221
        return new Response($this->container->get('templating')->render(
222
                    $this->getBaseTemplatePath().':Tabs/_category.html.twig',
223
                    [
224
                        'blog'               => $blog,
225
                        'form'               => $form->createView(),
226
                        'businessProperties' => $businessProperties,
227
                    ]
228
                )
229
        );
230
    }
231
232
    /**
233
     * List Blog articles.
234
     *
235
     * @param Request  $request
236
     * @param BasePage $blog
237
     *
238
     * @Route("/{id}/articles", name="victoire_blog_articles")
239
     * @ParamConverter("blog", class="VictoirePageBundle:BasePage")
240
     *
241
     * @return Response
242
     */
243
    public function articlesAction(Request $request, BasePage $blog)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
244
    {
245
        return new Response($this->container->get('templating')->render(
246
            $this->getBaseTemplatePath().':Tabs/_articles.html.twig',
247
            [
248
                'blog' => $blog,
249
            ]
250
        ));
251
    }
252
253
    /**
254
     * Delete a Blog.
255
     *
256
     * @param BasePage $blog
257
     *
258
     * @Route("/{id}/delete", name="victoire_blog_delete")
259
     * @Template()
260
     * @ParamConverter("blog", class="VictoirePageBundle:BasePage")
261
     *
262
     * @return JsonResponse
263
     */
264
    public function deleteAction(BasePage $blog)
265
    {
266
        if (!$this->get('security.authorization_checker')->isGranted('ROLE_VICTOIRE', $blog)) {
267
            throw new AccessDeniedException("Nop ! you can't do such an action");
268
        }
269
270
        foreach ($blog->getArticles() as $_article) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\PageBundle\Entity\BasePage as the method getArticles() does only exist in the following sub-classes of Victoire\Bundle\PageBundle\Entity\BasePage: Victoire\Bundle\BlogBundle\Entity\Blog. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
271
            $bep = $this->get('victoire_page.page_helper')->findPageByParameters(
272
                [
273
                    'templateId' => $_article->getTemplate()->getId(),
274
                    'entityId'   => $_article->getId(),
275
                ]
276
            );
277
            $this->get('victoire_blog.manager.article')->delete($_article, $bep);
278
        }
279
280
        return new JsonResponse(parent::deleteAction($blog));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...::deleteAction($blog)); (Symfony\Component\HttpFoundation\JsonResponse) is incompatible with the return type of the parent method Victoire\Bundle\PageBund...ontroller::deleteAction of type array<string,boolean|string>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
281
    }
282
283
    /**
284
     * @return string
285
     */
286
    protected function getPageSettingsType()
287
    {
288
        return BlogSettingsType::class;
289
    }
290
291
    /**
292
     * @return string
293
     */
294
    protected function getPageCategoryType()
295
    {
296
        return BlogCategoryType::class;
297
    }
298
299
    /**
300
     * @return string
301
     */
302
    protected function getNewPageType()
303
    {
304
        return BlogType::class;
305
    }
306
307
    /**
308
     * @return \Victoire\Bundle\BlogBundle\Entity\Blog
309
     */
310
    protected function getNewPage()
311
    {
312
        return new Blog();
313
    }
314
315
    /**
316
     * @return string
317
     */
318
    protected function getBaseTemplatePath()
319
    {
320
        return 'VictoireBlogBundle:Blog';
321
    }
322
323
    /**
324
     * Get Blog from id if defined.
325
     * If not return the first Blog.
326
     *
327
     * @param Request $request
328
     * @param $blogId
329
     *
330
     * @return Blog|false
331
     */
332
    protected function getBlog(Request $request, $blogId)
333
    {
334
        /** @var BlogRepository $blogRepo */
335
        $blogRepo = $this->get('doctrine.orm.entity_manager')->getRepository('VictoireBlogBundle:Blog');
336
337
        if ($blogId) {
338
            $blog = $blogRepo->find($blogId);
339
        } else {
340
            $blogs = $blogRepo->joinTranslations($request->getLocale())->run();
341
            $blog = reset($blogs);
342
        }
343
344
        return $blog;
345
    }
346
}
347