Comment.php 2.86 KB
<?php
    namespace common\modules\comment\models;

    /**
     * Class Comment
     * @property bool $guestComment
     * @package common\modules\comment\models
     */
    class Comment extends \yii\db\ActiveRecord
        implements \common\modules\comment\interfaces\CommentInterface
    {

        const STATUS_HIDDEN = 0;
        const STATUS_DELETED = 2;
        const STATUS_ACTIVE = 1;
        const STATUS_PERSONAL = 3;

        const SCENARIO_USER = 'user';
        const SCENARIO_GUEST = 'guest';

        public function rules()
        {
            return [
                [
                    ['text'],
                    'required',
                ],
                [
                    ['user_email'],
                    'email',
                ],
                [
                    ['user_name'],
                    'string',
                ],
            ];
        }

        public function scenarios()
        {
            return [
                self::SCENARIO_GUEST => ['user_name', 'user_email', 'text'],
                self::SCENARIO_USER => ['text'],
            ];
        }

        public static function tableName()
        {
            return '{{%comment}}';
        }

        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'text' => \Yii::t('app', 'Комментарий'),
                'user_name' => \Yii::t('app', 'Имя'),
                'user_email' => \Yii::t('app', 'Email'),
            ];
        }

        public function getGuestComment($entity)
        {
            return true;
        }

        public function getComments($entity)
        {
            return $this->find()->where(['entity' => $this->entity]);
        }

        public function postComment($data)
        {
            if($this->load($data) && $this->insert($data)) {
                $this->clearSafe();
                return true;
            } else {
                return false;
            }
        }

        public function updateComment($comment_id)
        {
            // TODO: Implement updateComment() method.
        }

        public function deleteComment($comment_id)
        {
            // TODO: Implement deleteComment() method.
        }

        public function checkCreate($entity)
        {
            if($this->getGuestComment($entity)) {
                return true;
            } else {
                return \Yii::$app->user->can(\common\modules\comment\Permissions::CREATE, ['entity' => $entity]);
            }
        }

        protected function clearSafe($setNew = true) {
            $safe = $this->safeAttributes();
            $count = count($safe);
            $values = array_fill(0, $count, NULL);
            $result = array_combine($safe, $values);
            $this->setAttributes($result);
            $this->setIsNewRecord($setNew);
        }

    }