NotifyBehavior.php 2.37 KB
<?php
    
    namespace common\behaviors;
    
    use common\models\Articles;
    use common\modules\comment\models\CommentModel;
    use common\modules\product\models\Product;
    use common\widgets\Mailer;
    use yii\base\Behavior;
    use yii\base\Event;
    use yii\db\ActiveRecord;
    use yii\helpers\Url;
    
    /**
     * Class NotifyBehavior
     * @property CommentModel $owner
     * @package common\behaviors
     */
    class NotifyBehavior extends Behavior
    {
        
        public function events()
        {
            return [
                ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
            ];
        }
        
        public function afterUpdate($event)
        {
            /**
             * @var Event        $event
             * @var CommentModel $owner
             */
            $owner = $this->owner;
            if($owner->status == $owner::STATUS_ACTIVE) {
                $entity = $owner->entity;
                $model = $entity::findOne($owner->entity_id);
                if($model != NULL) {
                    if(!empty( $owner->user )) {
                        $customer = $owner->user;
                        if(preg_match('/\S+@\S+\.\S+/', $customer->username)) {
                            $email = $customer->username;
                        } else {
                            return false;
                        }
                    }
                    $url = \Yii::$app->urlManager->getHostInfo();
                    if($model::className() == Product::className()) {
                        $url .= '/product/'.$model->alias.'#artbox-comment';
                    } elseif($model::className() == Articles::className()) {
                        $url .= '/blog/'.$model->translit.'#artbox-comment';
                    }
                    $mailer = Mailer::widget([
                        'type'    => 'comment_notify',
                        'params'  => [
                            'model' => $model,
                            'url'   => $url,
                            'comment' => $owner,
                        ],
                        'subject' => 'Ваш комментарий опубликован',
                        'email'   => ( !empty( $customer ) ? $email : $owner->email ),
                    ]);
                    return $mailer;
                }
            }
            return false;
        }
    }