Completed
Push — master ( a61a17...33cc83 )
by Klochok
03:51
created

BackButton::getLabel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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