Completed
Pull Request — master (#433)
by Paul
06:40
created

SitemapController::xmlAction()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 57
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 57
rs 8.7433
c 0
b 0
f 0
cc 5
eloc 35
nc 1
nop 1

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\SitemapBundle\Controller;
4
5
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
7
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
8
use Symfony\Component\HttpFoundation\JsonResponse;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\Response;
11
use Victoire\Bundle\CoreBundle\Entity\WebViewInterface;
12
use Victoire\Bundle\PageBundle\Entity\BasePage;
13
use Victoire\Bundle\PageBundle\Helper\PageHelper;
14
use Victoire\Bundle\SeoBundle\Entity\PageSeo;
15
use Victoire\Bundle\SitemapBundle\Form\SitemapPriorityPageSeoType;
16
use Victoire\Bundle\ViewReferenceBundle\ViewReference\BusinessPageReference;
17
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
18
19
/**
20
 * Victoire sitemap controller.
21
 *
22
 * @Route("/sitemap")
23
 */
24
class SitemapController extends Controller
25
{
26
    /**
27
     * Get the whole list of published pages
28
     * #1 get the _locale related homepage
29
     * #2 parse recursively and extract every persisted pages ids
30
     * #3 load these pages with seo (if exists)
31
     * #4 parse recursively and extract every VirtualBusinessPages references
32
     * #5 prepare VirtualBusinessPages.
33
     *
34
     * @Route(".{_format}", name="victoire_sitemap_xml", Requirements={"_format" = "xml"})
35
     *
36
     * @return Response
37
     */
38
    public function xmlAction(Request $request)
39
    {
40
        $em = $this->getDoctrine()->getManager();
41
        $homepage = $em->getRepository('VictoirePageBundle:BasePage')
0 ignored issues
show
Bug introduced by
The method findOneByHomepage() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
42
            ->findOneByHomepage($request->getLocale());
43
44
        /** @var ViewReference $tree */
45
        $tree = $this->get('victoire_view_reference.repository')->getOneReferenceByParameters(
46
            ['viewId' => $homepage->getId()],
47
            true,
48
            true
49
        );
50
51
        $ids = [$tree->getViewId()];
52
53
        $getChildrenIds = function (ViewReference $tree) use (&$getChildrenIds, $ids) {
54
            foreach ($tree->getChildren() as $child) {
55
                $ids[] = $child->getViewId();
56
                $ids = array_merge($ids, $getChildrenIds($child));
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $ids, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
57
            }
58
59
            return $ids;
60
        };
61
62
        $pages = $em->getRepository('VictoirePageBundle:BasePage')
63
            ->getAll(true)
64
            ->joinSeo()
65
            ->filterByIds($getChildrenIds($tree))
66
            ->run();
67
68
        /** @var PageHelper $pageHelper */
69
        $pageHelper = $this->get('victoire_page.page_helper');
70
        $entityManager = $this->getDoctrine()->getManager();
71
72
        $getBusinessPages = function (ViewReference $tree) use (&$getBusinessPages, $pageHelper, $entityManager) {
73
            $businessPages = [];
74
            foreach ($tree->getChildren() as $child) {
75
                if ($child instanceof BusinessPageReference
76
                    && $child->getViewNamespace() == 'Victoire\Bundle\BusinessPageBundle\Entity\VirtualBusinessPage') {
77
                    $entity = $entityManager->getRepository($child->getEntityNamespace())->find($child->getEntityId());
78
                    /** @var WebViewInterface $businessPage */
79
                    $businessPage = $pageHelper->findPageByReference($child, $entity);
80
                    $businessPage->setReference($child);
81
                    $businessPages[] = $businessPage;
82
                }
83
                $businessPages = array_merge($businessPages, $getBusinessPages($child));
84
            }
85
86
            return $businessPages;
87
        };
88
89
        $pages = array_merge($pages, $getBusinessPages($tree));
90
91
        return $this->render('VictoireSitemapBundle:Sitemap:sitemap.xml.twig', [
92
            'pages' => $pages,
93
        ]);
94
    }
95
96
    /**
97
     * Show sitemap as tree and reorganize it by dnd.
98
     *
99
     * @Route("/reorganize", name="victoire_sitemap_reorganize", options={"expose"=true})
100
     * @Template()
101
     *
102
     * @return JsonResponse
103
     */
104
    public function reorganizeAction(Request $request)
105
    {
106
        $em = $this->getDoctrine()->getManager();
107
        $pageRepo = $em->getRepository('VictoirePageBundle:BasePage');
108
        $response = [
109
            'success' => false,
110
        ];
111
        if ($request->getMethod() === 'POST') {
112
            $sorted = $request->request->get('sorted');
113
            $depths = [];
114
            //reorder pages positions
115
            foreach ($sorted as $item) {
116
                $depths[$item['depth']][$item['item_id']] = 1;
117
                $page = $pageRepo->findOneById($item['item_id']);
0 ignored issues
show
Bug introduced by
The method findOneById() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
118
                if ($page !== null) {
119
                    if ($item['parent_id'] !== '') {
120
                        $parent = $pageRepo->findOneById($item['parent_id']);
0 ignored issues
show
Bug introduced by
The method findOneById() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
121
                        $page->setParent($parent);
122
                    } else {
123
                        $page->setParent(null);
124
                    }
125
                    $page->setPosition(count($depths[$item['depth']]));
126
                    $em->persist($page);
127
                }
128
            }
129
            $em->flush();
130
131
            $response = [
132
                'success' => true,
133
                'message' => $this->get('translator')->trans('sitemap.changed.success', [], 'victoire'),
134
            ];
135
        }
136
137
        $allPages = $em->getRepository('VictoirePageBundle:BasePage')->findAll();
138
        $forms = [];
139
        foreach ($allPages as $_page) {
140
            $forms[$_page->getId()] = $this->createSitemapPriorityType($_page)->createView();
141
        }
142
143
        $pages = $em->getRepository('VictoirePageBundle:BasePage')->findByParent(null, ['position' => 'ASC']);
0 ignored issues
show
Bug introduced by
The method findByParent() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
144
        $response['html'] = $this->container->get('templating')->render(
145
            'VictoireSitemapBundle:Sitemap:reorganize.html.twig',
146
            [
147
                'pages' => $pages,
148
                'forms' => $forms,
149
            ]
150
        );
151
152
        return new JsonResponse($response);
153
    }
154
155
    /**
156
     * Change the sitemap priority for the given page.
157
     *
158
     * @Route("/changePriority/{id}", name="victoire_sitemap_changePriority", options={"expose"=true})
159
     *
160
     * @return JsonResponse
161
     */
162
    public function changePriorityAction(Request $request, BasePage $page)
163
    {
164
        $form = $this->createSitemapPriorityType($page);
165
        $form->handleRequest($request);
166
        $params = [
167
            'success' => $form->isValid(),
168
        ];
169
        if ($form->isValid()) {
170
            if (!$page->getSeo()) {
171
                $seo = new PageSeo();
172
                $page->setSeo($seo);
173
            }
174
            $this->get('doctrine.orm.entity_manager')->persist($page->getSeo());
175
            $this->get('doctrine.orm.entity_manager')->flush();
176
177
            // congratulate user, the action succeed
178
            $message = $this->get('translator')->trans(
179
                'sitemap.changedPriority.success',
180
                [
181
                    '%priority%' => $page->getSeo()->getSitemapPriority(),
182
                    '%pageName%' => $page->getName(),
183
                    ],
184
                'victoire'
185
            );
186
            $params['message'] = $message;
187
        }
188
189
        return new JsonResponse($params);
190
    }
191
192
    /**
193
     * Create a sitemap priority type.
194
     *
195
     * @return \Symfony\Component\Form\Form The form
196
     **/
197
    protected function createSitemapPriorityType(BasePage $page)
198
    {
199
        $form = $this->createForm(SitemapPriorityPageSeoType::class, $page->getSeo(), [
200
                'action' => $this->generateUrl('victoire_sitemap_changePriority', [
201
                        'id' => $page->getId(),
202
                    ]
203
                ),
204
                'method' => 'PUT',
205
                'attr'   => [
206
                    'class'       => 'sitemapPriorityForm form-inline',
207
                    'data-pageId' => $page->getId(),
208
                    'id'          => 'sitemap-priority-type-'.$page->getId(),
209
                    'style'       => 'display: inline;',
210
                ],
211
            ]
212
        );
213
214
        return $form;
215
    }
216
}
217