Completed
Pull Request — master (#11)
by Gilles
02:15
created

RewriteUrlAdminController::addAction()   F

Complexity

Conditions 13
Paths 370

Size

Total Lines 81
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 81
rs 3.7864
cc 13
eloc 50
nc 370
nop 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
/*************************************************************************************/
3
/*      This file is part of the RewriteUrl module for Thelia.                       */
4
/*                                                                                   */
5
/*      Copyright (c) OpenStudio                                                     */
6
/*      email : [email protected]                                                       */
7
/*      web : http://www.thelia.net                                                  */
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
8
/*                                                                                   */
9
/*      For the full copyright and license information, please view the LICENSE.txt  */
10
/*      file that was distributed with this source code.                             */
11
/*************************************************************************************/
12
13
namespace RewriteUrl\Controller\Admin;
14
15
use Propel\Runtime\ActiveQuery\Criteria;
16
use RewriteUrl\Model\RewritingUrlOverride;
17
use RewriteUrl\Event\RewriteUrlEvent;
18
use RewriteUrl\Event\RewriteUrlEvents;
19
use RewriteUrl\Form\AddUrlForm;
20
use RewriteUrl\Form\ReassignForm;
21
use RewriteUrl\Form\SetDefaultForm;
22
use Thelia\Controller\Admin\BaseAdminController;
23
use Thelia\Core\Security\AccessManager;
24
use Thelia\Core\Security\Resource\AdminResources;
25
use Thelia\Form\Exception\FormValidationException;
26
use Thelia\Model\BrandI18nQuery;
27
use Thelia\Model\CategoryI18nQuery;
28
use Thelia\Model\ConfigQuery;
29
use Thelia\Model\ContentI18nQuery;
30
use Thelia\Model\FolderI18nQuery;
31
use Thelia\Model\ProductI18nQuery;
32
use Thelia\Model\ProductQuery;
33
use Thelia\Model\RewritingUrl;
34
use Thelia\Model\RewritingUrlQuery;
35
use Thelia\Tools\URL;
36
use Thelia\Log\Tlog;
37
38
/**
39
 * Class RewriteUrlAdminController
40
 * @package RewriteUrl\Controller\Admin
41
 * @author Vincent Lopes <[email protected]>
42
 * @author Gilles Bourgeat <[email protected]>
43
 */
44
class RewriteUrlAdminController extends BaseAdminController
45
{
46
    /** @var array */
47
    private $correspondence = array(
48
        'brand'     => 'brand',
49
        'category'  => 'categories',
50
        'content'   => 'content',
51
        'folder'    => 'folders',
52
        'product'   => 'products'
53
    );
54
55
    private $unknownSource = [];
56
57
    public function __construct()
58
    {
59
        if (null !== $config = ConfigQuery::read('obsolete_rewriten_url_view', null)) {
60
            $this->unknownSource[] = $config;
61
        }
62
    }
63
64
    /**
65
     * @return mixed
66
     */
67
    public function deleteAction()
68
    {
69
        if (null !== $response = $this->checkAuth(array(AdminResources::MODULE), 'RewriteUrl', AccessManager::DELETE)) {
70
            return $response;
71
        }
72
73
        $id_url = $this->getRequest()->request->get('id_url');
74
        $rewritingUrl = RewritingUrlQuery::create()->findOneById($id_url);
75
76
        if ($rewritingUrl !== null) {
77
            $event = new RewriteUrlEvent($rewritingUrl);
78
            $this->getDispatcher()->dispatch(RewriteUrlEvents::REWRITEURL_DELETE, $event);
79
        }
80
81
        if (method_exists($this, 'generateSuccessRedirect')) {
82
            //for 2.1
83
            return $this->generateRedirectFromRoute(
84
                'admin.'.$this->correspondence[$rewritingUrl->getView()].'.update',
85
                [
86
                    $rewritingUrl->getView().'_id'=>$rewritingUrl->getViewId(),
87
                    'current_tab' => 'modules'
88
                ],
89
                [
90
                    $rewritingUrl->getView().'_id'=>$rewritingUrl->getViewId()
91
                ]
92
            );
93
        } else {
94
            //for 2.0
95
            $this->redirectToRoute(
96
                'admin.'.$this->correspondence[$rewritingUrl->getView()].'.update',
97
                [
98
                    $rewritingUrl->getView().'_id'=>$rewritingUrl->getViewId(),
99
                    'current_tab' => 'modules'
100
                ],
101
                [
102
                    $rewritingUrl->getView().'_id'=>$rewritingUrl->getViewId()
103
                ]
104
            );
105
        }
106
    }
107
108
    /**
109
     * @return mixed
110
     */
111
    public function addAction()
112
    {
113
        $message = null;
114
        $exception = null;
115
116
        if (null !== $response = $this->checkAuth(array(AdminResources::MODULE), 'RewriteUrl', AccessManager::CREATE)) {
117
            return $response;
118
        }
119
120
        $addForm = new AddUrlForm($this->getRequest());
121
122
        try {
123
            $form = $this->validateForm($addForm);
124
            $data = $form->getData($form);
125
126
            $findExist = RewritingUrlQuery::create()->findOneByUrl(($data['url']));
127
128
            if ($findExist !== null && in_array($findExist->getView(), $this->unknownSource)) {
129
                throw new \Exception("Url already exist");
130
            }
131
132
            $rewriting = $findExist !== null ? $findExist : new RewritingUrlOverride();
133
            $rewriting->setUrl($data['url'])
134
            ->setView($data['view'])
135
            ->setViewId($data['view-id'])
136
            ->setViewLocale($data['locale']);
137
138
            $rewriteDefault = RewritingUrlQuery::create()
139
                ->filterByView($rewriting->getView())
140
                ->filterByViewId($rewriting->getViewId())
141
                ->filterByViewLocale($rewriting->getViewLocale())
142
                ->findOneByRedirected(null);
143
144
            if ($data['default'] == 1) {
145
                $rewriting->setRedirected(null);
146
            } else {
147
                if ($rewriteDefault !== null) {
148
                    $rewriting->setRedirected($rewriteDefault->getId());
149
                } else {
150
                    $rewriting->setRedirected(null);
151
                }
152
            }
153
154
            $this->getDispatcher()->dispatch(
155
                RewriteUrlEvents::REWRITEURL_ADD,
156
                new RewriteUrlEvent($rewriting)
157
            );
158
159
            if (method_exists($this, 'generateSuccessRedirect')) {
160
                //for 2.1
161
                return $this->generateSuccessRedirect($addForm);
162
            } else {
163
                //for 2.0
164
                $this->redirectSuccess($addForm);
165
            }
166
167
        } catch (FormValidationException $exception) {
168
            $message = $this->createStandardFormValidationErrorMessage($exception);
169
        } catch (\Exception $exception) {
170
            $message = $exception->getMessage();
171
        }
172
173
        if ($message !== null && $exception !== null) {
174
            Tlog::getInstance()->error(sprintf("Error during order delivery process : %s. Exception was %s", $message, $exception->getMessage()));
175
176
            $addForm->setErrorMessage($message);
177
178
            $this->getParserContext()
179
                ->addForm($addForm)
180
                ->setGeneralError($message)
181
            ;
182
        }
183
184
        if (method_exists($this, 'generateSuccessRedirect')) {
185
            //for 2.1
186
            return $this->generateSuccessRedirect($addForm);
187
        } else {
188
            //for 2.0
189
            $this->redirectSuccess($addForm);
190
        }
191
    }
192
193
    /**
194
     * @return mixed
195
     */
196
    public function setDefaultAction()
197
    {
198
        $message = false;
199
200
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, 'RewriteUrl', AccessManager::UPDATE)) {
201
            return $response;
202
        }
203
204
        $setDefaultForm = new SetDefaultForm($this->getRequest());
205
206
        try {
207
            $form = $this->validateForm($setDefaultForm);
208
            $data = $form->getData($form);
209
210
            $rewritingUrl = RewritingUrlQuery::create()->findOneById($data['rewrite-id']);
211
            $newEvent = new RewriteUrlEvent($rewritingUrl);
212
            $this->getDispatcher()->dispatch(RewriteUrlEvents::REWRITEURL_SET_DEFAULT, $newEvent);
213
        } catch (FormValidationException $e) {
214
            $message = $this->createStandardFormValidationErrorMessage($e);
215
        } catch (\Exception $e) {
216
            $message = $e->getMessage();
217
        }
218
219
        if ($message !== false) {
220
            $setDefaultForm->setErrorMessage($message);
221
222
            $this->getParserContext()
223
                ->addForm($setDefaultForm)
224
                ->setGeneralError($message)
225
            ;
226
        }
227
228
        if (method_exists($this, 'generateSuccessRedirect')) {
229
            //for 2.1
230
            return $this->generateSuccessRedirect($setDefaultForm);
231
        } else {
232
            //for 2.0
233
            $this->redirectSuccess($setDefaultForm);
234
        }
235
    }
