Passed
Push — master ( bcfa32...be1ad5 )
by Alexander
02:28
created

widgets/VoteToggle.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace hauntd\vote\widgets;
4
5
use yii\bootstrap\Html;
6
use yii\web\View;
7
use yii\web\JsExpression;
8
use Yii;
9
10
/**
11
 * @author Alexander Kononenko <[email protected]>
12
 * @package hauntd\vote\widgets
13
 */
14
class VoteToggle extends BaseWidget
15
{
16
    /**
17
     * @var string
18
     */
19
    public $jsCodeKey = 'vote-toggle';
20
21
    /**
22
     * @var string
23
     */
24
    public $viewFile = 'toggle';
25
26
    /**
27
     * @var array
28
     */
29
    public $buttonOptions = [];
30
31
    /**
32
     * @return array
33
     */
34
    public function getDefaultOptions()
35
    {
36
        return [
37
            'class' => 'vote-toggle',
38
        ];
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public function getDefaultButtonOptions()
45
    {
46
        return [
47
            'class' => 'vote-btn btn btn-default',
48
            'icon' => Html::icon('glyphicon glyphicon-arrow-up'),
49
            'label' => Yii::t('vote', 'Vote up'),
50
        ];
51
    }
52
53
    public function init()
54
    {
55
        parent::init();
56
        $this->options = array_merge($this->getDefaultOptions(), $this->options);
57
        $this->buttonOptions = array_merge($this->getDefaultButtonOptions(), $this->buttonOptions);
58
        $this->initJsEvents();
59
        $this->registerJs();
60
    }
61
62
    /**
63
     * @return string
64
     * @throws \yii\base\InvalidConfigException
65
     */
66
    public function run()
67
    {
68
        return $this->render($this->viewFile, [
69
            'jsCodeKey' => $this->jsCodeKey,
70
            'entity' => $this->entity,
71
            'model' => $this->model,
72
            'targetId' => $this->targetId,
73
            'userValue' => $this->userValue,
74
            'count' => isset($this->aggregateModel->positive) ? $this->aggregateModel->positive : 0,
75
            'options' => $this->options,
76
            'buttonOptions' => $this->buttonOptions,
77
        ]);
78
    }
79
80
    /**
81
     * Initialize with default events.
82
     */
83
    public function initJsEvents()
84
    {
85
        $selector = $this->getSelector($this->options['class']);
86
        if (!isset($this->jsChangeCounters)) {
87
            $this->jsChangeCounters = "
88
                if (typeof(data.success) !== 'undefined') {
89
                    $('$selector .vote-count').text(data.aggregate.positive);
90
                    if (data.toggleValue) {
91
                        button.addClass('vote-active');
92
                    } else {
93
                        button.removeClass('vote-active');
94
                    }
95
                }
96
            ";
97
        }
98
        if (!isset($this->jsBeforeVote)) {
99
            $this->jsBeforeVote = "
100
                $('$selector .vote-btn').prop('disabled', 'disabled').addClass('vote-loading');
101
                $('$selector .vote-btn').append('<div class=\"vote-loader\"><span></span><span></span><span></span></div>');
102
            ";
103
        }
104
        if (!isset($this->jsAfterVote)) {
105
            $this->jsAfterVote = "
106
                $('$selector .vote-btn').prop('disabled', false).removeClass('vote-loading');
107
                $('$selector .vote-btn .vote-loader').remove();
108
            ";
109
        }
110
    }
111
112
    /**
113
     * Registers jQuery handler.
114
     */
115 View Code Duplication
    protected function registerJs()
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
    {
117
        $js = new JsExpression("
118
            $('body').on('click', '[data-rel=\"{$this->jsCodeKey}\"] button', function(event) {
119
                var vote = $(this).closest('[data-rel=\"{$this->jsCodeKey}\"]'),
120
                    button = $(this),
121
                    entity = vote.attr('data-entity'),
122
                    target = vote.attr('data-target-id');
123
                jQuery.ajax({
124
                    url: '$this->voteUrl', type: 'POST', dataType: 'json', cache: false,
125
                    data: { 'VoteForm[entity]': entity, 'VoteForm[targetId]': target, 'VoteForm[action]': 'toggle' },
126
                    beforeSend: function(jqXHR, settings) { $this->jsBeforeVote },
127
                    success: function(data, textStatus, jqXHR) { $this->jsChangeCounters $this->jsShowMessage },
128
                    complete: function(jqXHR, textStatus) { $this->jsAfterVote },
129
                    error: function(jqXHR, textStatus, errorThrown) { $this->jsErrorVote }
130
                });
131
            });
132
        ");
133
        $this->view->registerJs($js, View::POS_END, $this->jsCodeKey);
134
    }
135
}
136