BackButton::getCurrentUrl()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * HiPanel core package
4
 *
5
 * @link      https://hipanel.com/
6
 * @package   hipanel-core
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2014-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\widgets;
12
13
use Yii;
14
use yii\base\Widget;
15
use yii\helpers\Html;
16
17
class BackButton extends Widget
18
{
19
    /**
20
     * Html options.
21
     * @var array
22
     */
23
    public $options = [
24
        'class' => 'btn btn-default',
25
    ];
26
27
    /**
28
     * @var string
29
     */
30
    public $selectorClass = 'btn-cancel';
31
32
    /**
33
     * @var string
34
     */
35
    public $label;
36
37
    public function run()
38
    {
39
        $curr = $this->getCurrentUrl();
40
        $ref = $this->getReferrerUrl();
41
        if ($curr === $ref) {
42
            Yii::$app->session[$this->getIdentifier()] = Yii::$app->session[$this->getIdentifier()] + 1;
43
        } else {
44
            Yii::$app->session[$this->getIdentifier()] = 1;
45
        }
46
        $this->registerClientScript();
47
        Html::addCssClass($this->options, $this->selectorClass);
48
49
        return Html::button($this->getLabel(), $this->options);
50
    }
51
52
    /**
53
     * @return string
54
     */
55
    public function getLabel()
56
    {
57
        return $this->label !== null ? $this->label : Yii::t('hipanel', 'Cancel');
58
    }
59
60
    /**
61
     * Apply js to view.
62
     */
63
    protected function registerClientScript()
64
    {
65
        $this->getView()->registerJs(";$('button.{$this->selectorClass}').on('click', function () {window.history.go({$this->getBackStepsCount()});});");
66
    }
67
68
    /**
69
     * @return int
70
     */
71
    protected function getBackStepsCount()
72
    {
73
        return -Yii::$app->session[$this->getIdentifier()];
74
    }
75
76
    /**
77
     * @return string
78
     */
79
    protected function getIdentifier()
80
    {
81
        return self::class;
82
    }
83
84
    /**
85
     * @return string
86
     */
87
    protected function getCurrentUrl()
88
    {
89
        return $this->removeParams(Yii::$app->request->absoluteUrl);
90
    }
91
92
    /**
93
     * @return string
94
     */
95
    protected function getReferrerUrl()
96
    {
97
        return $this->removeParams(Yii::$app->request->referrer);
98
    }
99
100
    /**
101
     * Remove params from url.
102
     * @return string
103
     */
104
    protected function removeParams($url)
105
    {
106
        return explode('?', $url, 2)[0];
107
    }
108
}
109