RewriteUrlAdminController::searchAction()   B
last analyzed

Complexity

Conditions 8
Paths 65

Size

Total Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 56
rs 7.7155
cc 8
nc 65
nop 0

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