FavoriteController.php 6.11 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
<?php

/**
 * Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
 * OPEN 2.0
 *
 *
 * @package    elitedivision\amos\favorites\controllers
 * @category   CategoryName
 * @author     Elite Division S.r.l.
 */

namespace elitedivision\amos\favorites\controllers;

use elitedivision\amos\core\record\Record;
use elitedivision\amos\favorites\AmosFavorites;
use elitedivision\amos\favorites\exceptions\FavoritesException;
use elitedivision\amos\favorites\widgets\FavoriteWidget;
use elitedivision\amos\notificationmanager\AmosNotify;
use Yii;
use yii\web\Controller as YiiController;
use yii\web\NotFoundHttpException;

/**
 * Class FavoriteController
 * @package elitedivision\amos\favorites\controllers
 */
class FavoriteController extends YiiController
{
    /**
     * @var string $layout
     */
    public $layout = 'main';

    /**
     * @inheritdoc
     */
    public function init() {

        parent::init();
        $this->setUpLayout();
        // custom initialization code goes here
    }

    /**
     * The action manages the favorite add or remove.
     * @return string
     * @throws FavoritesException
     */
    public function actionFavorite()
    {
        // If the request is not AJAX throws an exception because this action can only be called via AJAX.
        if (!Yii::$app->getRequest()->getIsAjax()) {
            throw new FavoritesException(AmosFavorites::t('amosfavorites', 'This action cannot be reached directly'));
        }
        
        $retVal = [
            'success' => 0,
            'nowFavorite' => 0,
            'nowNotFavorite' => 1,
            'msg' => '',
            'favoriteBtnTitle' => ''
        ];
        
        // If the request is not via POST method or there is at least one parameter missing stop the execution.
        if (!Yii::$app->getRequest()->post()) {
            $retVal['msg'] = AmosFavorites::t('amosfavorites', 'Request not via POST method.');
            return json_encode($retVal);
        }
        
        $post = Yii::$app->getRequest()->post();
        
        // Missing request parameters.
        if (!isset($post['id']) || !isset($post['className'])) {
            $retVal['msg'] = AmosFavorites::t('amosfavorites', 'Missing request parameters.');
            return json_encode($retVal);
        }
        
        /** @var AmosNotify $notify */
        $notify = Yii::$app->getModule('notify');
        if (is_null($notify)) {
            $retVal['msg'] = AmosFavorites::t('amosfavorites', 'Notify module not present.');
            return json_encode($retVal);
        }
        
        $model = $this->findModel($post['id'], $post['className']);
        $readPerm = $this->makeReadPermission($model);
        if (Yii::$app->user->can($readPerm, ['model' => $model])) {
            $alreadyFavorite = $notify->isFavorite($model, Yii::$app->user->id);
            if ($alreadyFavorite) {
                $ok = $notify->favouriteOff(Yii::$app->user->id, $post['className'], $post['id']);
                return $this->returnValues($ok, $retVal, 'OFF');
            } else {
                $ok = $notify->favouriteOn(Yii::$app->user->id, $post['className'], $post['id']);
                return $this->returnValues($ok, $retVal, 'ON');
            }
        } else {
            $retVal['msg'] = AmosFavorites::t('amosfavorites', 'User cannot read the content.');
            return json_encode($retVal);
        }
    }
    
    /**
     * Make the final return values array and then encode it in JSON.
     * @param bool $ok
     * @param array $retVal
     * @param string $type
     * @return string
     */
    private function returnValues($ok, $retVal, $type)
    {
        $retVal['success'] = ($ok ? 1 : 0);
        
        if (($ok && ($type == 'ON')) || (!$ok && ($type == 'OFF'))) {
            $retVal['nowFavorite'] = 1;
            $retVal['nowNotFavorite'] = 0;
            $retVal['favoriteBtnTitle'] = FavoriteWidget::favoriteBtnTitle(true);
        } elseif ((!$ok && ($type == 'ON')) || ($ok && ($type == 'OFF'))) {
            $retVal['nowFavorite'] = 0;
            $retVal['nowNotFavorite'] = 1;
            $retVal['favoriteBtnTitle'] = FavoriteWidget::favoriteBtnTitle(false);
        }
        
        if ($type == 'ON') {
            $retVal['msg'] = ($ok ?
                AmosFavorites::t('amosfavorites', 'Favorite successfully added.') :
                AmosFavorites::t('amosfavorites', 'Error while adding favorite.'));
        } elseif ($type == 'OFF') {
            $retVal['msg'] = ($ok ?
                AmosFavorites::t('amosfavorites', 'Favorite successfully removed.') :
                AmosFavorites::t('amosfavorites', 'Error while removing favorite.'));
        }
        
        return json_encode($retVal);
    }
    
    /**
     * Find the content model.
     * @param int $id
     * @param string $className
     * @return Record
     * @throws NotFoundHttpException
     */
    private function findModel($id, $className)
    {
        /** @var Record $className */
        $model = $className::findOne($id);
        if (is_null($model)) {
            throw new NotFoundHttpException(AmosFavorites::t('amosfavorites', 'The requested page does not exist.'));
        }
        return $model;
    }
    
    /**
     * Return the read permission for a model by his class name.
     * @param Record $model
     * @return string
     */
    private function makeReadPermission($model)
    {
        $modelClassName = $model::className();
        $splitModelClassName = explode("\\", $modelClassName);
        $modelName = end($splitModelClassName);
        $modelNameUpper = strtoupper($modelName);
        return $modelNameUpper . '_READ';
    }

    /**
     * @param null $layout
     * @return bool
     */
    public function setUpLayout($layout = null){
        if ($layout === false){
            $this->layout = false;
            return true;
        }
        $module = \Yii::$app->getModule('layout');
        if(empty($module)){
            $this->layout =  '@vendor/elitedivision/amos-core/views/layouts/' . (!empty($layout) ? $layout : $this->layout);
            return true;
        }
        $this->layout = (!empty($layout)) ? $layout : $this->layout;
        return true;
    }
}