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

widgets/Vote.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\web\View;
6
use yii\web\JsExpression;
7
use Yii;
8
9
/**
10
 * @author Alexander Kononenko <[email protected]>
11
 * @package hauntd\vote\widgets
12
 */
13
class Vote extends BaseWidget
14
{
15
    /**
16
     * @var string
17
     */
18
    public $jsCodeKey = 'vote';
19
20
    /**
21
     * @return array
22
     */
23
    public function getDefaultOptions()
24
    {
25
        return [
26
            'class' => 'vote',
27
        ];
28
    }
29
30
    /**
31
     * @inherit
32
     */
33
    public function init()
34
    {
35
        parent::init();
36
        $this->options = array_merge($this->getDefaultOptions(), $this->options);
37
        $this->initJsEvents();
38
        $this->registerJs();
39
    }
40
41
    /**
42
     * @return string
43
     * @throws \yii\base\InvalidConfigException
44
     */
45
    public function run()
46
    {
47
        return $this->render($this->viewFile, [
48
            'jsCodeKey' => $this->jsCodeKey,
49
            'entity' => $this->entity,
50
            'model' => $this->model,
51
            'targetId' => $this->targetId,
52
            'userValue' => $this->userValue,
53
            'positive' => isset($this->aggregateModel->positive) ? $this->aggregateModel->positive : 0,
54
            'negative' => isset($this->aggregateModel->negative) ? $this->aggregateModel->negative : 0,
55
            'rating' => isset($this->aggregateModel->rating) ? $this->aggregateModel->rating : 0.0,
56
            'options' => $this->options,
57
        ]);
58
    }
59
60
    /**
61
     * Initialize with default events.
62
     */
63 View Code Duplication
    public function initJsEvents()
1 ignored issue
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...
64
    {
65
        parent::initJsEvents();
66
        $selector = $this->getSelector($this->options['class']);
67
        if (!isset($this->jsChangeCounters)) {
68
            $this->jsChangeCounters = "
69
                if (typeof(data.success) !== 'undefined') {
70
                    $('$selector .vote-count span').text(data.aggregate.positive - data.aggregate.negative);
71
                    vote.find('button').removeClass('vote-active');
72
                    button.addClass('vote-active');
73
                }
74
            ";
75
        }
76
        if (!isset($this->jsBeforeVote)) {
77
            $this->jsBeforeVote = "
78
                $('$selector .vote-btn').prop('disabled', 'disabled').addClass('vote-loading');
79
                $('$selector .vote-count')
80
                    .addClass('vote-loading')
81
                    .append('<div class=\"vote-loader\"><span></span><span></span><span></span></div>');
82
            ";
83
        }
84
        if (!isset($this->jsAfterVote)) {
85
            $this->jsAfterVote = "
86
                $('$selector .vote-btn').prop('disabled', false).removeClass('vote-loading');
87
                $('$selector .vote-count').removeClass('vote-loading').find('.vote-loader').remove();
88
            ";
89
        }
90
    }
91
92
    /**
93
     * Registers jQuery handler.
94
     */
95 View Code Duplication
    protected function registerJs()
96
    {
97
        $js = new JsExpression("
98
            $('body').on('click', '[data-rel=\"{$this->jsCodeKey}\"] button', function(event) {
99
                var vote = $(this).closest('[data-rel=\"{$this->jsCodeKey}\"]'),
100
                    button = $(this),
101
                    action = button.attr('data-action'),
102
                    entity = vote.attr('data-entity'),
103
                    target = vote.attr('data-target-id');
104
                jQuery.ajax({
105
                    url: '$this->voteUrl', type: 'POST', dataType: 'json', cache: false,
106
                    data: { 'VoteForm[entity]': entity, 'VoteForm[targetId]': target, 'VoteForm[action]': action },
107
                    beforeSend: function(jqXHR, settings) { $this->jsBeforeVote },
108
                    success: function(data, textStatus, jqXHR) { $this->jsChangeCounters $this->jsShowMessage },
109
                    complete: function(jqXHR, textStatus) { $this->jsAfterVote },
110
                    error: function(jqXHR, textStatus, errorThrown) { $this->jsErrorVote }
111
                });
112
            });
113
        ");
114
        $this->view->registerJs($js, View::POS_END, $this->jsCodeKey);
115
    }
116
}
117