Completed
Pull Request — master (#323)
by Leny
12:57 queued 06:24
created

SitemapController::xmlAction()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 65
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 65
rs 8.6195
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\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
        /**
53
         * @param ViewReference $tree
54
         * @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...
55
         */
56
        $getChildrenIds = function ($tree) use (&$getChildrenIds, $ids) {
57
            foreach ($tree->getChildren() as $child) {
58
                $ids[] = $child->getViewId();
59
                $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...
60
            }
61
62
            return $ids;
63
        };
64
65
        $pages = $em->getRepository('VictoirePageBundle:BasePage')
66
            ->getAll(true)
67
            ->joinSeo()
68
            ->filterByIds($getChildrenIds($tree))
69
            ->run();
70
71
        /** @var PageHelper $pageHelper */
72
        $pageHelper = $this->get('victoire_page.page_helper');
73
        $entityManager = $this->getDoctrine()->getManager();
74
75
        /**
76
         * @param BusinessPageReference $tree
77
         * @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...
78
         */
79
        $getBusinessPages = function ($tree) use (&$getBusinessPages, $pageHelper, $entityManager) {
80
            $businessPages = [];
81
            foreach ($tree->getChildren() as $child) {
82
                if ($child instanceof BusinessPageReference
83
                    && $child->getViewNamespace() == 'Victoire\Bundle\BusinessPageBundle\Entity\VirtualBusinessPage') {
84
                    $entity = $entityManager->getRepository($child->getEntityNamespace())->find($child->getEntityId());
85
                    /** @var WebViewInterface $businessPage */
86
                    $businessPage = $pageHelper->findPageByReference($child, $entity);
87
                    $businessPage->setReference($child);
88
                    $businessPages[] = $businessPage;
89
                }
90
                $businessPages = array_merge($businessPages, $getBusinessPages($child));
91
            }
92
93
            return $businessPages;
94
        };
95
96
        $pages = array_merge($pages, $getBusinessPages($tree));
97
98
        return $this->render('VictoireSitemapBundle:Sitemap:sitemap.xml.twig', [
99
            'pages' => $pages,
100
        ]);
101
    }
102
103
    /**
104
     * Show sitemap as tree and reorganize it by dnd.
105
     *
106
     * @Route("/reorganize", name="victoire_sitemap_reorganize", options={"expose"=true})
107
     * @Template()
108
     *
109
     * @return JsonResponse
110
     */
111
    public function reorganizeAction()
112
    {
113
        $em = $this->getDoctrine()->getManager();
114
        $pageRepo = $em->getRepository('VictoirePageBundle:BasePage');
115
        $response = [
116
            'success' => false,
117
        ];
118
        if ($this->get('request')->getMethod() === 'POST') {
119
            $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...
120
            $depths = [];
121
            //reorder pages positions
122
            foreach ($sorted as $item) {
123
                $depths[$item['depth']][$item['item_id']] = 1;
124
                $page = $pageRepo->findOneById($item['item_id']);
125
                if ($page !== null) {
126
                    if ($item['parent_id'] !== '') {
127
                        $parent = $pageRepo->findOneById($item['parent_id']);
128
                        $page->setParent($parent);
129
                    } else {
130
                        $page->setParent(null);
131
                    }
132
                    $page->setPosition(count($depths[$item['depth']]));
133
                    $em->persist($page);
134
                }
135
            }
136
            $em->flush();
137
138
            $response = [
139
                'success' => true,
140
                'message' => $this->get('translator')->trans('sitemap.changed.success', [], 'victoire'),
141
            ];
142
        }
143
144
        $allPages = $em->getRepository('VictoirePageBundle:BasePage')->findAll();
145
        $forms = [];
146
        foreach ($allPages as $_page) {
147
            $forms[$_page->getId()] = $this->createSitemapPriorityType($_page)->createView();
148
        }
149
150
        $pages = $em->getRepository('VictoirePageBundle:BasePage')->findByParent(null, ['position' => 'ASC']);
151
        $response['html'] = $this->container->get('victoire_templating')->render(
152
            'VictoireSitemapBundle:Sitemap:reorganize.html.twig',
153
            [
154
                'pages' => $pages,
155
                'forms' => $forms,
156
            ]
157
        );
158
159
        return new JsonResponse($response);
160
    }
161
162
    /**
163
     * Change the sitemap priority for the given page.
164
     *
165
     * @Route("/changePriority/{id}", name="victoire_sitemap_changePriority", options={"expose"=true})
166
     *
167
     * @return JsonResponse
168
     */
169
    public function changePriorityAction(Request $request, BasePage $page)
170
    {
171
        $form = $this->createSitemapPriorityType($page);
172
        $form->handleRequest($request);
173
        $params = [
174
            'success' => $form->isValid(),
175
        ];
176
        if ($form->isValid()) {
177
            if (!$page->getSeo()) {
178
                $seo = new PageSeo();
179
                $page->setSeo($seo);
180
            }
181
            $this->get('doctrine.orm.entity_manager')->persist($page->getSeo());
182
            $this->get('doctrine.orm.entity_manager')->flush();
183
184
            // congratulate user, the action succeed
185
            $message = $this->get('translator')->trans(
186
                'sitemap.changedPriority.success',
187
                [
188
                    '%priority%' => $page->getSeo()->getSitemapPriority(),
189
                    '%pageName%' => $page->getName(),
190
                    ],
191
                'victoire'
192
            );
193
            $params['message'] = $message;
194
        }
195
196
        return new JsonResponse($params);
197
    }
198
199
    /**
200
     * Create a sitemap priority type.
201
     *
202
     * @return \Symfony\Component\Form\Form The form
203
     **/
204
    protected function createSitemapPriorityType(BasePage $page)
205
    {
206
        $form = $this->createForm(
207
            'victoire_sitemap_priority_pageseo_type',
208
            $page->getSeo(),
209
            [
210
                'action'     => $this->generateUrl('victoire_sitemap_changePriority', [
211
                        'id' => $page->getId(),
212
                    ]
213
                ),
214
                'method' => 'PUT',
215
                'attr'   => [
216
                    'class'       => 'sitemapPriorityForm form-inline',
217
                    'data-pageId' => $page->getId(),
218
                    'id'          => 'sitemap-priority-type-'.$page->getId(),
219
                    'style'       => 'display: inline;',
220
                ],
221
            ]
222
        );
223
224
        return $form;
225
    }
226
}
227