236
237
    /**
238
     * @return mixed
239
     */
240
    public function reassignAction()
241
    {
242
        $message = false;
243
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, 'RewriteUrl', AccessManager::UPDATE)) {
244
            return $response;
245
        }
246
247
        $reassignForm = new ReassignForm($this->getRequest());
248
249
        try {
250
            $form = $this->validateForm($reassignForm);
251
            $data = $form->getData($form);
252
253
            $all = $data['all'];
254
            $newRewrite = explode('::', $data['select-reassign']);
255
            $rewriteId = $data['rewrite-id'];
256
            $newView = $newRewrite[1];
257
            $newViewId = $newRewrite[0];
258
259
            if ($all === 1) {
260
                self::allReassign($rewriteId, $newView, $newViewId);
261
            } else {
262
                self::simpleReassign($rewriteId, $newView, $newViewId);
263
            }
264
265
            if (method_exists($this, 'generateSuccessRedirect')) {
266
                //for 2.1
267
                return $this->generateSuccessRedirect($reassignForm);
268
            } else {
269
                //for 2.0
270
                $this->redirectSuccess($reassignForm);
271
            }
272
        } catch (FormValidationException $e) {
273
            $message = $this->createStandardFormValidationErrorMessage($e);
274
        } catch (\Exception $e) {
275
            $message = $e->getMessage();
276
        }
