Пример #1
0
 /**
  * @param $table
  * @return object
  * @throws InvalidConfigException
  */
 public static function findx($table)
 {
     if (self::$table != $table) {
         self::$table = $table;
     }
     return Yii::createObject(ActiveQuery::className(), [get_called_class(), ['from' => [static::tableName()]]]);
 }
Пример #2
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return array_merge(parent::rules(), [[['db', 'ns', 'tableName', 'modelClass', 'baseClass', 'queryNs', 'queryClass', 'queryBaseClass'], 'filter', 'filter' => 'trim'], [['ns', 'queryNs'], 'filter', 'filter' => function ($value) {
         return trim($value, '\\');
     }], [['db', 'ns', 'tableName', 'baseClass', 'queryNs', 'queryBaseClass'], 'required'], [['db', 'modelClass', 'queryClass'], 'match', 'pattern' => '/^\\w+$/', 'message' => 'Only word characters are allowed.'], [['ns', 'baseClass', 'queryNs', 'queryBaseClass'], 'match', 'pattern' => '/^[\\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'], [['tableName'], 'match', 'pattern' => '/^(\\w+\\.)?([\\w\\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'], [['db'], 'validateDb'], [['ns', 'queryNs'], 'validateNamespace'], [['tableName'], 'validateTableName'], [['modelClass'], 'validateModelClass', 'skipOnEmpty' => false], [['baseClass'], 'validateClass', 'params' => ['extends' => ActiveRecord::className()]], [['queryBaseClass'], 'validateClass', 'params' => ['extends' => ActiveQuery::className()]], [['generateRelations', 'generateLabelsFromComments', 'useTablePrefix', 'useSchemaName', 'generateQuery'], 'boolean'], [['enableI18N'], 'boolean'], [['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false], [['imagesDomain', 'imagesPath'], 'filter', 'filter' => 'trim'], [['imagesPath'], 'filter', 'filter' => function ($value) {
         return trim($value, '/');
     }], [['imagesDomain', 'imagesPath'], 'required'], [['addingI18NStrings'], 'boolean'], [['imagesDomain'], 'match', 'pattern' => '/^(?:[\\w](?:[\\w-]+[\\w])?\\.(?:{\\$domain})|(?:[\\w](?:[0-9\\w\\-\\.]+)?[\\w]\\.[\\w]+))|(?:@[\\w_-]+)$/', 'message' => 'No valid images domain.'], [['messagesPaths'], 'validateMessagesPaths']]);
 }
 /**
  * Move a node (model) below the parent and in between left and right
  *
  * @param integer $id  the primaryKey of the moved node
  * @param integer $lft the primaryKey of the node left of the moved node
  * @param integer $rgt the primaryKey of the node right to the moved node
  * @param integer $par the primaryKey of the parent of the moved node
  */
 public function run($id = 0, $lft = 0, $rgt = 0, $par = 0)
 {
     if (null == $this->modelName) {
         throw new \yii\base\InvalidConfigException("No 'modelName' supplied on action initialization.");
     }
     /* response will be in JSON format */
     Yii::$app->response->format = 'json';
     /* Locate the supplied model, left, right and parent models */
     $model = Yii::createObject(ActiveQuery::className(), [$this->modelName])->where(['id' => $id])->one();
     $lft = Yii::createObject(ActiveQuery::className(), [$this->modelName])->where(['id' => $lft])->one();
     $rgt = Yii::createObject(ActiveQuery::className(), [$this->modelName])->where(['id' => $rgt])->one();
     $par = Yii::createObject(ActiveQuery::className(), [$this->modelName])->where(['id' => $par])->one();
     /* Get attribute names from model behaviour config */
     foreach ($model->behaviors as $behavior) {
         if ($behavior instanceof NestedSetsBehavior) {
             $this->leftAttribute = $behavior->leftAttribute;
             $this->rightAttribute = $behavior->rightAttribute;
             $this->treeAttribute = $behavior->treeAttribute;
             $this->depthAttribute = $behavior->depthAttribute;
             break;
         }
     }
     /* attach our bahaviour to be able to call the moveNode() function of the NestedSetsBehavior */
     $model->attachBehavior('nestable', ['class' => \slatiusa\nestable\NestableBehavior::className(), 'leftAttribute' => $this->leftAttribute, 'rightAttribute' => $this->rightAttribute, 'treeAttribute' => $this->treeAttribute, 'depthAttribute' => $this->depthAttribute]);
     /* Calculate the depth change */
     if (null == $par) {
         $depthDelta = -1;
     } else {
         if (null == ($parent = $model->parents(1)->one())) {
             $depthDelta = 0;
         } else {
             if ($parent->id != $par->id) {
                 $depthDelta = $par->{$this->depthAttribute} - $model->{$this->depthAttribute} + 1;
             } else {
                 $depthDelta = 0;
             }
         }
     }
     /* Calculate the left/right change */
     if (null == $lft) {
         $model->nodeMove(($par ? $par->{$this->leftAttribute} : 0) + 1, $depthDelta);
     } else {
         if (null == $rgt) {
             $model->nodeMove(($lft ? $lft->{$this->rightAttribute} : 0) + 1, $depthDelta);
         } else {
             $model->nodeMove($rgt ? $rgt->{$this->leftAttribute} : 0, $depthDelta);
         }
     }
     /* report new position */
     return ['updated' => ['id' => $model->id, 'depth' => $model->{$this->depthAttribute}, 'lft' => $model->{$this->leftAttribute}, 'rgt' => $model->{$this->rightAttribute}]];
 }
 /**
  * Applies latest only condition for syncable behaved models
  *
  * @param Event $event
  */
 public function applyLatestOnlyCondition(Event $event)
 {
     /** @var \yii\db\BaseActiveRecord|\zarv1k\sync\twoway\behavior\model\SyncableBehavior $model */
     $model = $event->data;
     /** @var \yii\db\ActiveRecordInterface $modelClass */
     $modelClass = $this->owner->modelClass;
     /** @var ActiveQuery $activeQuery */
     $activeQuery = $event->sender;
     $updatedAfterDate = \Yii::$app->request->getQueryParam($model->timestampQueryParam);
     $orderBy = [$model->timestampColumn => SORT_ASC];
     foreach ($modelClass::primaryKey() as $column) {
         $orderBy[$column] = SORT_ASC;
     }
     $activeQuery->andFilterWhere(['>', $model->timestampColumn, $updatedAfterDate])->addOrderBy($orderBy);
     Event::off(ActiveQuery::className(), ActiveQuery::EVENT_INIT, [$this, 'applyLatestOnlyCondition']);
 }
