Completed
Pull Request — master (#336)
by Leny
11:52
created

BasePageController::translateAction()   B

Complexity

Conditions 8
Paths 26

Size

Total Lines 60
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 60
rs 7.0677
cc 8
eloc 39
nc 26
nop 2

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 Victoire\Bundle\PageBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\Response;
8
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
9
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
10
use Victoire\Bundle\CoreBundle\Controller\VictoireAlertifyControllerTrait;
11
use Victoire\Bundle\PageBundle\Entity\BasePage;
12
use Victoire\Bundle\PageBundle\Entity\Page;
13
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
14
15
/**
16
 * The base page controller is used to interact with all kind of pages.
17
 **/
18
class BasePageController extends Controller
19
{
20
    use VictoireAlertifyControllerTrait;
21
22
    public function showAction(Request $request, $url = '')
23
    {
24
        $response = $this->get('victoire_page.page_helper')->renderPageByUrl(
25
            $url,
26
            $request->getLocale(),
27
            $request->isXmlHttpRequest()
28
        );
29
30
        //throw an exception is the page is not valid
31
        return $response;
32
    }
33
34
    public function showByIdAction(Request $request, $viewId, $entityId = null)
35
    {
36
        $parameters = ['viewId' => $viewId];
37
        if ($entityId) {
38
            $parameters['entityId'] = $entityId;
39
        }
40
        $page = $this->get('victoire_page.page_helper')->findPageByParameters($parameters);
41
42
        return $this->redirect($this->generateUrl('victoire_core_page_show', array_merge(
43
                ['url' => $page->getReference()->getUrl()],
44
                $request->query->all()
45
            )
46
        ));
47
    }
48
49
    public function showBusinessPageByIdAction($entityId, $type)
50
    {
51
        $businessEntityHelper = $this->get('victoire_core.helper.queriable_business_entity_helper');
52
        $businessEntity = $businessEntityHelper->findById($type);
53
        $entity = $businessEntityHelper->getByBusinessEntityAndId($businessEntity, $entityId);
54
55
        $refClass = new \ReflectionClass($entity);
56
57
        $templateId = $this->get('victoire_business_page.business_page_helper')
58
            ->guessBestPatternIdForEntity($refClass, $entityId, $this->container->get('doctrine.orm.entity_manager'));
59
60
        $page = $this->get('victoire_page.page_helper')->findPageByParameters([
61
            'viewId'   => $templateId,
62
            'entityId' => $entityId,
63
        ]);
64
        $this->get('victoire_widget_map.builder')->build($page);
65
        $this->get('victoire_widget_map.widget_data_warmer')->warm(
66
            $this->get('doctrine.orm.entity_manager'),
67
            $page
68
        );
69
70
        return $this->redirect(
71
            $this->generateUrl(
72
                'victoire_core_page_show',
73
                [
74
                    'url' => $page->getReference()->Url(),
75
                ]
76
            )
77
        );
78
    }
79
80
    /**
81
     * New page.
82
     *
83
     * @param bool $isHomepage
84
     *
85
     * @return []
0 ignored issues
show
Documentation introduced by
The doc-type [] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
86
     */
87
    protected function newAction($isHomepage = false)
88
    {
89
        $entityManager = $this->get('doctrine.orm.entity_manager');
90
        $page = $this->getNewPage();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\PageBund...ller\BasePageController as the method getNewPage() does only exist in the following sub-classes of Victoire\Bundle\PageBund...ller\BasePageController: Victoire\Bundle\BlogBund...ntroller\BlogController, Victoire\Bundle\PageBund...dministrationController. 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...
91
        if ($page instanceof Page) {
92
            $page->setHomepage($isHomepage ? $isHomepage : 0);
0 ignored issues
show
Bug introduced by
It seems like $isHomepage ? $isHomepage : 0 can also be of type integer; however, Victoire\Bundle\PageBund...iewTrait::setHomepage() does only seem to accept boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
93
        }
94
95
        $form = $this->get('form.factory')->create($this->getNewPageType(), $page);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\PageBund...ller\BasePageController as the method getNewPageType() does only exist in the following sub-classes of Victoire\Bundle\PageBund...ller\BasePageController: Victoire\Bundle\BlogBund...ntroller\BlogController, Victoire\Bundle\PageBund...dministrationController. 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...
96
97
        $form->handleRequest($this->get('request'));
98
        if ($form->isValid()) {
99
            if ($page->getParent()) {
100
                $pageNb = count($page->getParent()->getChildren());
101
            } else {
102
                $pageNb = count($entityManager->getRepository('VictoirePageBundle:BasePage')->findByParent(null));
103
            }
104
            // + 1 because position start at 1, not 0
105
            $page->setPosition($pageNb + 1);
106
107
            $page->setAuthor($this->getUser());
108
            $entityManager->persist($page);
109
            $entityManager->flush();
110
111
            // If the $page is a BusinessEntity (eg. an Article), compute it's url
112
            if (null !== $this->get('victoire_core.helper.business_entity_helper')->findByEntityInstance($page)) {
113
                $page = $this
114
                        ->get('victoire_business_page.business_page_builder')
115
                        ->generateEntityPageFromTemplate($page->getTemplate(), $page, $entityManager);
116
            }
117
118
            $this->congrat($this->get('translator')->trans('victoire_page.create.success', [], 'victoire'));
119
            $viewReference = $this->get('victoire_view_reference.repository')->getOneReferenceByParameters([
120
                'viewId' => $page->getId(),
121
            ]);
122
123
            return [
124
                'success'  => true,
125
                'url'      => $this->generateUrl(
126
                    'victoire_core_page_show',
127
                    [
128
                        '_locale' => $page->getLocale(),
129
                        'url'     => $viewReference->getUrl(),
130
                    ]
131
                ),
132
            ];
133
        } else {
134
            $formErrorHelper = $this->get('victoire_form.error_helper');
135
136
            return [
137
                'success' => false,
138
                'message' => $formErrorHelper->getRecursiveReadableErrors($form),
139
                'html'    => $this->get('victoire_templating')->render(
140
                    $this->getBaseTemplatePath().':new.html.twig',
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\PageBund...ller\BasePageController as the method getBaseTemplatePath() does only exist in the following sub-classes of Victoire\Bundle\PageBund...ller\BasePageController: Victoire\Bundle\BlogBund...ntroller\BlogController, Victoire\Bundle\PageBund...dministrationController. 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...
141
                    ['form' => $form->createView()]
142
                ),
143
            ];
144
        }
145
    }
146
147
    /**
148
     * Page settings.
149
     *
150
     * @param Request  $request
151
     * @param BasePage $page
152
     *
153
     * @return array
154
     */
155
    protected function settingsAction(Request $request, BasePage $page)
156
    {
157
        $entityManager = $this->getDoctrine()->getManager();
158
        $form = $this->createForm($this->getPageSettingsType(), $page);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\PageBund...ller\BasePageController as the method getPageSettingsType() does only exist in the following sub-classes of Victoire\Bundle\PageBund...ller\BasePageController: Victoire\Bundle\BlogBund...ntroller\BlogController, Victoire\Bundle\PageBund...dministrationController. 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...
159
        $businessProperties = [];
160
161
        //if the page is a business entity page pattern
162
        if ($page instanceof BusinessTemplate) {
163
            //we can use the business entity properties on the seo
164
            $businessEntity = $this->get('victoire_core.helper.business_entity_helper')->findById($page->getBusinessEntityId());
165
            $businessProperties = $businessEntity->getBusinessPropertiesByType('seoable');
166
        }
167
168
        //if the page is a business entity page
169
        if ($page instanceof BusinessPage) {
170
            $form = $this->createForm($this->getBusinessPageType(), $page);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\PageBund...ller\BasePageController as the method getBusinessPageType() does only exist in the following sub-classes of Victoire\Bundle\PageBund...ller\BasePageController: Victoire\Bundle\PageBund...dministrationController. 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...
171
        }
172
173
        $form->handleRequest($request);
174
175
        if ($form->isValid()) {
176
            $entityManager->persist($page);
177
            $entityManager->flush();
178
            /** @var ViewReference $viewReference */
179
            $viewReference = $this->get('victoire_view_reference.repository')
180
                ->getOneReferenceByParameters(['viewId' => $page->getId()]);
181
182
            $page->setReference($viewReference);
183
184
            $this->congrat($this->get('translator')->trans('victoire_page.update.success', [], 'victoire'));
185
186
            return [
187
                'success' => true,
188
                'url'     => $this->generateUrl(
189
                    'victoire_core_page_show', [
190
                        '_locale' => $page->getLocale(),
191
                        'url'     => $viewReference->getUrl(),
192
                    ]
193
                ),
194
            ];
195
        }
196
        //we display the form
197
        $errors = $this->get('victoire_form.error_helper')->getRecursiveReadableErrors($form);
198
199
        return  [
200
            'success' => empty($errors),
201
            'html'    => $this->get('victoire_templating')->render(
202
                $this->getBaseTemplatePath().':settings.html.twig',
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\PageBund...ller\BasePageController as the method getBaseTemplatePath() does only exist in the following sub-classes of Victoire\Bundle\PageBund...ller\BasePageController: Victoire\Bundle\BlogBund...ntroller\BlogController, Victoire\Bundle\PageBund...dministrationController. 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...
203
                [
204
                    'page'               => $page,
205
                    'form'               => $form->createView(),
206
                    'businessProperties' => $businessProperties,
207
                ]
208
            ),
209
            'message' => $errors,
210
        ];
211
    }
212
213
    /**
214
     * @param Page $page The page to delete
215
     *
216
     * @return Response
217
     */
218
    public function deleteAction(BasePage $page)
219
    {
220
        $response = null;
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
221
222
        try {
223
            //it should not be allowed to try to delete an undeletable page
224
            if ($page->isUndeletable()) {
225
                $message = $this->get('translator')->trans('page.undeletable', [], 'victoire');
226
                throw new \Exception($message);
227
            }
228
229
            //the entity manager
230
            $entityManager = $this->get('doctrine.orm.entity_manager');
231
232
            //remove the page
233
            $entityManager->remove($page);
234
235
            //flush the modifications
236
            $entityManager->flush();
237
238
            //redirect to the homepage
239
240
            $homepageUrl = $this->generateUrl('victoire_core_homepage_show');
241
242
            $response = [
243
                'success' => true,
244
                'url'     => $homepageUrl,
245
            ];
246
        } catch (\Exception $ex) {
247
            $response = [
248
                'success' => false,
249
                'message' => $ex->getMessage(),
250
            ];
251
        }
252
253
        return $response;
254
    }
255
}
256