Passed
Push — master ( aada92...32790d )
by Julito
13:34
created

PageController::createPage()   F

Complexity

Conditions 21
Paths 126

Size

Total Lines 190
Code Lines 123

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 123
nc 126
nop 3
dl 0
loc 190
rs 3.16
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\PageBundle\Controller;
5
6
use Chamilo\CoreBundle\Controller\BaseController;
7
use Chamilo\PageBundle\Entity\Page;
8
use Chamilo\PageBundle\Entity\Snapshot;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
12
use Sonata\PageBundle\Entity\PageManager;
13
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
14
use Ivory\CKEditorBundle\Form\Type\CKEditorType;
15
use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
16
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
20
/**
21
 * Class PageController.
22
 *
23
 * @package Chamilo\PageBundle\Controller
24
 */
25
class PageController extends BaseController
26
{
27
    /**
28
     * @Route("/cms/page/latest/{number}")
29
     *
30
     * @param int $number
31
     */
32
    public function getLatestPages($number)
33
    {
34
        $site = $this->container->get('sonata.page.site.selector')->retrieve();
35
36
        $criteria = ['enabled' => 1, 'site' => $site, 'decorate' => 1, 'routeName' => 'page_slug'];
37
        $order = ['createdAt' => 'desc'];
38
        // Get latest pages
39
        $pages = $this->container->get('sonata.page.manager.page')->findBy($criteria, $order, $number);
40
        $pagesToShow = [];
41
        /** @var Page $page */
42
        foreach ($pages as $page) {
43
            // Skip homepage
44
            if ($page->getUrl() === '/') {
45
                continue;
46
            }
47
            $criteria = ['pageId' => $page];
48
            /** @var Snapshot $snapshot */
49
            // Check if page has a valid snapshot
50
            $snapshot = $this->container->get('sonata.page.manager.snapshot')->findEnableSnapshot($criteria);
51
            if ($snapshot) {
52
                $pagesToShow[] = $page;
53
            }
54
        }
55
56
        return $this->render(
57
            '@ChamiloPage/latest.html.twig',
58
            ['pages' => $pagesToShow]
59
        );
60
    }
61
62
    /**
63
     * Creates a site if needed checking the host and locale.
64
     * Creates a first root page.
65
     * Creates a page if it doesn't exists.
66
     * Updates the page if page exists.
67
     *
68
     * @param string  $pageSlug
69
     * @param string  $redirect
70
     * @param Request $request
71
     *
72
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
73
     */
74
    public function createPage($pageSlug, $redirect, Request $request)
75
    {
76
        $container = $this->container;
77
        //$siteSelector = $container->get('sonata.page.site.selector');
78
79
        $siteManager = $container->get('sonata.page.manager.site');
80
        $host = $request->getHost();
81
        $criteria = [
82
            'locale' => $request->getLocale(),
83
            'host' => $host,
84
        ];
85
        $site = $siteManager->findOneBy($criteria);
86
        //$site = $siteSelector->retrieve();
87
88
        if ($request->getLocale() !== $site->getLocale()) {
89
            // Check if there's site for this locale
90
            $siteManager = $container->get('sonata.page.manager.site');
91
            $host = $request->getHost();
92
            $criteria = [
93
                'locale' => $request->getLocale(),
94
                'host' => $host,
95
            ];
96
            $site = $siteManager->findOneBy($criteria);
97
            if (!$site) {
98
                // Create new site for this host and language
99
                $site = $siteManager->create();
100
                $site->setHost($host);
101
                $site->setEnabled(true);
102
                $site->setName($host.' in language '.$request->getLocale());
103
                $site->setEnabledFrom(new \DateTime('now'));
104
                $site->setEnabledTo(new \DateTime('+20 years'));
105
                $site->setRelativePath('');
106
                $site->setIsDefault(false);
107
                $site->setLocale($request->getLocale());
108
                $site = $siteManager->save($site);
109
110
                // Create first root page
111
112
                /** @var PageManager $pageManager */
113
                $pageManager = $container->get('sonata.page.manager.page');
114
                /** @var \Sonata\PageBundle\Model\Page $page */
115
                $page = $pageManager->create();
116
                $page->setSlug('homepage');
117
                $page->setUrl('/');
118
                $page->setName('homepage');
119
                $page->setTitle('home');
120
                $page->setEnabled(true);
121
                $page->setDecorate(1);
122
                $page->setRequestMethod('GET|POST|HEAD|DELETE|PUT');
123
                $page->setTemplateCode('default');
124
                $page->setRouteName('homepage');
125
                //$page->setParent($this->getReference('page-homepage'));
126
                $page->setSite($site);
127
                $pageManager->save($page);
128
            }
129
        }
130
131
        $em = $this->getDoctrine()->getManager();
132
        $page = null;
133
134
        $form = $this->createFormBuilder()
135
            ->add('content', CKEditorType::class)
136
            ->add('save', SubmitType::class, ['label' => 'Update'])
137
            ->getForm();
138
139
        $blockToEdit = null;
140
        if ($site) {
141
            $pageManager = $this->get('sonata.page.manager.page');
142
143
            // Getting parent
144
            $criteria = ['site' => $site, 'enabled' => true, 'parent' => null];
145
            /** @var Page $page */
146
            $parent = $pageManager->findOneBy($criteria);
147
148
            // Check if a page exists for this site
149
            $criteria = ['site' => $site, 'enabled' => true, 'parent' => $parent, 'slug' => $pageSlug];
150
151
            /** @var Page $page */
152
            $page = $pageManager->findOneBy($criteria);
153
            if ($page) {
0 ignored issues
show
introduced by
$page is of type Chamilo\PageBundle\Entity\Page, thus it always evaluated to true. If $page can have other possible types, add them to src/PageBundle/Controller/PageController.php:151
Loading history...
154
                $blocks = $page->getBlocks();
155
                /** @var Block $block */
156
                foreach ($blocks as $block) {
157
                    if ($block->getName() == 'Main content') {
158
                        $code = $block->getSetting('code');
159
                        if ($code == 'content') {
160
                            $children = $block->getChildren();
161
                            /** @var Block $child */
162
                            foreach ($children as $child) {
163
                                if ($child->getType() == 'sonata.formatter.block.formatter') {
164
                                    $blockToEdit = $child;
165
                                    break 2;
166
                                }
167
                            }
168
                        }
169
                    }
170
                }
171
            } else {
172
                $pageManager = $this->get('sonata.page.manager.page');
173
174
                $page = $pageManager->create();
175
                $page->setSlug($pageSlug);
176
                $page->setUrl('/'.$pageSlug);
177
                $page->setName($pageSlug);
178
                $page->setTitle($pageSlug);
179
                $page->setEnabled(true);
180
                $page->setDecorate(1);
181
                $page->setRequestMethod('GET');
182
                $page->setTemplateCode('default');
183
                $page->setRouteName($pageSlug);
184
                $page->setParent($parent);
185
                $page->setSite($site);
186
187
                $pageManager->save($page);
188
189
                $templateManager = $this->get('sonata.page.template_manager');
190
                $template = $templateManager->get('default');
191
                $templateContainers = $template->getContainers();
192
193
                $containers = [];
194
                foreach ($templateContainers as $id => $area) {
195
                    $containers[$id] = [
196
                        'area' => $area,
197
                        'block' => false,
198
                    ];
199
                }
200
201
                // Create blocks for this page
202
                $blockInteractor = $this->get('sonata.page.block_interactor');
203
                $parentBlock = null;
204
                foreach ($containers as $id => $area) {
205
                    if (false === $area['block'] && $templateContainers[$id]['shared'] === false) {
206
                        $block = $blockInteractor->createNewContainer(
207
                            [
208
                                'page' => $page,
209
                                'name' => $templateContainers[$id]['name'],
210
                                'code' => $id,
211
                            ]
212
                        );
213
214
                        if ($id === 'content' && $templateContainers[$id]['name'] == 'Main content') {
215
                            $parentBlock = $block;
216
                        }
217
                    }
218
                }
219
220
                // Create block in main content
221
                $block = $this->get('sonata.page.manager.block');
222
                /** @var \Sonata\BlockBundle\Model\Block $myBlock */
223
                $myBlock = $block->create();
224
                $myBlock->setType('sonata.formatter.block.formatter');
225
                $myBlock->setSetting('format', 'richhtml');
226
                $myBlock->setSetting('content', '');
227
                $myBlock->setSetting('rawContent', '');
228
                $myBlock->setSetting('template', '@SonataFormatter/Block/block_formatter.html.twig');
229
                $myBlock->setParent($parentBlock);
230
                $page->addBlocks($myBlock);
231
                $pageManager->save($page);
232
            }
233
        }
234
235
        if ($blockToEdit) {
236
            $form->setData(['content' => $blockToEdit->getSetting('content')]);
237
        }
238
239
        $form->handleRequest($request);
240
241
        if ($form->isSubmitted() && $form->isValid() && $blockToEdit) {
242
            $data = $form->getData();
243
            $content = $data['content'];
244
            /** @var Block $blockToEdit */
245
            $blockToEdit->setSetting('rawContent', $content);
246
            $blockToEdit->setSetting('content', $content);
247
            $em->merge($blockToEdit);
248
            $em->flush();
249
250
            $this->addFlash('success', $this->trans('Updated'));
251
252
            if (!empty($redirect)) {
253
                return $this->redirect($redirect);
254
            }
255
256
            return $this->redirectToRoute('home');
257
        }
258
259
        return $this->render(
260
            '@ChamiloCore/Index/page_edit.html.twig',
261
            [
262
                'page' => $page,
263
                'form' => $form->createView(),
264
            ]
265
        );
266
    }
267
268
    /**
269
     * The Chamilo index home page.
270
     *
271
     * @Route("/internal_page/edit/{slug}", name="edit_page")
272
     * @Method({"GET|POST"})
273
     * @Security("has_role('ROLE_ADMIN')")
274
     *
275
     * @param string $slug
276
     *
277
     * @return Response
278
     */
279
    public function editPageAction($slug): Response
280
    {
281
        return $this->forward(
282
            'Chamilo\PageBundle\Controller\PageController:createPage',
283
            ['pageSlug' => $slug, 'redirect' => $this->generateUrl('edit_page', ['slug' => $slug ])]
284
        );
285
    }
286
287
    /**
288
     * @Route("/internal_page/{slug}")
289
     *
290
     * @param string  $slug
291
     * @param Request $request
292
     *
293
     * @return Response
294
     */
295
    public function renderPageAction(string $slug, Request $request): Response
296
    {
297
        /*$siteSelector = $this->get('sonata.page.site.selector');
298
        $site = $siteSelector->retrieve();*/
299
300
        $container = $this->container;
301
        $siteManager = $container->get('sonata.page.manager.site');
302
        $host = $request->getHost();
303
        $criteria = [
304
            'locale' => $request->getLocale(),
305
            'host' => $host,
306
        ];
307
        $site = $siteManager->findOneBy($criteria);
308
309
        $page = null;
310
        if ($site) {
311
            $pageManager = $this->get('sonata.page.manager.page');
312
            // Parents only of homepage
313
            $criteria = ['site' => $site, 'enabled' => true, 'slug' => $slug];
314
            /** @var Page $page */
315
            $page = $pageManager->findOneBy($criteria);
316
        }
317
318
        return $this->render(
319
            '@ChamiloCore/Index/page.html.twig',
320
            [
321
                'page' => $page,
322
                'slug' => $slug,
323
                'content' => 'welcome',
324
            ]
325
        );
326
    }
327
}
328