Пример #5
0
 /**
  * Tests recovery request form.
  */
 public function testRecoveryRequest()
 {
     $mailer = test::double(Mailer::className(), ['sendRecoveryMessage' => true]);
     $form = Yii::createObject(['class' => RecoveryForm::className(), 'scenario' => 'request']);
     $this->specify('form is not valid when email is empty', function () use($form) {
         $form->setAttributes(['email' => '']);
         verify($form->validate())->false();
         verify($form->getErrors('email'))->contains('Email cannot be blank.');
     });
     $this->specify('form is not valid when email is incorrect', function () use($form) {
         $form->setAttributes(['email' => 'foobar']);
         verify($form->validate())->false();
         verify($form->getErrors('email'))->contains('Email is not a valid email address.');
     });
     $this->specify('form is not valid when user does not exist', function () use($form) {
         test::double(ActiveQuery::className(), ['exists' => false]);
         $form->setAttributes(['email' => '*****@*****.**']);
         verify($form->validate())->false();
         verify($form->getErrors('email'))->contains('There is no user with this email address');
         test::double(ActiveQuery::className(), ['exists' => true]);
     });
     $this->specify('form is not valid when user is not confirmed', function () use($form) {
         $user = \Yii::createObject(User::className());
         test::double($user, ['getIsConfirmed' => false]);
         test::double(Finder::className(), ['findUserByEmail' => $user]);
         $form->setAttributes(['email' => '*****@*****.**']);
         verify($form->validate())->false();
         verify($form->getErrors('email'))->contains('You need to confirm your email address');
         test::double($user, ['getIsConfirmed' => true]);
         verify($form->validate())->true();
     });
     $this->specify('sendRecoveryMessage return true if validation succeeded', function () use($form, $mailer) {
         test::double($form, ['validate' => true]);
         $token = test::double(Token::className(), ['save' => true]);
         $user = \Yii::createObject(['class' => User::className(), 'id' => 1]);
         test::double(Finder::className(), ['findUserByEmail' => $user]);
         verify($form->sendRecoveryMessage())->true();
         $token->verifyInvoked('save');
         verify(\Yii::$app->session->getFlash('info'))->equals('An email has been sent with instructions for resetting your password');
         $mailer->verifyInvoked('sendRecoveryMessage');
     });
 }
 /**
  * @return ActiveQuery
  * @throws \yii\base\InvalidConfigException
  */
 public static function find()
 {
     /** @var ActiveQuery $query */
     $query = Yii::createObject(ActiveQuery::className(), [get_called_class()]);
     $query = $query->innerJoinWith(['defaultTranslation']);
     /** @var ActiveRecord|MultilingualActiveRecord $modelInstance */
     if (method_exists(get_called_class(), 'applyDefaultScope')) {
         $query = call_user_func([get_called_class(), 'applyDefaultScope'], $query);
     } else {
         $modelInstance = new self();
         if ($modelInstance->translationPublishedAttribute !== false) {
             /** @var ActiveRecord $translationModelClassName */
             $translationModelClassName = $modelInstance->getTranslationModelClassName();
             $tableName = $translationModelClassName::tableName();
             // add condition on
             $where = ["{$tableName}.{$modelInstance->translationPublishedAttribute}" => $modelInstance->translationPublishedAttributeValue];
             unset($modelInstance);
             $query = $query->where($where);
         }
     }
     return $query;
 }
