DefaultController::actionGetRedirectHash()   B
last analyzed

Complexity

Conditions 7
Paths 9

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 17
c 2
b 0
f 0
nc 9
nop 0
dl 0
loc 23
rs 8.8333
1
<?php
2
3
namespace mmikkel\cpfieldinspect\controllers;
4
5
use Craft;
6
use craft\web\Controller;
7
8
use mmikkel\cpfieldinspect\helpers\CpFieldInspectHelper;
9
10
use yii\web\BadRequestHttpException;
11
12
class DefaultController extends Controller
13
{
14
15
    /**
16
     * @return string
17
     * @throws BadRequestHttpException
18
     * @throws \yii\base\Exception
19
     * @throws \yii\base\InvalidConfigException
20
     */
21
    public function actionGetRedirectHash(): string
22
    {
23
        $this->requireCpRequest();
24
        $this->requirePostRequest();
25
        $url = $this->request->getRequiredBodyParam('url');
26
        if (!$url || !is_string($url) || !$path = parse_url($url, PHP_URL_PATH)) {
27
            throw new BadRequestHttpException('Bad URL parameter');
28
        }
29
        $segments = array_values(array_filter(explode('/', $path)));
30
        $cpTrigger = Craft::$app->getConfig()->getGeneral()->cpTrigger;
31
        if ($segments[0] === $cpTrigger) {
32
            array_shift($segments);
33
        }
34
        $redirectTo = implode('/', $segments);
35
        $queryString = parse_url($url, PHP_URL_QUERY);
36
        if ($queryString) {
37
            $redirectTo .= "?{$queryString}";
38
        }
39
        $hashbang = parse_url($url, PHP_URL_FRAGMENT);
40
        if ($hashbang) {
41
            $redirectTo .= "#{$hashbang}";
42
        }
43
        return CpFieldInspectHelper::getRedirectUrl($redirectTo);
44
    }
45
46
}
47