277
278
        if ($message !== false) {
279
            $reassignForm->setErrorMessage($message);
280
281
            $this->getParserContext()
282
                ->addForm($reassignForm)
283
                ->setGeneralError($message)
284
            ;
285
        }
286
    }
287
288
    /**
289
     * @param int $rewriteId
290
     * @param string $newView
291
     * @param int $newViewId
292
     */
293
    protected function allReassign($rewriteId, $newView, $newViewId)
294
    {
295
        $origin = RewritingUrlQuery::create()->findOneById($rewriteId);
296
297
        $rewrites = RewritingUrlQuery::create()
298
            ->filterByView($origin->getView())
299
            ->filterByViewId($origin->getViewId())
300
            ->find();
301
302
        /** @var RewritingUrl $rewrite */
303
        foreach ($rewrites as $rewrite) {
304
            $destination = RewritingUrlQuery::create()
305
                ->filterByView($newView)
306
                ->filterByViewId($newViewId)
307
                ->filterByViewLocale($rewrite->getViewLocale())
308
                ->filterByRedirected(null)
309
                ->findOne();
310
311
            $rewrite
312
                ->setView($newView)
313
                ->setViewId($newViewId)
314
                ->setRedirected(($destination === null) ? null : $destination->getId());
315
316
            $this->getDispatcher()->dispatch(
317
                RewriteUrlEvents::REWRITEURL_UPDATE,
318
                new RewriteUrlEvent($rewrite)
319
            );
320
        }
321
    }
322
323
    /**
324
     * @param int $rewriteId
325
     * @param string $newView
326
     * @param int $newViewId
327
     */
328
    protected function simpleReassign($rewriteId, $newView, $newViewId)
329
    {
330
        $rewrite = RewritingUrlQuery::create()->findOneById($rewriteId);
331
332
        // add new default url
333
        if (null !== $newDefault = RewritingUrlQuery::create()->findOneByRedirected($rewrite->getId())) {
334
            $this->getDispatcher()->dispatch(
335
                RewriteUrlEvents::REWRITEURL_UPDATE,
336
                new RewriteUrlEvent(
337
                    $newDefault->setRedirected(null)
338
                )
339
            );
340
        }
341
342
        //Update urls who redirected to updated URL
343
        if (null !== $isRedirection = RewritingUrlQuery::create()->findByRedirected($rewrite->getId())) {
344
            /** @var \Thelia\Model\RewritingUrl $redirected */
345
            foreach ($isRedirection as $redirected) {
346
                $this->getDispatcher()->dispatch(
347
                    RewriteUrlEvents::REWRITEURL_UPDATE,
348
                    new RewriteUrlEvent(
349
                        $redirected->setRedirected(
350
                            ($newDefault !== null) ? $newDefault->getId() : $rewrite->getRedirected()
351
                        )
352
                    )
353
                );
354
            }
355
        }
356
357
        $rewrite->setView($newView)
358
            ->setViewId($newViewId);
359
360
        //Check if default url already exist for the view with the locale
361
        $rewriteDefault = RewritingUrlQuery::create()
362
            ->filterByView($newView)
363
            ->filterByViewId($newViewId)
364
            ->filterByViewLocale($rewrite->getViewLocale())
365
            ->findOneByRedirected(null);
366
367
        if ($rewriteDefault !== null) {
368
            $rewrite->setRedirected($rewriteDefault->getId());
369
        } else {
370
            $rewrite->setRedirected(null);
371
        }
372
373
        $event = new RewriteUrlEvent($rewrite);
374
        $this->getDispatcher()->dispatch(RewriteUrlEvents::REWRITEURL_UPDATE, $event);
375
    }