Пример #7
0
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return array_merge(parent::rules(), [
            [['db', 'ns', 'tableName', 'modelClass', 'baseClass', 'queryNs', 'queryClass', 'queryBaseClass'], 'filter', 'filter' => 'trim'],
            [['ns', 'queryNs'], 'filter', 'filter' => function($value) { return trim($value, '\\'); }],

            [['db', 'ns', 'tableName', 'baseClass', 'queryNs', 'queryBaseClass'], 'required'],
            [['db', 'modelClass', 'queryClass'], 'match', 'pattern' => '/^\w+$/', 'message' => 'Only word characters are allowed.'],
            [['ns', 'baseClass', 'queryNs', 'queryBaseClass'], 'match', 'pattern' => '/^[\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'],
            [['tableName'], 'match', 'pattern' => '/^(\w+\.)?([\w\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'],
            [['db'], 'validateDb'],
            [['ns', 'queryNs'], 'validateNamespace'],
            [['tableName'], 'validateTableName'],
            [['modelClass'], 'validateModelClass', 'skipOnEmpty' => false],
            [['baseClass'], 'validateClass', 'params' => ['extends' => ActiveRecord::className()]],
            [['queryBaseClass'], 'validateClass', 'params' => ['extends' => ActiveQuery::className()]],
            [['generateRelations', 'generateLabelsFromComments', 'useTablePrefix', 'useSchemaName', 'generateQuery'], 'boolean'],
            [['enableI18N'], 'boolean'],
            [['especializado'], 'integer'],
            [['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
        ]);
    }
Пример #8
0
 /**
  * @inheritdoc
  * @return ActiveQuery the newly created [[ActiveQuery]] instance.
  */
 public static function find()
 {
     return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
 }
Пример #9
0
 /**
  * @inheritdoc
  */
 public function find()
 {
     return Yii::createObject(ActiveQuery::className(), [$this]);
 }
Пример #10
0
 /**
  * Validation of source query data
  *
  * @throws InvalidConfigException
  */
 protected function validateSourceData()
 {
     if (empty($this->query) || !$this->query instanceof ActiveQuery) {
         throw new InvalidConfigException("The 'query' property must be defined and must be an instance of '" . ActiveQuery::className() . "'.");
     }
     $class = isset($this->query->modelClass) ? $this->query->modelClass : null;
     if (empty($class) || !is_subclass_of($class, ActiveRecord::className())) {
         throw new InvalidConfigException("The 'query' must be implemented using 'ActiveRecord::find()' method.");
     }
     $trait = 'jaclise\\tree\\models\\TreeTrait';
     if (!self::usesTrait($class, $trait)) {
         throw new InvalidConfigException("The model class '{$class}' for the 'query' must use the trait '{$trait}' or extend from '" . Tree::className() . "''.");
     }
 }
Пример #11
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return array_merge(parent::rules(), [[['relationClassName'], 'validateClass', 'params' => ['extends' => ActiveQuery::className()]]]);
 }
