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

SitemapBundle/Controller/SitemapController.php (4 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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));
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
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
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
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