Completed
Push — master ( cde4a2...ad2587 )
by Leny
07:38
created

SitemapController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 196
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 15
c 1
b 0
f 0
lcom 1
cbo 11
dl 0
loc 196
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
B xmlAction() 0 57 5
B reorganizeAction() 0 50 6
B changePriorityAction() 0 29 3
A createSitemapPriorityType() 0 22 1
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\ViewReferenceBundle\ViewReference\BusinessPageReference;
16
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
17
18
/**
19
 * Victoire sitemap controller.
20
 *
21
 * @Route("/sitemap")
22
 */
23
class SitemapController extends Controller
24
{
25
    /**
26
     * Get the whole list of published pages
27
     * #1 get the _locale related homepage
28
     * #2 parse recursively and extract every persisted pages ids
29
     * #3 load these pages with seo (if exists)
30
     * #4 parse recursively and extract every VirtualBusinessPages references
31
     * #5 prepare VirtualBusinessPages.
32
     *
33
     * @Route(".{_format}", name="victoire_sitemap_xml", Requirements={"_format" = "xml"})
34
     *
35
     * @return Response
36
     */
37
    public function xmlAction(Request $request)
38
    {
39
        $em = $this->getDoctrine()->getManager();
40
        $homepage = $em->getRepository('VictoirePageBundle:BasePage')
41
            ->findOneByHomepage($request->getLocale());
42
43
        /** @var ViewReference $tree */
44
        $tree = $this->get('victoire_view_reference.repository')->getOneReferenceByParameters(
45
            ['viewId' => $homepage->getId()],
46
            true,
47
            true
48
        );
49
50
        $ids = [$tree->getViewId()];
51
52
        $getChildrenIds = function (ViewReference $tree) use (&$getChildrenIds, $ids) {
53
            foreach ($tree->getChildren() as $child) {
54
                $ids[] = $child->getViewId();
55
                $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...
56
            }
57
58
            return $ids;
59
        };
60
61
        $pages = $em->getRepository('VictoirePageBundle:BasePage')
62
            ->getAll(true)
63
            ->joinSeo()
64
            ->filterByIds($getChildrenIds($tree))
65
            ->run();
66
67
        /** @var PageHelper $pageHelper */
68
        $pageHelper = $this->get('victoire_page.page_helper');
69
        $entityManager = $this->getDoctrine()->getManager();
70
71
        $getBusinessPages = function (ViewReference $tree) use (&$getBusinessPages, $pageHelper, $entityManager) {
72
            $businessPages = [];
73
            foreach ($tree->getChildren() as $child) {
74
                if ($child instanceof BusinessPageReference
75
                    && $child->getViewNamespace() == 'Victoire\Bundle\BusinessPageBundle\Entity\VirtualBusinessPage') {
76
                    $entity = $entityManager->getRepository($child->getEntityNamespace())->find($child->getEntityId());
77
                    /** @var WebViewInterface $businessPage */
78
                    $businessPage = $pageHelper->findPageByReference($child, $entity);
79
                    $businessPage->setReference($child);
80
                    $businessPages[] = $businessPage;
81
                }
82
                $businessPages = array_merge($businessPages, $getBusinessPages($child));
83
            }
84
85
            return $businessPages;
86
        };
87
88
        $pages = array_merge($pages, $getBusinessPages($tree));
89
90
        return $this->render('VictoireSitemapBundle:Sitemap:sitemap.xml.twig', [
91
            'pages' => $pages,
92
        ]);
93
    }
94
95
    /**
96
     * Show sitemap as tree and reorganize it by dnd.
97
     *
98
     * @Route("/reorganize", name="victoire_sitemap_reorganize", options={"expose"=true})
99
     * @Template()
100
     *
101
     * @return JsonResponse
102
     */
103
    public function reorganizeAction()
104
    {
105
        $em = $this->getDoctrine()->getManager();
106
        $pageRepo = $em->getRepository('VictoirePageBundle:BasePage');
107
        $response = [
108
            'success' => false,
109
        ];
110
        if ($this->get('request')->getMethod() === 'POST') {
111
            $sorted = $this->getRequest()->request->get('sorted');
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
112
            $depths = [];
113
            //reorder pages positions
114
            foreach ($sorted as $item) {
115
                $depths[$item['depth']][$item['item_id']] = 1;
116
                $page = $pageRepo->findOneById($item['item_id']);
117
                if ($page !== null) {
118
                    if ($item['parent_id'] !== '') {
119
                        $parent = $pageRepo->findOneById($item['parent_id']);
120
                        $page->setParent($parent);
121
                    } else {
122
                        $page->setParent(null);
123
                    }
124
                    $page->setPosition(count($depths[$item['depth']]));
125
                    $em->persist($page);
126
                }
127
            }
128
            $em->flush();
129
130
            $response = [
131
                'success' => true,
132
                'message' => $this->get('translator')->trans('sitemap.changed.success', [], 'victoire'),
133
            ];
134
        }
135
136
        $allPages = $em->getRepository('VictoirePageBundle:BasePage')->findAll();
137
        $forms = [];
138
        foreach ($allPages as $_page) {
139
            $forms[$_page->getId()] = $this->createSitemapPriorityType($_page)->createView();
140
        }
141
142
        $pages = $em->getRepository('VictoirePageBundle:BasePage')->findByParent(null, ['position' => 'ASC']);
143
        $response['html'] = $this->container->get('victoire_templating')->render(
144
            'VictoireSitemapBundle:Sitemap:reorganize.html.twig',
145
            [
146
                'pages' => $pages,
147
                'forms' => $forms,
148
            ]
149
        );
150
151
        return new JsonResponse($response);
152
    }
153
154
    /**
155
     * Change the sitemap priority for the given page.
156
     *
157
     * @Route("/changePriority/{id}", name="victoire_sitemap_changePriority", options={"expose"=true})
158
     *
159
     * @return JsonResponse
160
     */
161
    public function changePriorityAction(Request $request, BasePage $page)
162
    {
163
        $form = $this->createSitemapPriorityType($page);
164
        $form->handleRequest($request);
165
        $params = [
166
            'success' => $form->isValid(),
167
        ];
168
        if ($form->isValid()) {
169
            if (!$page->getSeo()) {
170
                $seo = new PageSeo();
171
                $page->setSeo($seo);
172
            }
173
            $this->get('doctrine.orm.entity_manager')->persist($page->getSeo());
174
            $this->get('doctrine.orm.entity_manager')->flush();
175
176
            // congratulate user, the action succeed
177
            $message = $this->get('translator')->trans(
178
                'sitemap.changedPriority.success',
179
                [
180
                    '%priority%' => $page->getSeo()->getSitemapPriority(),
181
                    '%pageName%' => $page->getName(),
182
                    ],
183
                'victoire'
184
            );
185
            $params['message'] = $message;
186
        }
187
188
        return new JsonResponse($params);
189
    }
190
191
    /**
192
     * Create a sitemap priority type.
193
     *
194
     * @return \Symfony\Component\Form\Form The form
195
     **/
196
    protected function createSitemapPriorityType(BasePage $page)
197
    {
198
        $form = $this->createForm(
199
            'victoire_sitemap_priority_pageseo_type',
200
            $page->getSeo(),
201
            [
202
                'action'     => $this->generateUrl('victoire_sitemap_changePriority', [
203
                        'id' => $page->getId(),
204
                    ]
205
                ),
206
                'method' => 'PUT',
207
                'attr'   => [
208
                    'class'       => 'sitemapPriorityForm form-inline',
209
                    'data-pageId' => $page->getId(),
210
                    'id'          => 'sitemap-priority-type-'.$page->getId(),
211
                    'style'       => 'display: inline;',
212
                ],
213
            ]
214
        );
215
216
        return $form;
217
    }
218
}
219