FavoriteWidget.php 7.37 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
2
3
4
5
6
7
<?php

/**
 * Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
 * OPEN 2.0
 *
 *
waltermazza's avatar
waltermazza committed
8
 * @package    arter\amos\favorites\widgets
Marcello Pivanti's avatar
Marcello Pivanti committed
9
10
11
12
 * @category   CategoryName
 * @author     Elite Division S.r.l.
 */

waltermazza's avatar
waltermazza committed
13
namespace arter\amos\favorites\widgets;
Marcello Pivanti's avatar
Marcello Pivanti committed
14

waltermazza's avatar
waltermazza committed
15
16
17
18
19
use arter\amos\core\helpers\Html;
use arter\amos\core\icons\AmosIcons;
use arter\amos\favorites\AmosFavorites;
use arter\amos\favorites\exceptions\FavoritesException;
use arter\amos\notificationmanager\AmosNotify;
Marcello Pivanti's avatar
Marcello Pivanti committed
20
21
22
23
24
25
26
27
use yii\base\Widget;
use yii\web\View;

/**
 * Class FavoriteWidget
 *
 * Widget to show the favorite icon.
 *
waltermazza's avatar
waltermazza committed
28
 * @package arter\amos\favorites\widgets
Marcello Pivanti's avatar
Marcello Pivanti committed
29
30
31
32
33
34
 */
class FavoriteWidget extends Widget
{
    public $layout = '{beginContainerSection}{favoriteButton}{endContainerSection}';
    
    /**
waltermazza's avatar
waltermazza committed
35
     * @var \arter\amos\core\record\Record $model
Marcello Pivanti's avatar
Marcello Pivanti committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
     */
    public $model;
    
    /**
     * @var array $containerOptions Default to ['id' => 'favorite-container-MODEL_ID']
     */
    public $containerOptions = [];
    
    /**
     * @var bool $isAlreadyFavorite
     */
    private $isAlreadyFavorite = false;
    
    /**
     * @throws FavoritesException
     */
    public function init()
    {
        parent::init();
        
        if (is_null($this->model)) {
            throw new FavoritesException(AmosFavorites::t('amosfavorites', 'FavoriteWidget: model required'));
        }
    }
    
    /**
     * @return string
     */
    public function getLayout()
    {
        return $this->layout;
    }
    
    /**
     * @inheritdoc
     */
    public function run()
    {
        if ($this->model->isNewRecord) {
            return '';
        }
    
        /** @var AmosFavorites $favorites */
        $favorites = \Yii::$app->getModule('favorites');
        if (!isset($favorites->modelsEnabled) || !in_array($this->model->className(), $favorites->modelsEnabled)) {
            return false;
        }
        
        $this->initDefaultOptions();
        
        $content = preg_replace_callback("/{\\w+}/", function ($matches) {
            $content = $this->renderSection($matches[0]);
            
            return $content === false ? $matches[0] : $content;
        }, $this->layout);
        
        $this->registerWidgetJs();
        
        return $content;
    }
    
    /**
     * Set default options values.
     */
    private function initDefaultOptions()
    {
        $this->containerOptions['id'] = 'favorite-container-' . $this->model->id;
        $this->containerOptions['class'] = 'pull-left favorites-container';
    }
    
    /**
     * Return the container id.
     * @return string
     */
    public function getContainerId()
    {
        return $this->containerOptions['id'];
    }
    
    /**
     * Renders a section of the specified name.
     * If the named section is not supported, false will be returned.
     * @param string $name the section name, e.g., `{summary}`, `{items}`.
     * @return string|boolean the rendering result of the section, or false if the named section is not supported.
     */
    public function renderSection($name)
    {
        switch ($name) {
            case '{beginContainerSection}':
                return $this->renderBeginContainerSection();
            case '{favoriteButton}':
                return $this->favoriteButton();
            case '{endContainerSection}':
                return $this->renderEndContainerSection();
            default:
                return false;
        }
    }
    
    /**
     * This method render the beginning part of the container.
     * @return string
     */
    protected function renderBeginContainerSection()
    {
        $sectionContent = Html::beginTag('div', $this->containerOptions);
        return $sectionContent;
    }
    
    /**
     * Method that render the section of the comment container.
     * @return string
     */
    public function favoriteButton()
    {
        /** @var AmosNotify $notify */
        $notify = \Yii::$app->getModule('notify');
        $this->isAlreadyFavorite = $notify->isFavorite($this->model, \Yii::$app->user->id);
        $button = Html::a(AmosIcons::show('star', ['class' => 'am-2', 'id' => $this->favoriteIconId()]), null, [
            'title' => self::favoriteBtnTitle($this->isAlreadyFavorite),
            'id' => $this->favoriteBtnId()
        ]);
        return $button;
    }
    
    /**
     * This method render the end part of the container.
     * @return string
     */
    protected function renderEndContainerSection()
    {
        $sectionContent = Html::endTag('div');
        return $sectionContent;
    }
    
    /**
     * Return the favorite button title.
     * @return string
     */
    public static function favoriteBtnTitle($isAlreadyFavorite = false)
    {
        return ($isAlreadyFavorite ?
            AmosFavorites::t('amosfavorites', 'Remove favorite') :
            AmosFavorites::t('amosfavorites', 'Add to favorites')
        );
    }
    
    /**
     * Return the favorite button ID.
     * @return string
     */
    private function favoriteBtnId()
    {
        return 'favorite-btn-id-' . $this->model->id;
    }
    
    /**
     * Return the favorite icon ID.
     * @return string
     */
    private function favoriteIconId()
    {
        return 'favorite-icon-id-' . $this->model->id;
    }
    
    /**
     * This method registers all widget javascript.
     */
    private function registerWidgetJs()
    {
        $alreadyFavorite = ($this->isAlreadyFavorite ? 1 : 0);
        $js = "
        var disableFavoriteClick" . $this->model->id . " = 0;
        $('#" . $this->favoriteBtnId() . "').on('click', function(event) {
            if (disableFavoriteClick" . $this->model->id . " == 1) {
                return false;
            } else {
                disableFavoriteClick" . $this->model->id . " = 1;
            }
            event.preventDefault();
            var params = {};
            params.className = '" . addslashes($this->model->className()) . "';
            params.id = " . $this->model->id . ";
            $.ajax({
                url: '/favorites/favorite/favorite',
                data: params,
                type: 'post',
                dataType: 'json',
                complete: function (jjqXHR, textStatus) {
                    disableFavoriteClick" . $this->model->id . " = 0;
                },
                success: function (response) {
                    if (response.success == 1) {
                        if (response.nowFavorite == 1) {
                            $('#" . $this->favoriteIconId() . "').addClass('favorite');
                        } else if (response.nowNotFavorite == 1) {
                            $('#" . $this->favoriteIconId() . "').removeClass('favorite');
                        }
                        $('#" . $this->favoriteBtnId() . "').prop('title', response.favoriteBtnTitle);
                    }
                    alert(response.msg);
                },
                error: function (response) {
                    alert('Favorite AJAX error');
                }
            });
            return false;
        });
        
        $('#" . $this->favoriteBtnId() . "').prop('title', '" . self::favoriteBtnTitle($this->isAlreadyFavorite) . "');
        if (" . $alreadyFavorite . " == 1) {
            $('#" . $this->favoriteIconId() . "').addClass('favorite');
        } else {
            $('#" . $this->favoriteIconId() . "').removeClass('favorite');
        }
        ";
        \Yii::$app->view->registerJs($js, View::POS_READY);
    }
}