Snippets

You are viewing an old version of this snippet. View the current version.
Revised by Илья Караваев 47ff801
namespace ...;

use ...;

/**
 * Class ActiveRecord
 *
 * @property integer $id
 * @property string $name
 * @property string $phone
 * @property string $email
 * @property string $description
 * @property string $date_from
 * @property string $date_to
 * @property string $created_at
 * @property string $updated_at
 *
 * @property File[] $files
 */
class ActiveRecord extends CommonActiveRecord
{
    protected $_files = [];
    protected $_filesForDelete = [];
    
    public static function tableName()
    {
        return '{{%active_record}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'value' => new Expression('NOW()'),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at']
                ],
            ],
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'date_from',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'date_from',
                    ActiveRecord::EVENT_BEFORE_VALIDATE => 'date_from',
                ],
                'value' => function ($event) {
                    return date('Y-m-d', strtotime($this->date_from));
                },
            ],
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'date_to',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'date_to',
                    ActiveRecord::EVENT_BEFORE_VALIDATE => 'date_to',
                ],
                'value' => function ($event) {
                    return date('Y-m-d', strtotime($this->date_to));
                },
            ],
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_AFTER_FIND => 'name',
                ],
                'value' => function ($event) {
                    return Html::decode($this->name);
                },
            ],
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_AFTER_FIND => 'description',
                ],
                'value' => function ($event) {
                    return Html::decode($this->description);
                },
            ],
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_AFTER_FIND => 'comment',
                ],
                'value' => function ($event) {
                    return Html::decode($this->comment);
                },
            ],
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'phone',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'phone',
                    ActiveRecord::EVENT_AFTER_FIND    => 'phone',
                ],
                'value' => function (\yii\base\Event $event) {
                    if ($this->phone) {
                        if ($event->name == ActiveRecord::EVENT_BEFORE_INSERT || $event->name == ActiveRecord::EVENT_BEFORE_UPDATE) {
                                return preg_replace('/[^0-9]/u', '', $this->phone);
                        }  else {
                            return '+7 ' . Helper::formatPhone($this->phone,'');
                        }
                    }
                    return "";
                },
            ],
        ];
    }
    
    public function attributeLabels()
    {
        return [
            'name' => 'Название',
            'description' => 'Описание',
            'date_from' => 'Начало срока',
            'date_to' => 'Конец срока',
            'email' => 'Email',
            'phone' => 'Телефон',
        ];
    }


    public function rules()
    {
        retirn [
            [['name', 'description', 'date_from', 'date_to', 'email'], 'required'],
            [['description'], 'string'],
            [['max_price'], 'integer'],
            [['max_price'], 'number', 'min' => 0, 'max' => 2147483647],
            [['date_from', 'date_to', 'created_at', 'updated_at'], 'safe'],
            [['date_from', 'date_to'], 'date', 'format' => 'php:Y-m-d'],
            [['name'], 'string', 'max' => 64],
            [['email'], 'string', 'max' => 255],
            [['email'], 'email'],
            [['phone'], 'string', 'max' => 20],
            [['phone'], function ($attribute, $params) {
                if ($this->$attribute) {
                    $clearPhone = preg_replace('/[^0-9]/u', '', $this->$attribute);
                    if (mb_strlen($clearPhone, 'UTF-8') != 11) {
                        $this->addError($attribute, '...');
                    }
                }
            }],
            [['name', 'description', 'email', 'phone'], 'filter', 'filter' => '\yii\helpers\HtmlPurifier::process'],
            [['name', 'description', 'email', 'phone'], 'filter', 'filter' => '\yii\helpers\Html::encode'],
            [
                ['name'],
                'unique',
                'targetAttribute' => [
                    'name',
                    'description',
                    'email',
                    'date_from',
                    'date_to'
                ],
                'message' => '...',
                'when' => function () {
                    return $this->isNewRecord;
                }
            ],
            'date_to', function ($attribute, $params) {
                if (strtotime($this->$attribute) < strtotime($this->date_from)) {
                    $this->addError('date_to', '...');
                }
            }];
        ];
    }
    
    public function getFiles()
    {
        return $this
            ->hasMany(File::className(), ['id' => 'file_id'])
            ->viaTable('doc', ['doc_id' => 'id']);
    }

    public function setFilesForDelete($files)
    {
        if ($files) {
            $this->_filesForDelete = is_array($files) ? $files : explode(',', preg_replace('/([\d,]+)[,]&?/', '$1', $files));
        } else {
            $this->_filesForDelete = [];
        }
    }

    public function afterSave($insert, $changedAttributes)
    {
        \Yii::$app
            ->db
            ->createCommand()
            ->delete('doc', 'id = ' . $this->id)
            ->execute();

        if (!empty($this->_files)) {
            foreach ($this->_files as $file) {
                \Yii::$app
                    ->db
                    ->createCommand()
                    ->insert('doc', [
                        'id' => $this->id,
                        'file_id' => $file,
                        'attached_at' => new Expression('NOW()'),
                    ])->execute();
            }
        }

        if (!empty($this->_filesForDelete)) {
            foreach ($this->_filesForDelete as $fileId) {
                File::findOne($fileId)->delete();
            }
        }
        parent::afterSave($insert, $changedAttributes);
    }

    public function setFiles($files)
    {
        if ($files) {
            $this->_files = is_array($files) ? $files : explode(',', $files);
        } else {
            $this->_files = [];
        }
    }

    public function beforeDelete()
    {
        if ($this->files) {
            foreach ($this->files as $file) {
                if ($file->delete() === false) {
                    return false;
                }
            }
        }
        return parent::beforeDelete();
    }

    public static function find()
    {
        return \Yii::createObject(ActiceQuery::className(), [get_called_class()]);
    }

    public function hasLimitEditing()
    {
        $limitEditing = \Yii::$app->formatter->asTimestamp($this->created_at) + \Yii::$app->params['editingLimit'];
        
        if (time() >= $limitEditing) {
            return true;
        }
        
        return false;
    }
}
namespace ...;

