/** * More intelligent version of saveRating - checks record existance and ratings * * @param Model $Model * @param string model primary key / id * @param mixed user id integer or string uuid * @param mixed integer or string rating * @param array options * @param return boolean True on success */ public function rate(Model $Model, $foreignKey = null, $userId = null, $rating = null, $options = array()) { $options = array_merge(array('userField' => 'user_id', 'find' => array('contain' => array(), 'conditions' => array($Model->alias . '.' . $Model->primaryKey => $foreignKey)), 'values' => array('up' => 1, 'down' => -1)), $options); if (!in_array($rating, array_keys($options['values']))) { throw new OutOfBoundsException(__d('ratings', 'Invalid Rating')); } $record = $Model->find('first', $options['find']); if (empty($record)) { throw new OutOfBoundsException(__d('ratings', 'Invalid Record')); } if ($options['userField'] !== false && $Model->getColumnType($options['userField'])) { if ($record[$Model->alias][$options['userField']] == $userId) { $Model->data = $record; throw new LogicException(__d('ratings', 'You can not vote on your own records')); } } if ($Model->saveRating($foreignKey, $userId, $options['values'][$rating])) { $Model->data = $record; return true; } else { throw new RuntimeException(__d('ratings', 'You have already rated this record')); } }