Просмотр файла vkclone-0.0.1/protected/models/Group.php

Размер файла: 2.82Kb
<?php
/**
 * This is the model class for table "{{groups}}".
 */
class Group extends CActiveRecord {
	private $_access = null;

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return '{{groups}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		return array(
			array('name', 'required'),
			array('id, creator_id', 'length', 'max' => 10),
			array('name, description', 'length', 'max' => 255),
			// The following rule is used by search().
			array('id, name', 'safe', 'on' => 'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		return array(
			'profile' => array(self::BELONGS_TO, 'Profile', 'id'),
			'creator' => array(self::BELONGS_TO, 'User', 'creator_id'),
			'moderators' => array(self::HAS_MANY, 'Moderator', 'community_id'),
			'members' => array(self::MANY_MANY, 'User', GroupMember::model()->tableName().'(group_id, user_id)'),
		);
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Group the static model class
	 */
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}

	/**
	 * Creates a group
	 */
	public function create() {
		$transaction = $this->dbConnection->beginTransaction();
		$profile = new Profile;
		$profile->type = 'group';
		if (!$profile->save())
			return false;
		$group = new self;
		$group->attributes = $this->attributes;
		$group->id = $profile->id;
		if (!$group->save())
			return false;
		$membership = new GroupMember;
		$membership->group_id = $group->id;
		$membership->user_id = Yii::app()->user->record->id;
		$membership->role = GroupMember::MEMBER;
		$membership->approved = "1";
		if (!$membership->save())
			return false;
		$transaction->commit();
		return $group;
	}

	/**
	 * Checks access for currently logged user
	 * @param string $requiredRole
	 */
	public function checkAccess($requiredRole, $allowCaching = true) {
		if ($this->creator_id == Yii::app()->user->record->id)
			return true;

		if ($allowCaching && $this->_access !== null)
			return GroupMember::checkAccess($this->_access, $requiredRole);

		if (($membership = GroupMember::model()->findByAttributes(array('group_id' => $this->id, 'user_id' => Yii::app()->user->record->id))) == null)
			return false;

		if ($allowCaching)
			$this->_access = $membership->role;

		return GroupMember::checkAccess($membership->role, $requiredRole);
	}

	/**
	 * @param CActiveRecord|int $user model or User id
	 */
	public function hasMember($user) {
		if (is_object($user))
			$user = $user->id;
		return GroupMember::model()->exists((new CDbCriteria)->compare('group_id', $this->id)->compare('user_id', $user));
	}
}