getNotPersistedSettingsResponse()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 12
nc 1
nop 3
1
<?php
2
3
namespace Victoire\Bundle\SeoBundle\Controller;
4
5
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\Form\FormInterface;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
13
use Victoire\Bundle\CoreBundle\Controller\VictoireAlertifyControllerTrait;
14
use Victoire\Bundle\CoreBundle\Entity\View;
15
use Victoire\Bundle\SeoBundle\Entity\PageSeo;
16
use Victoire\Bundle\SeoBundle\Form\PageSeoType;
17
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
18
19
/**
20
 * The Page Seo controller.
21
 *
22
 * @Route("/victoire-dcms/seo")
23
 */
24
class PageSeoController extends Controller
25
{
26
    use VictoireAlertifyControllerTrait;
27
28
    /**
29
     * Display a form to edit Seo settings.
30
     *
31
     * @param Request $request
32
     * @param View    $view
33
     *
34
     * @Route("/{id}/settings", name="victoire_seo_pageSeo_settings")
35
     * @Method("GET")
36
     * @Template()
37
     *
38
     * @return JsonResponse
39
     */
40
    public function settingsAction(Request $request, View $view)
41
    {
42
        $pageSeo = $view->getSeo() ?: new PageSeo();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\CoreBundle\Entity\View as the method getSeo() does only exist in the following sub-classes of Victoire\Bundle\CoreBundle\Entity\View: Victoire\Bundle\BlogBundle\Entity\ArticleTemplate, Victoire\Bundle\BlogBundle\Entity\Blog, Victoire\Bundle\Business...dle\Entity\BusinessPage, Victoire\Bundle\Business...Entity\BusinessTemplate, Victoire\Bundle\Business...ity\VirtualBusinessPage, Victoire\Bundle\PageBundle\Entity\BasePage, Victoire\Bundle\PageBundle\Entity\Page. 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...
43
        $form = $this->createSettingsForm($pageSeo, $view);
44
45
        $form->handleRequest($request);
46
47
        $response = $this->getNotPersistedSettingsResponse(
48
            $form,
49
            $view,
50
            $request->query->get('novalidate', false)
51
        );
52
53
        return new JsonResponse($response);
54
    }
55
56
    /**
57
     * Save Seo settings.
58
     *
59
     * @param Request $request
60
     * @param View    $view
61
     *
62
     * @Route("/{id}/settings", name="victoire_seo_pageSeo_settings_post")
63
     * @Method("POST")
64
     * @Template()
65
     *
66
     * @return JsonResponse
67
     */
68
    public function settingsPostAction(Request $request, View $view)
69
    {
70
        $em = $this->getDoctrine()->getManager();
71
72
        $pageSeo = $view->getSeo() ?: new PageSeo();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\CoreBundle\Entity\View as the method getSeo() does only exist in the following sub-classes of Victoire\Bundle\CoreBundle\Entity\View: Victoire\Bundle\BlogBundle\Entity\ArticleTemplate, Victoire\Bundle\BlogBundle\Entity\Blog, Victoire\Bundle\Business...dle\Entity\BusinessPage, Victoire\Bundle\Business...Entity\BusinessTemplate, Victoire\Bundle\Business...ity\VirtualBusinessPage, Victoire\Bundle\PageBundle\Entity\BasePage, Victoire\Bundle\PageBundle\Entity\Page. 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...
73
        $form = $this->createSettingsForm($pageSeo, $view);
74
75
        $form->handleRequest($request);
76
        $novalidate = $request->query->get('novalidate', false);
77
78
        if (false === $novalidate && $form->isValid()) {
79
            $em->persist($pageSeo);
80
            $view->setSeo($pageSeo);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Victoire\Bundle\CoreBundle\Entity\View as the method setSeo() does only exist in the following sub-classes of Victoire\Bundle\CoreBundle\Entity\View: Victoire\Bundle\BlogBundle\Entity\ArticleTemplate, Victoire\Bundle\BlogBundle\Entity\Blog, Victoire\Bundle\Business...dle\Entity\BusinessPage, Victoire\Bundle\Business...Entity\BusinessTemplate, Victoire\Bundle\Business...ity\VirtualBusinessPage, Victoire\Bundle\PageBundle\Entity\BasePage, Victoire\Bundle\PageBundle\Entity\Page. 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...
81
            $em->persist($view);
82
            $em->flush();
83
84
            $this->get('victoire_core.current_view')->setCurrentView($view);
85
            $this->congrat('victoire_seo.save.success');
86
87
            $response = [
88
                'success' => true,
89
                'url'     => $this->getViewUrl($view),
90
            ];
91
        } else {
92
            $response = $this->getNotPersistedSettingsResponse($form, $view, $novalidate);
93
        }
94
95
        return new JsonResponse($response);
96
    }
97
98
    /**
99
     * Create PageSeo Form.
100
     *
101
     * @param PageSeo $pageSeo
102
     * @param View    $view
103
     *
104
     * @return FormInterface
105
     */
106
    private function createSettingsForm(PageSeo $pageSeo, View $view)
107
    {
108
        return $this->get('form.factory')->create(PageSeoType::class, $pageSeo,
109
            [
110
                'action' => $this->get('router')->generate('victoire_seo_pageSeo_settings_post',
111
                    [
112
                        'id' => $view->getId(),
113
                    ]
114
                ),
115
                'method' => 'POST',
116
            ]
117
        );
118
    }
119
120
    /**
121
     * Get JsonResponse array for Settings novalidate and form display.
122
     *
123
     * @param FormInterface $form
124
     * @param View          $view
125
     * @param $novalidate
126
     *
127
     * @return array
128
     */
129
    private function getNotPersistedSettingsResponse(FormInterface $form, View $view, $novalidate)
130
    {
131
        $template = sprintf(
132
            '%s:%s',
133
            $this->getBaseTemplatePath(),
134
            ($novalidate === false) ? 'settings.html.twig' : 'form.html.twig'
135
        );
136
137
        return [
138
            'success' => !$form->isSubmitted(),
139
            'html'    => $this->container->get('templating')->render(
140
                $template,
141
                [
142
                    'page'               => $view,
143
                    'form'               => $form->createView(),
144
                    'businessProperties' => $this->getBusinessProperties($view),
145
                ]
146
            ),
147
        ];
148
    }
149
150
    /**
151
     * Get url for a View using ViewReferences if necessary.
152
     *
153
     * @param View $view
154
     *
155
     * @return string
156
     */
157
    private function getViewUrl(View $view)
158
    {
159
        if (!method_exists($view, 'getUrl')) {
160
            return $this->generateUrl('victoire_business_template_show', ['id' => $view->getId()]);
161
        }
162
163
        /** @var ViewReference $viewReference */
164
        $viewReference = $this->container->get('victoire_view_reference.repository')
165
            ->getOneReferenceByParameters(['viewId' => $view->getId()]);
166
167
        $view->setReference($viewReference);
168
169
        return $this->generateUrl('victoire_core_page_show', ['url' => $viewReference->getUrl()]);
170
    }
171
172
    /**
173
     * Return BusinessEntity seaoable properties if View is a BusinessTemplate.
174
     *
175
     * @param View $view
176
     *
177
     * @return array
178
     */
179 View Code Duplication
    private function getBusinessProperties(View $view)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
180
    {
181
        $businessProperties = [];
182
183
        if ($view instanceof BusinessTemplate) {
184
            //we can use the business entity properties on the seo
185
            $businessEntity = $this->get('victoire_core.entity.business_entity_repository')->findOneBy(['name' => $view->getBusinessEntityName()]);
186
            $businessProperties = $businessEntity->getBusinessPropertiesByType('seoable');
187
        }
188
189
        return $businessProperties;
190
    }
191
192
    /**
193
     * @return string
194
     */
195
    private function getBaseTemplatePath()
196
    {
197
        return 'VictoireSeoBundle:PageSeo';
198
    }
199
}
200