Completed
Push — master ( 579211...343140 )
by Craig
06:19
created

ThemeController::previewAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Zikula package.
5
 *
6
 * Copyright Zikula Foundation - http://zikula.org/
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zikula\ThemeModule\Controller;
13
14
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
15
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
17
use Symfony\Component\Filesystem\Exception\IOException;
18
use Symfony\Component\Filesystem\Filesystem;
19
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
20
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
21
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
22
use Symfony\Component\HttpFoundation\RedirectResponse;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
26
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
27
use Zikula\Core\Controller\AbstractController;
28
use Zikula\Core\Event\GenericEvent;
29
use Zikula\ExtensionsModule\ExtensionEvents;
30
use Zikula\ThemeModule\Engine\Annotation\Theme;
31
use Zikula\ExtensionsModule\Api\VariableApi;
32
use Zikula\ThemeModule\Entity\Repository\ThemeEntityRepository;
33
34
/**
35
 * Class ThemeController
36
 * @Route("/admin")
37
 */
38
class ThemeController extends AbstractController
39
{
40
    /**
41
     * @Route("/view")
42
     * @Method("GET")
43
     * @Theme("admin")
44
     * @Template
45
     *
46
     * view all themes
47
     *
48
     * @param Request $request
49
     *
50
     * @return array
51
     *
52
     * @throws AccessDeniedException Thrown if the user doesn't have edit permissions to the module
53
     */
54
    public function viewAction(Request $request)
55
    {
56
        if (!$this->hasPermission('ZikulaThemeModule::', '::', ACCESS_EDIT)) {
57
            throw new AccessDeniedException();
58
        }
59
        $vetoEvent = new GenericEvent();
60
        $this->get('event_dispatcher')->dispatch(ExtensionEvents::REGENERATE_VETO, $vetoEvent);
61
        if (!$vetoEvent->isPropagationStopped()) {
62
            $this->get('zikula_theme_module.helper.bundle_sync_helper')->regenerate();
63
        }
64
65
        $themes = $this->get('zikula_theme_module.theme_entity.repository')->get(ThemeEntityRepository::FILTER_ALL, ThemeEntityRepository::STATE_ALL);
66
67
        return [
68
            'themes' => $themes,
69
            'currenttheme' => $this->get('zikula_extensions_module.api.variable')->getSystemVar('Default_Theme')
70
        ];
71
    }
72
73
    /**
74
     * @Route("/preview/{themeName}")
75
     * @param $themeName
76
     * @return Response
77
     */
78
    public function previewAction($themeName)
79
    {
80
        $this->get('zikula_core.common.theme_engine')->setActiveTheme($themeName);
81
82
        return $this->forward('zikula_core.controller.main_controller:homeAction');
83
    }
84
85
    /**
86
     * @Route("/activate/{themeName}")
87
     */
88
    public function activateAction($themeName)
89
    {
90
        $theme = $this->get('zikula_theme_module.theme_entity.repository')->findOneBy(['name' => $themeName]);
91
        $theme->setState(ThemeEntityRepository::STATE_ACTIVE);
92
        $this->getDoctrine()->getManager()->flush();
93
        $this->get('zikula.cache_clearer')->clear('symfony.config');
94
95
        return $this->redirectToRoute('zikulathememodule_theme_view');
96
    }
97
98
    /**
99
     * @Route("/makedefault/{themeName}")
100
     * @Theme("admin")
101
     * @Template
102
     *
103
     * set theme as default for site
104
     *
105
     * @param Request $request
106
     * @param string $themeName
107
     *
108
     * @return array|RedirectResponse
109
     *
110
     * @throws AccessDeniedException Thrown if the user doesn't have admin permissions over the module
111
     */
112
    public function setAsDefaultAction(Request $request, $themeName)
113
    {
114
        if (!$this->hasPermission('ZikulaThemeModule::', '::', ACCESS_ADMIN)) {
115
            throw new AccessDeniedException();
116
        }
117
118
        $form = $this->createFormBuilder(['themeName' => $themeName])
119
            ->add('themeName', HiddenType::class)
120
            ->add('accept', SubmitType::class, [
121
                'label' => $this->__('Accept'),
122
                'icon' => 'fa-check',
123
                'attr' => [
124
                    'class' => 'btn btn-success'
125
                ]
126
            ])
127
            ->add('cancel', SubmitType::class, [
128
                'label' => $this->__('Cancel'),
129
                'icon' => 'fa-times',
130
                'attr' => [
131
                    'class' => 'btn btn-default'
132
                ]
133
            ])
134
            ->getForm();
135
136
        if ($form->handleRequest($request)->isValid()) {
137
            if ($form->get('accept')->isClicked()) {
138
                $data = $form->getData();
139
                // Set the default theme
140
                $this->get('zikula_extensions_module.api.variable')->set(VariableApi::CONFIG, 'Default_Theme', $data['themeName']);
141
                $this->get('zikula.cache_clearer')->clear('twig');
142
                $this->get('zikula.cache_clearer')->clear('symfony.config');
143
                $this->addFlash('status', $this->__('Done! Changed default theme.'));
144
            }
145
            if ($form->get('cancel')->isClicked()) {
146
                $this->addFlash('status', $this->__('Operation cancelled.'));
147
            }
148
149
            return $this->redirectToRoute('zikulathememodule_theme_view');
150
        }
151
152
        return [
153
            'themeName' => $themeName,
154
            'form' => $form->createView()
155
        ];
156
    }
157
158
    /**
159
     * @Route("/delete/{themeName}")
160
     * @Theme("admin")
161
     * @Template
162
     *
163
     * delete a theme
164
     *
165
     * @param Request $request
166
     * @param string $themeName
167
     *
168
     * @return array|RedirectResponse
169
     *
170
     * @throws NotFoundHttpException Thrown if themename isn't provided or doesn't exist
171
     * @throws AccessDeniedException Thrown if the user doesn't have delete permissions over the module
172
     */
173
    public function deleteAction(Request $request, $themeName)
174
    {
175
        if (!$this->hasPermission('ZikulaThemeModule::', "$themeName::", ACCESS_DELETE)) {
176
            throw new AccessDeniedException();
177
        }
178
179
        $form = $this->createFormBuilder(['themeName' => $themeName, 'deletefiles' => false])
180
            ->add('themeName', HiddenType::class)
181
            ->add('deletefiles', CheckboxType::class, [
182
                'label' => $this->__('Also delete theme files, if possible'),
183
                'required' => false,
184
            ])
185
            ->add('delete', SubmitType::class, [
186
                'label' => $this->__('Delete'),
187
                'icon' => 'fa-trash-o',
188
                'attr' => [
189
                    'class' => 'btn btn-danger'
190
                ]
191
            ])
192
            ->add('cancel', SubmitType::class, [
193
                'label' => $this->__('Cancel'),
194
                'icon' => 'fa-times',
195
                'attr' => [
196
                    'class' => 'btn btn-default'
197
                ]
198
            ])
199
            ->getForm();
200
201
        if ($form->handleRequest($request)->isValid()) {
202
            if ($form->get('delete')->isClicked()) {
203
                $data = $form->getData();
204
                $themeEntity = $this->getDoctrine()->getRepository('ZikulaThemeModule:ThemeEntity')->findOneBy(['name' => $themeName]);
205
                if (empty($themeEntity)) {
206
                    throw new NotFoundHttpException($this->__('Sorry! No such theme found.'), null, 404);
207
                }
208
                if ($data['deletefiles']) {
209
                    $fs = new Filesystem();
210
                    $path = realpath($this->get('kernel')->getRootDir() . '/../themes/' . $themeEntity->getDirectory());
211
                    try {
212
                        // attempt to delete files
213
                        $fs->remove($path);
214
                        $this->addFlash('status', $this->__('Files removed as requested.'));
215
                    } catch (IOException $e) {
1 ignored issue
show
Bug introduced by
The class Symfony\Component\Filesystem\Exception\IOException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
216
                        $this->addFlash('danger', $this->__('Could not remove files as requested.') . ' (' . $e->getMessage() . ') ' . $this->__('The files must be removed manually.'));
217
                    }
218
                }
219
                // remove theme
220
                $this->getDoctrine()->getManager()->remove($themeEntity);
221
                // remove any theme vars
222
                $vars = $this->get('zikula_extensions_module.api.variable')->getAll($themeName);
223
                foreach ($vars as $var) {
224
                    $this->getDoctrine()->getManager()->remove($var);
225
                }
226
                $this->getDoctrine()->getManager()->flush();
227
                // clear all caches
228
                $this->get('zikula.cache_clearer')->clear('twig');
229
                $this->get('zikula.cache_clearer')->clear('symfony.config');
230
                $this->addFlash('status', $data['deletefiles'] ? $this->__('Done! Deleted the theme.') : $this->__('Done! Deactivated the theme.'));
231
            }
232
            if ($form->get('cancel')->isClicked()) {
233
                $this->addFlash('status', $this->__('Operation cancelled.'));
234
            }
235
236
            return $this->redirectToRoute('zikulathememodule_theme_view');
237
        }
238
239
        return [
240
            'themeName' => $themeName,
241
            'form' => $form->createView()
242
        ];
243
    }
244
245
    /**
246
     * @Route("/credits/{themeName}")
247
     * @Method("GET")
248
     * @Theme("admin")
249
     * @Template
250
     *
251
     * display the theme credits
252
     *
253
     * @param string $themeName name of the theme
254
     *
255
     * @return array
256
     *
257
     * @throws AccessDeniedException Thrown if the user doesn't have edit permissions over the theme
258
     */
259
    public function creditsAction($themeName)
260
    {
261
        if (!$this->hasPermission('ZikulaThemeModule::', "$themeName::credits", ACCESS_EDIT)) {
262
            throw new AccessDeniedException();
263
        }
264
        $themeInfo = $this->getDoctrine()->getRepository('ZikulaThemeModule:ThemeEntity')->findOneBy(['name' => $themeName]);
265
266
        return ['themeinfo' => $themeInfo->toArray()];
267
    }
268
}
269