Пример #12
0
 /**
  * @inheritdoc
  * @return ActiveQuery the newly created [[ActiveQuery]] instance.
  */
 public static function find()
 {
     // 创建一个 ActiveQuery 实例,并把当前类的名字作为参数传入
     return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
 }
Пример #13
0
 protected function prepareDataProvider()
 {
     $dp = parent::prepareDataProvider();
     $urlParams = Yii::$app->getRequest()->queryParams;
     if (is_array($urlParams)) {
         if (isset($urlParams['criteria'])) {
             $criteria = Json::decode($urlParams['criteria']);
             $params = $this->getParams($criteria);
             if (isset($this->controller) && $this->controller->useSecureSearch) {
                 $conditionKeys = $this->getConditionKeys($criteria);
                 if (isset($conditionKeys) && count($conditionKeys) > 0) {
                     $c = $this->getConditionMapItem($conditionKeys, $params);
                     if (isset($c)) {
                         /** @var ActiveQuery $query */
                         if ($c instanceof ActiveQuery) {
                             $query = $c;
                         } else {
                             $query = Yii::createObject(ActiveQuery::className(), [$this->controller->modelClass]);
                             if (isset($c['condition']) || isset($c['with']) || isset($c['expand'])) {
                                 if (isset($c['condition'])) {
                                     $query->where($c['condition'], $params);
                                 }
                                 if (isset($c['with'])) {
                                     $with = $c['with'];
                                 }
                                 if (isset($c['expand'])) {
                                     $with = $c['expand'];
                                 }
                                 if (isset($with)) {
                                     $query->with($with);
                                 }
                             } else {
                                 $query->where($c, $params);
                             }
                         }
                     } else {
                         throw new BadRequestHttpException("Condition definition(s) not found: " . implode(',', $conditionKeys));
                     }
                 }
             } elseif (is_array($criteria) && isset($criteria['condition'])) {
                 /** @var ActiveQuery $query */
                 $query = Yii::createObject(ActiveQuery::className(), [$this->modelClass]);
                 $query->where($criteria['condition'], $params);
             }
             if (is_array($criteria)) {
                 if (isset($criteria['pagination']) && is_array($criteria['pagination'])) {
                     $pagination = $criteria['pagination'];
                     if (!isset($pagination['per-page']) && isset($pagination['perPage'])) {
                         $pagination['per-page'] = $pagination['perPage'];
                     }
                     $dp->setPagination(['params' => array_merge($urlParams, $pagination)]);
                 }
                 if (isset($criteria['sort'])) {
                     $dp->setSort(['params' => array_merge($urlParams, ['sort' => $criteria['sort']])]);
                     $sort = true;
                 }
             }
         }
         if (isset($query)) {
             $dp->query = $query;
         }
         if (isset($sort) || isset($urlParams['sort'])) {
             $dp->getSort()->enableMultiSort = true;
         }
     }
     return $dp;
 }
Пример #14
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return array_merge(parent::rules(), [[['db', 'nsModel', 'tableName', 'modelClass', 'queryNs'], 'filter', 'filter' => 'trim'], [['tableName', 'db'], 'required'], [['tableName'], 'match', 'pattern' => '/^(\\w+\\.)?([\\w\\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'], [['tableName'], 'validateTableName'], [['nsModel', 'baseModelClass', 'queryNs', 'queryBaseClass'], 'match', 'pattern' => '/^[\\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'], [['modelClass', 'baseModelClass', 'db'], 'match', 'pattern' => '/^[\\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'], [['queryBaseClass', 'queryClass'], 'validateClass', 'params' => ['extends' => ActiveQuery::className()]], [['db'], 'validateDb'], [['enableI18N', 'generateQuery', 'generateLabelsFromComments', 'useTablePrefix', 'generateMigrations', 'generateAttributeHints', 'generateBaseOnly'], 'boolean'], [['generateRelations'], 'in', 'range' => [self::RELATIONS_NONE, self::RELATIONS_ALL, self::RELATIONS_ALL_INVERSE]], [['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false], [['skippedColumns', 'skippedRelations', 'blameableValue', 'nameAttribute', 'hiddenColumns', 'timestampValue', 'optimisticLock', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy', 'blameableValue', 'UUIDColumn', 'deletedBy', 'deletedAt'], 'safe']]);
 }