Skip to content

Commit

Permalink
Change modelName to modelId
Browse files Browse the repository at this point in the history
issue #17
  • Loading branch information
chiliec committed Jan 23, 2016
1 parent 31feb75 commit 1cf9708
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 56 deletions.
6 changes: 3 additions & 3 deletions Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ class Module extends \yii\base\Module
* Matching models with integer id's
* @var array
*/
public $matchingModels;
public $models;

public function init()
{
parent::init();
if (!isset($this->matchingModels)) {
throw new InvalidConfigException('matchingModels not configurated');
if (!isset($this->models)) {
throw new InvalidConfigException('models not configurated');
}
if (empty(Yii::$app->i18n->translations['vote'])) {
Yii::$app->i18n->translations['vote'] = [
Expand Down
20 changes: 6 additions & 14 deletions actions/VoteAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,36 +19,28 @@ public function run()
{
if (Yii::$app->request->getIsAjax()) {
Yii::$app->response->format = Response::FORMAT_JSON;

if (null === $modelName = Yii::$app->request->post('modelName')) {
return ['content' => Yii::t('vote', 'Model name has not been sent')];
if (null === $modelId = (int)Yii::$app->request->post('modelId')) {
return ['content' => Yii::t('vote', 'modelId has not been sent')];
}

if (null === $targetId = Yii::$app->request->post('targetId')) {
if (null === $targetId = (int)Yii::$app->request->post('targetId')) {
return ['content' => Yii::t('vote', 'The purpose is not defined')];
}

$act = Yii::$app->request->post('act');
if (!in_array($act, ['like', 'dislike'], true)) {
return ['content' => Yii::t('vote', 'Wrong action')];
}
$value = $act === 'like' ? Rating::VOTE_LIKE : Rating::VOTE_DISLIKE;

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

if (!$userIp = Rating::compressIp(Yii::$app->request->getUserIP())) {
return ['content' => Yii::t('vote', 'The user is not recognized')];
}

$modelId = Rating::getModelIdByName($modelName);
if (!is_int($modelId)) {
return ['content' => Yii::t('vote', 'The model is not registered')];
}

if (Rating::getIsAllowGuests($modelName)) {
if (Rating::getIsAllowGuests($modelId)) {
$isVoted = Rating::findOne(['model_id' => $modelId, 'target_id' => $targetId, 'user_ip' => $userIp]);
} else {
$isVoted = Rating::findOne(['model_id' => $modelId, 'target_id' => $targetId, 'user_id' => $userId]);
Expand All @@ -70,7 +62,7 @@ public function run()
return ['content' => Yii::t('vote', 'Validation error')];
}
} else {
if ($isVoted->value !== $value && Rating::getIsAllowChangeVote($modelName)) {
if ($isVoted->value !== $value && Rating::getIsAllowChangeVote($modelId)) {
$isVoted->value = $value;
if ($isVoted->save()) {
return ['content' => Yii::t('vote', 'Your vote has been changed. Thanks!'), 'success' => true, 'changed' => true];
Expand Down
2 changes: 1 addition & 1 deletion messages/de/vote.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
'You have already voted!' => 'Sie haben bereits abgestimmt!',
'Forbidden method' => 'Verbotene Methode',
'Aggregate rating' => 'Aggregate Bewertung',
'Model name has not been sent' => 'Modelname wurde nicht gesendet',
'modelId has not been sent' => 'modelId wurde nicht gesendet',
'Target id has not been sent' => 'Ziel-ID wurde nicht gesendet',
'modelName or targetId not configurated' => 'Der Modelname oder Ziel-ID wurde nicht konfiguriert',
];
2 changes: 1 addition & 1 deletion messages/ru/vote.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
'You have already voted!' => 'Вы уже голосовали!',
'Forbidden method' => 'Запрещенный метод',
'Aggregate rating' => 'Совокупный рейтинг',
'Model name has not been sent' => 'Не передано имя модели',
'modelId has not been sent' => 'Не передано id модели',
'Target id has not been sent' => 'Не передано id цели',
'modelName or targetId not configurated' => 'Имя модели или цели не задано',
];
68 changes: 45 additions & 23 deletions models/Rating.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,53 +90,74 @@ public function afterSave($insert, $changedAttributes)
*/
public static function getModelIdByName($modelName)
{
$matchingModels = Yii::$app->getModule('vote')->matchingModels;
if (isset($matchingModels[$modelName]['id'])) {
return $matchingModels[$modelName]['id'];
if (null !== $models = Yii::$app->getModule('vote')->models) {
$modelId = array_search($modelName, $models);
if (is_int($modelId)) {
return $modelId;
}
foreach ($models as $key => $value) {
if (!is_array($value)) {
continue;
}
if ($value['modelName'] === $modelName) {
return $key;
}
}
}
if (isset($matchingModels[$modelName])) {
return $matchingModels[$modelName];
return false;
}

/**
* @param integer $modelId Id of model
* @return string|false Model name or false if matches not found
*/
public static function getModelNameById($modelId)
{
if (null !== $models = Yii::$app->getModule('vote')->models) {
if (isset($models[$modelId])) {
if (is_array($models[$modelId])) {
return $models[$modelId]['modelName'];
} else {
return $models[$modelId];
}
}
}
return false;
}

/**
* @param string $modelName Name of model
* @param integer $modelId Id of model
* @return boolean Checks exists permission for guest voting in model params or return global value
*/
public static function getIsAllowGuests($modelName)
public static function getIsAllowGuests($modelId)
{
$matchingModels = Yii::$app->getModule('vote')->matchingModels;
if (isset($matchingModels[$modelName]['allowGuests'])) {
return $matchingModels[$modelName]['allowGuests'];
$models = Yii::$app->getModule('vote')->models;
if (isset($models[$modelId]['allowGuests'])) {
return $models[$modelId]['allowGuests'];
}
return Yii::$app->getModule('vote')->allowGuests;
}

/**
* @param string $modelName Name of model
* @param string $modelId Id of model
* @return boolean Checks exists permission for change vote in model params or return global value
*/
public static function getIsAllowChangeVote($modelName)
public static function getIsAllowChangeVote($modelId)
{
$matchingModels = Yii::$app->getModule('vote')->matchingModels;
if (isset($matchingModels[$modelName]['allowChangeVote'])) {
return $matchingModels[$modelName]['allowChangeVote'];
$models = Yii::$app->getModule('vote')->models;
if (isset($models[$modelId]['allowChangeVote'])) {
return $models[$modelId]['allowChangeVote'];
}
return Yii::$app->getModule('vote')->allowChangeVote;
}

/**
* @param string $modelName Name of model
* @param string $modelId Id of model
* @param integer $targetId Current value of primary key
* @return array ['likes', 'dislikes', 'aggregateRating']
* @return array ['likes', 'dislikes', 'rating']
*/
public static function getRating($modelName, $targetId)
public static function getRating($modelId, $targetId)
{
$modelId = static::getModelIdByName($modelName);
if (!is_int($modelId)) {
throw new InvalidParamException(Yii::t('vote', 'The model is not registered'));
}
$cacheKey = 'rating' . $modelId . 'target' . $targetId;
$result = Yii::$app->cache->get($cacheKey);
if ($result === false) {
Expand Down Expand Up @@ -184,7 +205,8 @@ public static function compressIp($ip)
* @param string $str
* @return string $ip
*/
public static function expandIp($str) {
public static function expandIp($str)
{
if (strlen($str) == 16 OR strlen($str) == 4) {
return inet_ntop(pack("A".strlen($str), $str));
}
Expand Down
46 changes: 32 additions & 14 deletions widgets/Vote.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use yii\base\Widget;
use yii\helpers\Html;
use yii\web\View;
use yii\web\JsExpression;
use yii\helpers\Json;
use Yii;

class Vote extends Widget
Expand Down Expand Up @@ -75,31 +77,33 @@ class Vote extends Widget
* @var string
*/
public $jsErrorVote = "
jQuery('#vote-response-'+model+target).html(errorThrown);
jQuery('#vote-response-' + model + '-' + target).html(errorThrown);
";

/**
* @var string
*/
public $jsShowMessage = "
jQuery('#vote-response-'+model+target).html(data.content);
jQuery('#vote-response-' + model + '-' + target).html(data.content);
";

/**
* @var string
*/
public $jsChangeCounters = "
if (typeof(data.success) !== 'undefined') {
var idUp = '#vote-up-' + model + '-' + target;
var idDown = '#vote-down-' + model + '-' + target;
if (act === 'like') {
jQuery('#vote-up-'+model+target).text(parseInt(jQuery('#vote-up-'+model+target).text()) + 1);
jQuery(idUp).text(parseInt(jQuery(idUp).text()) + 1);
} else {
jQuery('#vote-down-'+model+target).text(parseInt(jQuery('#vote-down-'+model+target).text()) + 1);
jQuery(idDown).text(parseInt(jQuery(idDown).text()) + 1);
}
if (typeof(data.changed) !== 'undefined') {
if (act === 'like') {
jQuery('#vote-down-'+model+target).text(parseInt(jQuery('#vote-down-'+model+target).text()) - 1);
jQuery(idDown).text(parseInt(jQuery(idDown).text()) - 1);
} else {
jQuery('#vote-up-'+model+target).text(parseInt(jQuery('#vote-up-'+model+target).text()) - 1);
jQuery(idUp).text(parseInt(jQuery(idUp).text()) - 1);
}
}
}
Expand All @@ -116,30 +120,44 @@ public function init()
$this->voteUrl = Yii::$app->getUrlManager()->createUrl(['vote/default/vote']);
}

$js = "
$js = new JsExpression("
function vote(model, target, act) {
jQuery.ajax({
url: '$this->voteUrl', type: 'POST', dataType: 'json', cache: false,
data: { modelName: model, targetId: target, act: act },
data: { modelId: model, targetId: target, act: act },
beforeSend: function(jqXHR, settings) { $this->jsBeforeVote },
success: function(data, textStatus, jqXHR) { $this->jsChangeCounters $this->jsShowMessage },
complete: function(jqXHR, textStatus) { $this->jsAfterVote },
error: function(jqXHR, textStatus, errorThrown) { $this->jsErrorVote }
});
}
";
");
$this->view->registerJs($js, View::POS_END, $this->jsCodeKey);
}

public function run()
{
$rating = Rating::getRating($this->modelName, $this->targetId);
$id = $this->modelName . $this->targetId;
$modelId = Rating::getModelIdByName($this->modelName);
$rating = Rating::getRating($modelId, $this->targetId);
$id = $modelId . '-' . $this->targetId;
$content = Html::beginTag('div', ['class' => $this->classGeneral]);
$content .= Html::tag('span', $rating['likes'], ['id' => "vote-up-$id", 'class' => $this->classLike, 'onclick' => "vote('$this->modelName', $this->targetId, 'like'); return false;", 'style' => 'cursor: pointer;']);
$content .= Html::tag('span', $rating['likes'], [
'id' => "vote-up-$id",
'class' => $this->classLike,
'onclick' => new JsExpression("vote({$modelId}, {$this->targetId}, 'like'); return false;"),
'style' => 'cursor: pointer;'
]);
$content .= $this->separator;
$content .= Html::tag('span', $rating['dislikes'], ['id' => "vote-down-$id", 'class' => $this->classDislike, 'onclick' => "vote('$this->modelName', $this->targetId, 'dislike'); return false;", 'style' => 'cursor: pointer;']);
$content .= Html::tag('div', $this->showAggregateRating ? Yii::t('vote', 'Aggregate rating') . ': ' . $rating['rating'] : '', ['id' => "vote-response-$id"]);
$content .= Html::tag('span', $rating['dislikes'], [
'id' => "vote-down-$id",
'class' => $this->classDislike,
'onclick' => new JsExpression("vote({$modelId}, {$this->targetId}, 'dislike'); return false;"),
'style' => 'cursor: pointer;'
]);
$content .= Html::tag('div',
$this->showAggregateRating ? Yii::t('vote', 'Aggregate rating') . ': ' . $rating['rating'] : '',
['id' => "vote-response-$id"]
);
$content .= Html::endTag('div');
return $content;
}
Expand Down

0 comments on commit 1cf9708

Please sign in to comment.