NodeController::dispatchAction()   C
last analyzed

Complexity

Conditions 12
Paths 25

Size

Total Lines 88

Duplication

Lines 11
Ratio 12.5 %

Importance

Changes 0
Metric Value
dl 11
loc 88
rs 5.8351
c 0
b 0
f 0
cc 12
nc 25
nop 2

How to fix   Long Method    Complexity   

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 Alpixel\Bundle\CMSBundle\Controller;
4
5
use Alpixel\Bundle\CMSBundle\Entity\Node;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
7
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
8
use Symfony\Component\Debug\Exception\ContextErrorException;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\Routing\Route;
12
use Symfony\Component\Routing\Router;
13
14
class NodeController extends Controller
15
{
16
    /**
17
     * @Method({"GET", "POST"})
18
     *
19
     * @param Request $request
20
     * @param         $slug
21
     *
22
     * @return \Symfony\Component\HttpFoundation\Response
23
     */
24
    public function dispatchAction(Request $request, $slug)
25
    {
26
        $entityManager = $this->get('doctrine.orm.entity_manager');
27
        $node = $entityManager->getRepository('AlpixelCMSBundle:Node')
28
            ->findOneBySlugAndLocale($slug, $request->getLocale());
29
30
        if ($node !== null) {
31
            if ($node->getPublished() === false && !$this->isAuthenticated($request)) {
32
                throw $this->createNotFoundException();
33
            }
34
35
            $contentType = $this->get('alpixel_cms.helper.cms')->getContentTypeFromNodeElementClass($node);
36
            $controller = explode('::', $contentType['controller']);
37
38
            try {
39
                if (count($controller) !== 2) {
40
                    throw new \LogicException(
41
                        'The parameter controller must be a valid callable controller, like "My\Namespace\Controller\Class::method"'
42
                    );
43
                } elseif (!class_exists($controller[0]) || !method_exists($controller[0], $controller[1])) {
44
                    throw new \LogicException(
45
                        sprintf(
46
                            'Unable to find the "%s" controller or the method "%s" doesn\'t exist.',
47
                            $controller[0],
48
                            $controller[1]
49
                        )
50
                    );
51
                }
52
53
                /** Generating the alternate link for SEO */
54
                $seoHelper = $this->get('sonata.seo.page.default');
55
                $translatedPages = $entityManager->getRepository('AlpixelCMSBundle:Node')->findTranslations($node);
56
57
                $router = $this->get('router');
58
                foreach ($translatedPages as $translation) {
59
                    $seoHelper->addLangAlternate(
60
                        $router->generate(
61
                            "alpixel_cms",
62
                            [
63
                                'slug'    => $translation->getSlug(),
64
                                '_locale' => $translation->getLocale(),
65
                            ],
66
                            Router::ABSOLUTE_URL
67
                        ),
68
                        $translation->getLocale()
69
                    );
70
                }
71
72
                return $this->forward(
73
                    $contentType['controller'],
74
                    [
75
                        '_route'        => $request->attributes->get('_route'),
76
                        '_route_params' => $request->attributes->get('_route_params'),
77
                        'object'        => $node,
78
                    ]
79
                );
80
            } catch (\LogicException $e) {
81
                if (!$this->container->get('kernel')->isDebug()) {
82
                    $logger = $this->get('logger');
83
                    $logger->error($e->getMessage());
84
                } else {
85
                    throw $e;
86
                }
87
            }
88
        } else {
89
            //Trying to find another node with this slug, in another language
90
            $node = $entityManager->getRepository('AlpixelCMSBundle:Node')
91
                ->findOnePublishedBySlug($slug);
92
93
            if ($node !== null) {
94
                $translation = $entityManager->getRepository('AlpixelCMSBundle:Node')
95
                    ->findTranslation($node, $request->getLocale());
96 View Code Duplication
                if ($translation !== null) {
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...
97
                    return $this->redirect(
98
                        $this->generateUrl(
99
                            'alpixel_cms',
100
                            [
101
                                'slug'    => $translation->getSlug(),
102
                                '_locale' => $translation->getLocale(),
103
                            ]
104
                        ), 301
105
                    );
106
                }
107
            }
108
        }
109
110
        throw $this->createNotFoundException();
111
    }
112
113
    /**
114
     * @param $node
115
     *
116
     * @return Response
117
     */
118
    public function displayNodeAdminBarAction(Request $request, $node)
119
    {
120
        $entityManager = $this->get('doctrine.orm.entity_manager');
121
        $node = $entityManager->getRepository('AlpixelCMSBundle:Node')->find($node);
122
123
        $response = new Response();
124
        $response->setPrivate();
125
        $response->setMaxAge(900);
126
127
        if ($this->isAuthenticated($request)) {
128
            $content = $this->renderView(
129
                'AlpixelCMSBundle:admin:blocks/admin_bar_page.html.twig',
130
                [
131
                    'node' => $node,
132
                    'link' => $this->generateUrl(
133
                        'alpixel_admin_cms_node_forwardEdit',
134
                        [
135
                            'type' => $node->getType(),
136
                            'id'   => $node->getId(),
137
                        ]
138
                    ),
139
                ]
140
            );
141
            $response->setContent($content);
142
        }
143
144
        return $response;
145
    }
146
147
    /**
148
     * @param $link
149
     *
150
     * @return Response
151
     */
152
    public function displayCustomAdminBarAction(Request $request, $link)
153
    {
154
        $response = new Response();
155
        $response->setPrivate();
156
        $response->setMaxAge(900);
157
158
        if ($this->isAuthenticated($request)) {
159
            $content = $this->renderView(
160
                'AlpixelCMSBundle:admin:blocks/admin_bar_page.html.twig',
161
                [
162
                    'link' => $link,
163
                ]
164
            );
165
            $response->setContent($content);
166
        }
167
168
        return $response;
169
    }
170
171
    /**
172
     * @param Request $request
173
     */
174
    private function isAuthenticated(Request $request)
175
    {
176
        $canEdit = $request->cookies->get('can_edit');
177
178
        if (isset($canEdit)) {
179
            if ($request->getSession()->has('_security_admin')) {
180
                try {
181
                    $token = unserialize($request->getSession()->get('_security_admin'));
182
                    $user = $token->getUser();
183
184
                    return $canEdit === hash(
185
                        'sha256',
186
                        'can_edit'.$this->container->getParameter('secret').$user->getSalt()
187
                    );
188
                } catch (ContextErrorException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
189
                }
190
            }
191
        }
192
193
        return false;
194
    }
195
}
196