Completed
Push — master ( ef9fce...66659a )
by
unknown
14s
created

SitemapController::changePriorityAction()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 13
nc 4
nop 2
1
<?php
2
3
namespace Victoire\Bundle\SitemapBundle\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\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Victoire\Bundle\PageBundle\Entity\BasePage;
13
use Victoire\Bundle\SeoBundle\Entity\PageSeo;
14
use Victoire\Bundle\SitemapBundle\Form\SitemapPriorityPageSeoType;
15
16
/**
17
 * Victoire sitemap controller.
18
 *
19
 * @Route("/sitemap")
20
 */
21
class SitemapController extends Controller
22
{
23
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
24
     * Get Sitemap as XML.
25
     *
26
     * @Route(".{_format}", name="victoire_sitemap_xml", Requirements={"_format" = "xml"})
27
     *
28
     * @return Response
29
     */
30
    public function xmlAction(Request $request)
31
    {
32
        $pages = $this->get('victoire_sitemap.export.handler')->handle(
33
            $request->getLocale()
34
        );
35
36
        return $this->render('VictoireSitemapBundle:Sitemap:sitemap.xml.twig', [
37
            'pages' => $pages,
38
        ]);
39
    }
40
41
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
42
     * Show Sitemap as tree and save new order if necessary.
43
     *
44
     * @Route("/reorganize", name="victoire_sitemap_reorganize", options={"expose"=true})
45
     * @Template()
46
     *
47
     * @return JsonResponse
48
     */
49
    public function reorganizeAction(Request $request)
50
    {
51
        if ($request->isMethod('POST')) {
52
            $this->get('victoire_sitemap.sort.handler')->handle(
53
                $request->request->get('sorted')
54
            );
55
            $response['message'] = $this->get('translator')->trans('sitemap.changed.success', [], 'victoire');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
56
        }
57
58
        $basePageRepo = $this->getDoctrine()->getManager()->getRepository('VictoirePageBundle:BasePage');
59
        $basePages = $basePageRepo
60
            ->getAll(true)
61
            ->joinSeo()
62
            ->joinSeoTranslations($request->getLocale())
63
            ->run();
64
65
        $forms = [];
66
        foreach ($basePages as $_page) {
67
            $_pageSeo = $_page->getSeo() ?: new PageSeo();
68
            $forms[$_page->getId()] = $this->createSitemapPriorityType($_page, $_pageSeo)->createView();
69
        }
70
71
        $response['success'] = true;
0 ignored issues
show
Bug introduced by
The variable $response does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
72
        $response['html'] = $this->container->get('templating')->render(
73
            'VictoireSitemapBundle:Sitemap:reorganize.html.twig',
74
            [
75
                'pages' => $basePageRepo->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...
76
                'forms' => $forms,
77
            ]
78
        );
79
80
        return new JsonResponse($response);
81
    }
82
83
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$page" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
84
     * Change the sitemap priority for the given page.
85
     *
86
     * @Route("/changePriority/{id}", name="victoire_sitemap_changePriority", options={"expose"=true})
87
     *
88
     * @return JsonResponse
89
     */
90
    public function changePriorityAction(Request $request, BasePage $page)
91
    {
92
        $em = $this->get('doctrine.orm.entity_manager');
93
94
        $pageSeo = $page->getSeo() ?: new PageSeo();
95
        $pageSeo->setCurrentLocale($request->getLocale());
96
97
        $form = $this->createSitemapPriorityType($page, $pageSeo);
98
        $form->handleRequest($request);
99
        $params = [
100
            'success' => $form->isValid(),
101
        ];
102
103
        if ($form->isValid()) {
104
            $page->setSeo($pageSeo);
105
            $em->persist($pageSeo);
106
            $em->flush();
107
        }
108
109
        return new JsonResponse($params);
110
    }
111
112
    /**
113
     * Create a sitemap priority type.
114
     *
115
     * @param BasePage $page
116
     * @param PageSeo  $pageSeo
117
     *
118
     * @return \Symfony\Component\Form\Form
119
     */
120
    protected function createSitemapPriorityType(BasePage $page, PageSeo $pageSeo)
121
    {
122
        $form = $this->createForm(SitemapPriorityPageSeoType::class, $pageSeo, [
123
                'action' => $this->generateUrl('victoire_sitemap_changePriority', [
124
                        'id' => $page->getId(),
125
                    ]
126
                ),
127
                'method' => 'PUT',
128
                'attr'   => [
129
                    'class'       => 'sitemapPriorityForm form-inline',
130
                    'data-pageId' => $page->getId(),
131
                    'id'          => 'sitemap-priority-type-'.$page->getId(),
132
                    'style'       => 'display: inline;',
133
                ],
134
            ]
135
        );
136
137
        return $form;
138
    }
139
}
140