376
377
    /**
378
     * @return mixed|\Thelia\Core\HttpFoundation\Response
379
     */
380
    public function existAction()
381
    {
382
        if (null !== $response = $this->checkAuth(array(AdminResources::MODULE), 'RewriteUrl', AccessManager::VIEW)) {
383
            return $response;
384
        }
385
386
        $search = $this->getRequest()->query->get('q');
387
388
389
        $rewritingUrl = RewritingUrlQuery::create()
390
            ->filterByView($this->unknownSource, Criteria::NOT_IN)
391
            ->findOneByUrl($search);
392
393
        if ($rewritingUrl !== null) {
394
            $route = $this->getRoute(
395
                "admin.".$this->correspondence[$rewritingUrl->getView()].".update",
396
                [$rewritingUrl->getView().'_id'=>$rewritingUrl->getViewId()]
397
            );
398
            $url = URL::getInstance()->absoluteUrl(
399
                $route,
400
                [$rewritingUrl->getView().'_id'=>$rewritingUrl->getViewId()]
401
            );
402
403
            $rewritingUrlArray = ["reassignUrl" => $url];
404
405
            return $this->jsonResponse(json_encode($rewritingUrlArray));
406
        } else {
407
            return $this->jsonResponse(json_encode(false));
408
        }
409
    }
410
411
    /**
412
     * @return mixed|\Thelia\Core\HttpFoundation\Response
413
     * @throws \Propel\Runtime\Exception\PropelException
414
     */
415
    public function searchAction()
416
    {
417
        if (null !== $response = $this->checkAuth(array(AdminResources::MODULE), 'RewriteUrl', AccessManager::VIEW)) {
418
            return $response;
419
        }
420
421
        $search = '%'.$this->getRequest()->query->get('q').'%';
422
423
        $resultArray = array();
424
425
        $categoriesI18n = CategoryI18nQuery::create()->filterByTitle($search)->limit(10);
426
        $contentsI18n = ContentI18nQuery::create()->filterByTitle($search)->limit(10);
427
        $foldersI18n = FolderI18nQuery::create()->filterByTitle($search)->limit(10);
428
        $brandsI18n = BrandI18nQuery::create()->filterByTitle($search)->limit(10);
429
430
        $productsI18n = ProductI18nQuery::create()->filterByTitle($search)->limit(10);
431
        $productsRef = ProductQuery::create()->filterByRef($search)->limit(10);
432
433
        /** @var \Thelia\Model\CategoryI18n $categoryI18n */
434
        foreach ($categoriesI18n as $categoryI18n) {
435
            $category = $categoryI18n->getCategory();
436
            $resultArray['category'][$category->getId()] = $categoryI18n->getTitle();
437
        }
438
439
        /** @var \Thelia\Model\ContentI18n $contentI18n */
440
        foreach ($contentsI18n as $contentI18n) {
441
            $content = $contentI18n->getContent();
442
            $resultArray['content'][$content->getId()] = $contentI18n->getTitle();
443
        }
444
445
        /** @var \Thelia\Model\FolderI18n $folderI18n */
446
        foreach ($foldersI18n as $folderI18n) {
447
            $folder = $folderI18n->getFolder();
448
            $resultArray['folder'][$folder->getId()] = $folderI18n->getTitle();
449
        }
450
451
        /** @var \Thelia\Model\BrandI18n $brandI18n */
452
        foreach ($brandsI18n as $brandI18n) {
453
            $brand = $brandI18n->getBrand();
454
            $resultArray['brand'][$brand->getId()] = $brandI18n->getTitle();
455
        }
456
457
        /** @var \Thelia\Model\ProductI18n $productI18n */
458
        foreach ($productsI18n as $productI18n) {
459
            $product = $productI18n->getProduct();
460
            $resultArray['product'][$product->getId()] = $productI18n->getTitle();
461
        }
462
463
        /** @var \Thelia\Model\Product $product */
464
        foreach ($productsRef as $product) {
465
            $productI18n = ProductI18nQuery::create()->filterByProduct($product)->findOne();
466
            $resultArray['product'][$product->getId()] = $productI18n->getTitle();
467
        }
468
469
        return $this->jsonResponse(json_encode($resultArray));
470
    }
471
}
472