Passed
Push — master ( b8e901...ba029a )
by M. Mikkel
05:36
created

DefaultController::actionGetRedirectHash()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 21
rs 9.7333
1
<?php
2
3
namespace mmikkel\cpfieldinspect\controllers;
4
5
use Craft;
6
use craft\web\Controller;
7
use craft\web\Response;
8
9
use yii\web\BadRequestHttpException;
10
11
class DefaultController extends Controller
12
{
13
14
    /**
15
     * @return string
16
     * @throws \yii\base\Exception
17
     * @throws \yii\base\InvalidConfigException
18
     */
19
    public function actionGetRedirectHash(): Response
20
    {
21
        $this->requireCpRequest();
22
        $this->requirePostRequest();
23
        $url = Craft::$app->getRequest()->getRequiredBodyParam('url');
24
        $path = \parse_url($url, PHP_URL_PATH);
0 ignored issues
show
Bug introduced by
It seems like $url can also be of type array and array; however, parameter $url of parse_url() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

24
        $path = \parse_url(/** @scrutinizer ignore-type */ $url, PHP_URL_PATH);
Loading history...
25
        if (!$path) {
26
            throw new BadRequestHttpException('Invalid URL');
27
        }
28
        $segments = \array_values(\array_filter(\explode('/', $path)));
29
        $cpTrigger = Craft::$app->getConfig()->getGeneral()->cpTrigger;
30
        if ($segments[0] === $cpTrigger) {
31
            \array_shift($segments);
32
        }
33
        $redirectTo = \implode('/', $segments);
34
        $queryString = \parse_url($url, PHP_URL_QUERY);
35
        if ($queryString) {
36
            $redirectTo .= "?{$queryString}";
37
        }
38
        return $this->asJson([
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->asJson(arr...hashData($redirectTo))) returns the type yii\web\Response which includes types incompatible with the type-hinted return craft\web\Response.
Loading history...
39
            'data' => Craft::$app->getSecurity()->hashData($redirectTo),
40
        ]);
41
    }
42
43
}
44