Completed
Push — master ( d1535f...93b502 )
by Leny
06:44
created

BasePageController::showBusinessPageByIdAction()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 30
rs 8.8571
cc 1
eloc 18
nc 1
nop 2
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->container->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->container->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->container->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->container->get('victoire_business_page.business_page_helper')
58
            ->guessBestPatternIdForEntity($refClass, $entityId, $this->container->get('doctrine.orm.entity_manager'));
59
60
        $page = $this->container->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->container->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->container->get('victoire_core.helper.business_entity_helper')->findByEntityInstance($page)) {
113
                $page = $this->container
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.cache.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 View Code Duplication
        } else {
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...
134
            $formErrorHelper = $this->container->get('victoire_form.error_helper');
135
136
            return [
137
                'success' => false,
138
                'message' => $formErrorHelper->getRecursiveReadableErrors($form),
139
                'html'    => $this->container->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->container->get('victoire_view_reference.cache.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->container->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
     * Page translation.
215
     *
216
     * @param Request  $request
217
     * @param BasePage $page
218
     *
219
     * @return array
220
     */
221
    protected function translateAction(Request $request, BasePage $page)
222
    {
223
        $form = $this->createForm($this->getPageTranslateType(), $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 getPageTranslateType() 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...
224
225
        $businessProperties = [];
226
227
        if ($page instanceof BusinessTemplate) {
228
            $businessEntityId = $page->getBusinessEntityId();
229
            $businessEntity = $this->get('victoire_core.helper.business_entity_helper')->findById($businessEntityId);
230
            $businessProperties = $businessEntity->getBusinessPropertiesByType('seoable');
231
        }
232
233
        $form->handleRequest($request);
234
235 View Code Duplication
        if ($form->isValid()) {
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...
236
            $clone = $this->get('victoire_i18n.view_translation_manager')->addTranslation($page, $page->getName(), $page->getLocale());
237
238
            return [
239
                'success' => true,
240
                'url'     => $this->generateUrl('victoire_core_page_show', ['_locale' => $clone->getLocale(), 'url' => $clone->getUrl()]),
241
            ];
242
        }
243
        $errors = $this->get('victoire_form.error_helper')->getRecursiveReadableErrors($form);
244
245
        return [
246
            'success' => empty($errors),
247
            'html'    => $this->container->get('victoire_templating')->render(
248
                $this->getBaseTemplatePath().':translate.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...
249
                [
250
                    'page'               => $page,
251
                    'form'               => $form->createView(),
252
                    'businessProperties' => $businessProperties,
253
                ]
254
            ),
255
            'message' => $errors,
256
        ];
257
    }
258
259
    /**
260
     * @param Page $page The page to delete
261
     *
262
     * @return Response
263
     */
264
    public function deleteAction(BasePage $page)
265
    {
266
        $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...
267
268
        try {
269
            //it should not be allowed to try to delete an undeletable page
270
            if ($page->isUndeletable()) {
271
                $message = $this->get('translator')->trans('page.undeletable', [], 'victoire');
272
                throw new \Exception($message);
273
            }
274
275
            //the entity manager
276
            $entityManager = $this->get('doctrine.orm.entity_manager');
277
278
            //remove the page
279
            $entityManager->remove($page);
280
281
            //flush the modifications
282
            $entityManager->flush();
283
284
            //redirect to the homepage
285
286
            $homepageUrl = $this->generateUrl('victoire_core_homepage_show');
287
288
            $response = [
289
                'success' => true,
290
                'url'     => $homepageUrl,
291
            ];
292
        } catch (\Exception $ex) {
293
            $response = [
294
                'success' => false,
295
                'message' => $ex->getMessage(),
296
            ];
297
        }
298
299
        return $response;
300
    }
301
}
302