Passed
Push — master ( 1156c5...dc7b85 )
by Alexander
02:24
created

BaseWidget::getViewParams()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace hauntd\vote\widgets;
4
5
use hauntd\vote\assets\VoteAsset;
6
use hauntd\vote\models\VoteAggregate;
7
use hauntd\vote\traits\ModuleTrait;
8
use yii\base\InvalidParamException;
9
use yii\base\Widget;
10
use yii\web\View;
11
use yii\web\JsExpression;
12
use Yii;
13
14
/**
15
 * @author Alexander Kononenko <[email protected]>
16
 * @package hauntd\vote\widgets
17
 */
18
abstract class BaseWidget extends Widget
19
{
20
    use ModuleTrait;
21
22
    /**
23
     * @var string
24
     */
25
    public $entity;
26
27
    /**
28
     * @var null|\yii\db\ActiveRecord
29
     */
30
    public $model;
31
32
    /**
33
     * @var null|integer;
34
     */
35
    public $targetId;
36
37
    /**
38
     * @var string
39
     */
40
    public $voteUrl;
41
42
    /**
43
     * @var null|\hauntd\vote\models\VoteAggregate
44
     */
45
    public $aggregateModel;
46
47
    /**
48
     * @var null|integer
49
     */
50
    public $userValue = null;
51
52
    /**
53
     * @var string
54
     */
55
    public $jsBeforeVote;
56
57
    /**
58
     * @var string
59
     */
60
    public $jsAfterVote;
61
62
    /**
63
     * @var string
64
     */
65
    public $jsCodeKey = 'vote';
66
67
    /**
68
     * @var string
69
     */
70
    public $jsErrorVote;
71
72
    /**
73
     * @var string
74
     */
75
    public $jsShowMessage;
76
77
    /**
78
     * @var string
79
     */
80
    public $jsChangeCounters;
81
82
    /**
83
     * @var array
84
     */
85
    public $options = [];
86
87
    /**
88
     * @var string
89
     */
90
    public $viewFile = 'vote';
91
92
    /**
93
     * @var array
94
     */
95
    public $viewParams = [];
96
97
    /**
98
     * @return string
99
     */
100
    public function getSelector()
101
    {
102
        $classes = str_replace(' ', '.', $this->options['class']);
103
        return ".{$classes}[data-entity=\"' + entity + '\"][data-target-id=\"' + target  + '\"]";
104
    }
105
106
    /**
107
     * @inheritdoc
108
     * @throws \yii\base\InvalidConfigException
109
     */
110
    public function init()
111
    {
112
        parent::init();
113
114
        if (!isset($this->entity) || !isset($this->model)) {
115
            throw new InvalidParamException(Yii::t('vote', 'Entity and model must be set.'));
116
        }
117
118
        $this->initDefaults();
119
120
        if ($this->getModule()->registerAsset) {
121
            $this->view->registerAssetBundle(VoteAsset::class);
122
        }
123
    }
124
125
    /**
126
     * Initialize widget with default options.
127
     *
128
     * @throws \yii\base\InvalidConfigException
129
     */
130
    public function initDefaults()
131
    {
132
        if (!isset($this->voteUrl)) {
133
            $this->voteUrl = Yii::$app->getUrlManager()->createUrl(['vote/default/vote']);
134
        }
135
        if (!isset($this->targetId)) {
136
            $this->targetId = $this->model->getPrimaryKey();
137
        }
138
        if (!isset($this->aggregateModel)) {
139
            $this->aggregateModel = VoteAggregate::findOne([
140
                'entity' => $this->getModule()->encodeEntity($this->entity),
141
                'target_id' => $this->targetId,
142
            ]);
143
        }
144
    }
145
146
    /**
147
     * Registers jQuery handler.
148
     */
149
    protected function registerJs()
150
    {
151
        $jsCode = new JsExpression("
152
            $('body').on('click', '[data-rel=\"{$this->jsCodeKey}\"] button', function(event) {
153
                var vote = $(this).closest('[data-rel=\"{$this->jsCodeKey}\"]'),
154
                    button = $(this),
155
                    action = button.attr('data-action'),
156
                    entity = vote.attr('data-entity'),
157
                    target = vote.attr('data-target-id');
158
                jQuery.ajax({
159
                    url: '$this->voteUrl', type: 'POST', dataType: 'json', cache: false,
160
                    data: { 'VoteForm[entity]': entity, 'VoteForm[targetId]': target, 'VoteForm[action]': action },
161
                    beforeSend: function(jqXHR, settings) { $this->jsBeforeVote },
162
                    success: function(data, textStatus, jqXHR) { $this->jsChangeCounters $this->jsShowMessage },
163
                    complete: function(jqXHR, textStatus) { $this->jsAfterVote },
164
                    error: function(jqXHR, textStatus, errorThrown) { $this->jsErrorVote }
165
                });
166
            });
167
        ");
168
        $this->view->registerJs($jsCode, View::POS_END, $this->jsCodeKey);
169
    }
170
171
    /**
172
     * @param array $params
173
     * @return array
174
     */
175
    protected function getViewParams(array $params)
176
    {
177
        return array_merge($this->viewParams, $params);
178
    }
179
}
180