use ...;

class Controller extends \yii\web\Controller
{
    public function behaviors()
    {
        $behaviours = [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [
                            'index',
                            'list',
                            'create',
                            'update',
                            'delete',
                            'upload',
                            'comment'
                        ],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            [
                'class' => 'yii\filters\ContentNegotiator',
                'only' => [
                    'list',
                    'create',
                    'update',
                    'delete',
                    'upload',
                    'comment'
                ],
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                ],
            ]
        ];
        return ArrayHelper::merge(parent::behaviors(), $behaviours);
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionCreate()
    {
        $request = \Yii::$app->request;

        $model = new ActiveRecord();
        $model->files = $request->post('files');
        $model->filesForDelete = $request->post('files_delete');

        if ($model->load(Common::prepareRequestData($model->formName())) && $model->save() && $model->refresh()) {
            return ArrayHelper::toArray($model, [
                ActiveRecord::className() => [
                    'id',
                    'name',
                    'email',
                    'phone',
                    'description',
                    'comment',
                    'date_from',
                    'date_to',
                    'files',
                ],
                File::className() => [
                    'id',
                    'name',
                    'url'
                ]
            ]);
        }

        throw new BadRequestHttpException();
    }

    public function actionUpdate($id)
    {
        $model = ActiveRecord::findOne($id);

        if ($model->hasLimitEditing()) {
            throw new BadRequestHttpException();
        }

        $request = \Yii::$app->request;

        $model->files = $request->post('files');
        $model->filesForDelete = $request->post('files_delete');

        if ($model->load(Common::prepareRequestData($model->formName())) && $model->save() && $model->refresh()) {

            return ArrayHelper::toArray($model, [
                ActiveRecord::className() => [
                    'id',
                    'name',
                    'email',
                    'phone',
                    'description',
                    'comment',
                    'date_from',
                    'date_to',
                    'files'
                ],
                File::className() => [
                    'id',
                    'name',
                    'url'
                ],
            ]);
        }

        throw new BadRequestHttpException();
    }

    public function actionDelete($id)
    {
        ...
    }

    public function actionComment()
    {
        ...
    }

    public function actionUpload()
    {
        ...
    }

    public function actionAdd()
    {
        ...
    }

    public function actionMove()
    {
        ...
    }
    
    ...
}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.