Skip to content

Commit

Permalink
Fix check allow_guests and small refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
chiliec committed Jan 30, 2015
1 parent d428646 commit 5b22a72
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 46 deletions.
3 changes: 1 addition & 2 deletions Display.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,9 @@ function vote(model, target, act){

public function run()
{
$rating = new Rating();
$target_id = $this->target_id;
$model_name = $this->model_name;
$rating = $rating->getRating($this->model_name, $this->target_id);
$rating = Rating::getRating($this->model_name, $this->target_id);
$id = $model_name . $target_id;
$content = Html::beginTag('div', $this->mainDivOptions);
$content .= Html::tag('span', $rating['likes'], ['id'=>"vote-up-$id", 'class' => $this->classLike, 'onclick' => "vote('$model_name',$target_id,'like');return false;", 'style' => 'cursor:pointer;']);
Expand Down
19 changes: 7 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ Step 1: Install component via composer
Run command

```
php composer.phar require --prefer-dist chiliec/yii2-vote "~1.3"
php composer.phar require --prefer-dist chiliec/yii2-vote "~2.0"
```

or add

```
"chiliec/yii2-vote": "~1.3"
"chiliec/yii2-vote": "~2.0"
```

to the require section of your `composer.json` file.
Expand All @@ -28,20 +28,18 @@ Step 2: Configuring your application

Add following lines to your main configuration file:

Attention: this configuration works only with dev-master version. Configuration for last stable version [see here](https://github.com/Chiliec/yii2-vote/tree/1.4).

```php
'modules' => [
'vote' => [
'class' => 'chiliec\vote\Module',
'allow_guests' => true, // if true will check IP, otherwise - UserID. Can be changed at any time
'allow_guests' => true, // if true will check IP, otherwise - UserID
'allow_change_vote' => true, // if true vote can be changed
'matchingModels' => [ // matching model names with whatever unique integer ID
'article' => 0, // may be just integer value
'audio' => ['id'=>1], // or array with 'id' key
'video' => ['id'=>2, 'allow_guests'=>true], // or with own value of 'allow_guests' for any models
],

'video' => ['id'=>2, 'allow_guests'=>false], // own value 'allow_guests'
'photo' => ['id'=>3, 'allow_guests'=>false, 'allow_change_vote'=>false],
],
],
],
```
Expand All @@ -58,9 +56,6 @@ And add widget in view:
'classLike' => 'glyphicon glyphicon-thumbs-up', // class for like button
'classDislike' => 'glyphicon glyphicon-thumbs-down', // class for dislike button
'separator' = ' ', // separator between like and dislike button
'js_before_vote' => 'alert("before_vote")', // your javascript before vote
'js_after_vote' => 'alert("after_vote")', // your javascript after vote
'js_result' => '', // for overwrite js functional
]); ?>
```

Expand Down Expand Up @@ -116,7 +111,7 @@ For example, if you want to use [noty jQuery plugin](https://github.com/needim/n

```php
<?php echo \chiliec\vote\Display::widget([
'model_name' => 'Article',
'model_name' => 'article',
'target_id' => $model->id,
'js_show_message' => "
message = data.content;
Expand Down
9 changes: 5 additions & 4 deletions actions/VoteAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public function run()
$value = $act==='like' ? 1 : 0;

$user_id = Yii::$app->user->getId();
if($user_id === null && !Rating::getIsAllowGuests($model_name)) {
return ['content' => Yii::t('vote', 'Guests are not allowed to vote')];
}

if(!$user_ip = Rating::compressIp(Yii::$app->request->getUserIP())) {
return ['content' => Yii::t('vote', 'The user is not recognized')];
Expand All @@ -58,19 +61,17 @@ public function run()
$newVote->user_ip = $user_ip;
$newVote->value = $value;
if($newVote->save()) {
Yii::$app->cache->delete('aggregate_rating'.$model_name.$target_id);
Yii::$app->cache->delete('rating'.$model_name.$target_id);
if($value===1) {
Yii::$app->cache->delete('likes'.$model_name.$target_id);
return ['content' => Yii::t('vote', 'Your vote is accepted. Thanks!'), 'success' => true];
} else {
Yii::$app->cache->delete('dislikes'.$model_name.$target_id);
return ['content' => Yii::t('vote', 'Thanks for your opinion'), 'success' => true];
}
} else {
return ['content' => Yii::t('vote', 'Validation error')];
}
} else {
if($isVoted->value !== $value && Yii::$app->getModule('vote')->allow_change_vote) {
if($isVoted->value !== $value && Rating::getIsAllowChangeVote($model_name)) {
$isVoted->value = $value;
if($isVoted->save()) {
return ['content' => Yii::t('vote', 'Your vote has been changed. Thanks!'), 'success' => true, 'changed' => true];
Expand Down
3 changes: 1 addition & 2 deletions behaviors/RatingBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ public function events()

public function afterFind($event)
{
$model = new Rating();
if($received_rating = $model->getRating($this->model_name, $this->owner->id)) {
if($received_rating = Rating::getRating($this->model_name, $this->owner->id)) {
$rating = $received_rating['likes'] - $received_rating['dislikes'];
$aggregate_rating = $received_rating['aggregate_rating'];
if(($this->owner->{$this->rating_field} != $rating) or ($this->owner->{$this->aggregate_rating_field} != $aggregate_rating)) {
Expand Down
1 change: 1 addition & 0 deletions messages/ru/vote.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

return [
'The user is not recognized' => 'Пользователь не распознан',
'Guests are not allowed to vote' => 'Гостям не разрешено голосовать',
'The model is not registered' => 'Модель не зарегистрирована!',
'The purpose is not defined' => 'Цель не определена',
'Wrong action' => 'Неправильное действие!',
Expand Down
52 changes: 26 additions & 26 deletions models/Rating.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,40 +95,40 @@ public static function getModelIdByName($model_name)
public static function getIsAllowGuests($model_name)
{
$matchingModels = Yii::$app->getModule('vote')->matchingModels;
if(isset($matchingModels[$model_name]) && is_array($matchingModels[$model_name])) {
if(array_key_exists('allow_guests', $matchingModels[$model_name])) {
return $matchingModels[$model_name]['allow_guests'];
}
if(isset($matchingModels[$model_name]['allow_guests'])) {
return $matchingModels[$model_name]['allow_guests'];
}
return Yii::$app->getModule('vote')->allow_guests;
}

/**
* @param string $model_name Name of model
* @param integer $target_id Current value of primary key
* @return array
* @return boolean Checks exists permission for change vote in model params or return global value
*/
public function getRating($model_name, $target_id)
public static function getIsAllowChangeVote($model_name)
{
$model_id = $this->getModelIdByName($model_name);
if(!is_int($model_id)) {
throw new InvalidParamException('Model name not recognized');
}

$likes = Yii::$app->cache->get('likes'.$model_name.$target_id);
if($likes === false) {
$likes = $this->find()->where(['model_id'=>$model_id, 'target_id'=>$target_id, 'value'=>1])->count();
Yii::$app->cache->set('likes'.$model_name.$target_id, $likes);
$matchingModels = Yii::$app->getModule('vote')->matchingModels;
if(isset($matchingModels[$model_name]['allow_change_vote'])) {
return $matchingModels[$model_name]['allow_change_vote'];
}
return Yii::$app->getModule('vote')->allow_change_vote;
}

$dislikes = Yii::$app->cache->get('dislikes'.$model_name.$target_id);
if($dislikes === false) {
$dislikes = $this->find()->where(['model_id'=>$model_id, 'target_id'=>$target_id, 'value'=>0])->count();
Yii::$app->cache->set('dislikes'.$model_name.$target_id, $dislikes);
/**
* @param string $model_name Name of model
* @param integer $target_id Current value of primary key
* @return array ['likes', 'dislikes', 'aggregate_rating']
*/
public static function getRating($model_name, $target_id)
{
$model_id = self::getModelIdByName($model_name);
if(!is_int($model_id)) {
throw new InvalidParamException(Yii::t('vote', 'The model is not registered'));
}

$rating = Yii::$app->cache->get('aggregate_rating'.$model_name.$target_id);
if ($rating === false) {
$result = Yii::$app->cache->get('rating'.$model_name.$target_id);
if($result === false) {
$likes = self::find()->where(['model_id'=>$model_id, 'target_id'=>$target_id, 'value'=>1])->count();
$dislikes = self::find()->where(['model_id'=>$model_id, 'target_id'=>$target_id, 'value'=>0])->count();
if ($likes+$dislikes != 0) {
// Рейтинг = Нижняя граница доверительного интервала Вильсона (Wilson) для параметра Бернулли
// http://habrahabr.ru/company/darudar/blog/143188/
Expand All @@ -138,10 +138,10 @@ public function getRating($model_name, $target_id)
$rating = 0;
}
$rating = round($rating*10, 2);
Yii::$app->cache->set('aggregate_rating'.$model_name.$target_id, $rating);
$result = ['likes'=>$likes, 'dislikes'=>$dislikes, 'aggregate_rating'=>$rating];
Yii::$app->cache->set('rating'.$model_name.$target_id, $result);
}

return ['likes'=>$likes, 'dislikes'=>$dislikes, 'aggregate_rating'=>$rating];
return $result;
}

/**
Expand Down

0 comments on commit 5b22a72

Please sign in to comment.