Esempio n. 1
0
 /**
  * Initializes the widget options.
  * This method sets the default values for various options.
  */
 protected function initOptions()
 {
     if (!isset($this->options['id'])) {
         $this->options['id'] = $this->getId();
     }
     $this->clientOptions = ArrayHelper::merge(['form' => $this->form, 'fieldsUrl' => Url::to(['/eav/backend/attribute/fields']), 'modelClass' => $this->model ? $this->model->className() : ''], $this->clientOptions);
 }
 /**
  * @inheritdoc
  *
  * @param ActiveRecord $owner
  *
  * @throws ErrorException
  */
 public function attach($owner)
 {
     if (!self::$_eventSwitched) {
         Event::on($owner->className(), VekActiveRecord::EVENT_TO_SAVE_MULTIPLE, [self::className(), 'logToSaveMultiple']);
         Event::on($owner->className(), VekActiveRecord::EVENT_SAVED_MULTIPLE, [self::className(), 'logSavedMultiple']);
     }
     parent::attach($owner);
 }
Esempio n. 3
0
 public function run()
 {
     $object = app\models\Object::getForClass($this->model->className());
     /** @var \app\modules\shop\models\AddonCategory $addonCategories */
     $addonCategories = app\components\Helper::getModelMap(AddonCategory::className(), 'id', 'name');
     /** @var app\modules\shop\models\Addon $bindedAddons */
     $bindedAddons = $this->model->bindedAddons;
     $addAddonModel = new AddAddonModel();
     return $this->render('addons-widget', ['object' => $object, 'addonCategories' => $addonCategories, 'bindedAddons' => $bindedAddons, 'model' => $this->model, 'form' => $this->form, 'addAddonModel' => $addAddonModel]);
 }
 public function search($params)
 {
     /* @var $query \yii\db\ActiveQuery */
     $query = $this->baseModel->find();
     $table_inheritance_joined = false;
     $dataProvider = new ActiveDataProvider(['query' => &$query, 'pagination' => ['pageSize' => 10], 'sort' => ['defaultOrder' => ['id' => SORT_DESC]]]);
     if (!$this->load($params)) {
         return $dataProvider;
     }
     $object = Object::getForClass($this->baseModel->className());
     $baseModelTableName = $this->baseModel->tableName();
     $eavJoinsCount = 0;
     $osvJoinsCount = 0;
     foreach ($this->propertyGroups as $groupId => $properties) {
         foreach ($properties as $key => $propertyValue) {
             /** @var \app\properties\PropertyValue $propertyValue */
             $prop = Property::findById($propertyValue->property_id);
             if (empty($this->{$prop->key}) === true && $this->{$prop->key} !== '0') {
                 continue;
             }
             // determine property storage type and join needed table if needed
             if ($prop->is_column_type_stored) {
                 if ($table_inheritance_joined === false) {
                     $table_inheritance_joined = true;
                     $query->join('INNER JOIN', $object->column_properties_table_name . ' ti', 'ti.object_model_id = ' . $baseModelTableName . '.id');
                 }
                 if ($prop->value_type === 'STRING' && $prop->property_handler_id !== 3) {
                     $query->andFilterWhere(['like', 'ti.' . $prop->key, $this->{$prop->key}]);
                 } else {
                     $query->andFilterWhere(['ti.' . $prop->key => $this->{$prop->key}]);
                 }
             } elseif ($prop->is_eav) {
                 $eavJoinsCount++;
                 $eavTableName = 'eav' . $eavJoinsCount;
                 $key = 'key' . $eavJoinsCount;
                 $query->join('INNER JOIN', "{$object->eav_table_name} {$eavTableName}", $eavTableName . '.object_model_id = ' . $baseModelTableName . ".id AND {$eavTableName}.key=:{$key}", [$key => $prop->key]);
                 if ($prop->value_type === 'STRING' && $prop->property_handler_id !== 3) {
                     $query->andFilterWhere(['like', $eavTableName . '.value', $this->{$prop->key}]);
                 } else {
                     // numeric - direct match
                     $query->andFilterWhere([$eavTableName . '.value' => $this->{$prop->key}]);
                 }
             } elseif ($prop->has_static_values) {
                 $osvJoinsCount++;
                 $osvTableName = 'osv' . $osvJoinsCount;
                 $query->join('INNER JOIN', "object_static_values {$osvTableName}", "{$osvTableName}.object_id={$object->id} AND {$osvTableName}.object_model_id={$baseModelTableName}.id");
                 // numeric - direct match
                 $query->andFilterWhere(["{$osvTableName}.property_static_value_id", $this->{$prop->key}]);
             }
         }
     }
     return $dataProvider;
 }
 /**
  * @return ActiveQuery|ISortableActiveQuery
  */
 protected function getQuery()
 {
     if ($this->query instanceof Closure) {
         $query = call_user_func_array($this->query, [$this->owner]);
     } else {
         if ($this->query instanceof ActiveQuery) {
             $query = $this->query;
         } else {
             /** @var ActiveRecord $className */
             $className = $this->owner->className();
             $query = $className::find();
         }
     }
     return $query;
 }
Esempio n. 6
0
 public function init()
 {
     $command = null;
     if ($this->onInsert) {
         Event::on(ActiveRecord::className(), ActiveRecord::EVENT_BEFORE_INSERT, function ($event) {
             $db = $event->sender->db;
             $values = $event->sender->getDirtyAttributes();
             $command = $db->createCommand()->insert($event->sender->tableName(), $values)->rawSql;
         });
     }
     if ($this->onUpdate) {
         Event::on(ActiveRecord::className(), ActiveRecord::EVENT_BEFORE_UPDATE, function ($event) {
             $db = $event->sender->db;
             $values = $event->sender->getDirtyAttributes();
             $condition = $event->sender->getOldPrimaryKey(true);
             $command = $db->createCommand()->update($event->sender->tableName(), $values, $condition)->rawSql;
         });
     }
     if ($this->onDelete) {
         Event::on(ActiveRecord::className(), ActiveRecord::EVENT_BEFORE_DELETE, function ($event) {
             $db = $event->sender->db;
             $values = $event->sender->getDirtyAttributes();
             $condition = $event->sender->getOldPrimaryKey(true);
             $command = $db->createCommand()->delete($event->sender->tableName(), $condition)->rawSql;
         });
     }
     Log::save($command);
     return parent::init();
 }
Esempio n. 7
0
 /**
  * @param \skeeks\cms\base\db\ActiveRecord $owner
  * @throws Exception
  */
 public function attach($owner)
 {
     if (!$owner instanceof \yii\db\ActiveRecord) {
         throw new Exception(\Yii::t('app', "This behavior is designed only to work with {class}", ['class' => \yii\db\ActiveRecord::className()]));
     }
     parent::attach($owner);
 }
Esempio n. 8
0
 /**
  * @param Component $component
  * @return \skeeks\sx\validate\Result
  */
 public function validate($component)
 {
     if (!$component instanceof ActiveRecord) {
         return $this->_bad(\Yii::t('app', "Object: {class} must be inherited from: {parent}", ['class' => $component->className(), 'parent' => ActiveRecord::className()]));
     }
     return !$component->isNewRecord ? $this->_ok() : $this->_bad(\Yii::t('app', "The object must already be saved"));
 }
 public function events()
 {
     // 查询事件
     // Event::on(
     //     ActiveRecord::className(),
     //     ActiveRecord::EVENT_AFTER_FIND, [$this, 'afterFind']
     // );
     // 写入事件
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, [$this, 'afterInsert']);
     // 更新事件
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_UPDATE, [$this, 'afterUpdate']);
     // 删除事件
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_DELETE, [$this, 'afterDelete']);
     // 后台登录事件
     Event::on(\service\models\LoginForm::className(), \service\models\LoginForm::EVENT_LOGIN_AFTER, [$this, 'afterBackendLogin']);
     // 后台退出事件
     Event::on(\service\models\LoginForm::className(), \service\models\LoginForm::EVENT_LOGOUT_BEFORE, [$this, 'beforeBackendLogout']);
     return [];
     // return [
     //     ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
     //     ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
     //     ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
     //     ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
     //     \backend\models\LoginForm::EVENT_LOGIN_AFTER => 'afterBackendLogin',
     //     \backend\models\LoginForm::EVENT_LOGOUT_AFTER => 'afterBackendLogout',
     // ];
 }
 public function createEnumeration()
 {
     $modelClass = $this->enumerationClass;
     $enumeration = new $modelClass();
     $enumeration->setEntity($this->owner->primaryKey, $this->owner->className());
     $enumeration->save();
     return $enumeration;
 }
Esempio n. 11
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']]);
 }
 public function run()
 {
     $cacheKey = static::className() . ':' . implode("_", [$this->model->object->id, $this->model->id, $this->viewFile, $this->limit, $this->offset, $this->thumbnailOnDemand ? '1' : '0', $this->thumbnailWidth, $this->thumbnailHeight, $this->useWatermark]);
     $result = Yii::$app->cache->get($cacheKey);
     if ($result === false) {
         if ($this->offset > 0 || !is_null($this->limit)) {
             $images = $this->model->getImages()->limit($this->limit)->offset($this->offset)->all();
         } else {
             $images = $this->model->images;
         }
         if ($this->noImageOnEmptyImages === true && count($images) === 0) {
             return $this->render('noimage', ['model' => $this->model, 'thumbnailOnDemand' => $this->thumbnailOnDemand, 'thumbnailWidth' => $this->thumbnailWidth, 'thumbnailHeight' => $this->thumbnailHeight, 'useWatermark' => $this->useWatermark, 'additional' => $this->additional]);
         }
         $result = $this->render($this->viewFile, ['model' => $this->model, 'images' => $images, 'thumbnailOnDemand' => $this->thumbnailOnDemand, 'thumbnailWidth' => $this->thumbnailWidth, 'thumbnailHeight' => $this->thumbnailHeight, 'useWatermark' => $this->useWatermark, 'additional' => $this->additional]);
         Yii::$app->cache->set($cacheKey, $result, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Image::className()), ActiveRecordHelper::getCommonTag($this->model->className())]]));
     }
     return $result;
 }
 /**
  * @param AttributeInfo $rule
  * @return AttributeRecord
  */
 public function create(AttributeInfo $rule)
 {
     $class = $rule->attributeRecordClass;
     $attributeRecord = new $class();
     /** @var AttributeRecord $attributeRecord */
     $attributeRecord->setOwner($this->owner->primaryKey, $this->owner->className());
     $attributeRecord->setAttributeName($rule->attribute);
     return $attributeRecord;
 }
Esempio n. 14
0
 /**
  * Initializes CRUD handler
  * @throws \yii\base\ErrorException
  */
 public function __construct($model = false)
 {
     if (!$model) {
         $model = $this->modelClass();
     }
     $this->model = $model;
     if (!is_subclass_of($this->model, \yii\db\ActiveRecord::className())) {
         throw new \yii\base\ErrorException('Invalid model class. Method "getModelClass" has to retrieve ActiveRecord descendant class.');
     }
 }
Esempio n. 15
0
 /**
  * Get label column name
  * @param ActiveRecord $model
  * @return mixed
  */
 public static function getLabelColumnName(ActiveRecord $model)
 {
     $class = $model->className();
     if (!isset(self::$label_columns_cache[$class])) {
         $schema = $model->getTableSchema();
         $available_names = array_intersect(static::$label_column_default, $schema->getColumnNames());
         self::$label_columns_cache[$class] = reset($available_names);
     }
     return self::$label_columns_cache[$class];
 }
 /**
  * @inheritdoc
  * @throws InvalidConfigException
  */
 public function init()
 {
     if (!static::$sourceClass) {
         throw new InvalidConfigException('Static property "sourceClass" must be contain source model class name.');
     }
     if (!is_subclass_of(static::$sourceClass, ActiveRecord::className())) {
         throw new InvalidConfigException('Model in "sourceClass" must to be inherited from "' . ActiveRecord::className() . '"');
     }
     $this->_source = new static::$sourceClass();
     parent::init();
 }
Esempio n. 17
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return array_merge(parent::rules(), [[['db', 'ns', 'tableName', 'modelClass', 'baseClass'], 'filter', 'filter' => 'trim'], [['ns', 'modelLangClass'], 'filter', 'filter' => function ($value) {
         return trim($value, '\\');
     }], [['modelLangClass'], 'filter', 'filter' => function ($value) {
         if ($value !== '' && strpos($value, '\\') === false) {
             return $this->ns . '\\' . $value;
         }
         return $value;
     }], [['db', 'ns', 'tableName', 'baseClass'], 'required'], [['db', 'modelClass'], 'match', 'pattern' => '/^\\w+$/', 'message' => 'Only word characters are allowed.'], [['ns', 'baseClass'], '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'], 'validateNamespace'], [['tableName'], 'validateTableName'], [['modelClass'], 'validateModelClass', 'skipOnEmpty' => false], [['modelLangClass'], 'validateClass', 'params' => ['extends' => BaseActiveRecord::className()]], [['baseClass'], 'validateClass', 'params' => ['extends' => ActiveRecord::className()]], [['generateRelations', 'generateLabelsFromComments'], 'boolean'], [['modelClassQuery'], 'boolean'], [['enableI18N'], 'boolean'], [['useTablePrefix'], 'boolean'], [['isLang'], 'boolean'], [['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false]]);
 }
Esempio n. 18
0
 /**
  * Get available relation choices
  * @param $relation_name
  * @return mixed
  */
 public static function getSelectChoices(ActiveRecord $model, $relation_name)
 {
     $class = $model->className();
     if (!isset(self::$relationsChoices[$class][$relation_name])) {
         self::$relationsChoices[$class][$relation_name] = [];
         $relation = $model->getRelation($relation_name, false);
         if ($relation) {
             self::$relationsChoices[$class][$relation_name] = ModelHelper::getSelectChoices(new $relation->modelClass());
         }
     }
     return self::$relationsChoices[$class][$relation_name];
 }
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->canGetProperty("events") && !empty($this->events) && is_array($this->events)) {
         foreach ($this->events as $event => $data) {
             Event::on(ActiveRecord::className(), $event, function ($closureEvent) {
                 $model = $closureEvent->sender;
                 $this->run($model, $closureEvent->data);
             }, $data);
         }
     }
 }
Esempio n. 20
0
 /**
  * @param \yii\base\Application $app
  */
 public function bootstrap($app)
 {
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
         $this->insertHistory($event->sender, self::INSERT);
     });
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_UPDATE, function ($event) {
         $this->insertHistory($event->sender, self::UPDATE);
     });
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_DELETE, function ($event) {
         $this->insertHistory($event->sender, self::DELETE);
     });
 }
Esempio n. 21
0
 /**
  * Checks if class is model
  * @param $attribute
  */
 public function validateModelClass($attribute)
 {
     /* @var $class ActiveRecord */
     $class = $this->{$attribute};
     try {
         $reflection = new \ReflectionClass($class);
         if (!$reflection->isSubclassOf(ActiveRecord::className())) {
             $this->addError($attribute, 'Class must be model');
         }
     } catch (\Exception $e) {
         $this->addError($attribute, $e->getMessage());
     }
 }
Esempio n. 22
0
 private function loadMessages($className)
 {
     if (!is_subclass_of($className, \yii\db\ActiveRecord::className())) {
         throw new \Exception("'{$className}' does not extend \\yii\\db\\ActiveRecord.");
     }
     $attributeNames = $this->getTranslatableAttributes($className);
     $messages = [];
     foreach ($attributeNames as $attributeName) {
         $query = new Query();
         $query->select($attributeName)->distinct()->from($className::tableName());
         $messages = array_merge($messages, $query->column());
     }
     return $messages;
 }
Esempio n. 23
0
 /**
  * @inheritdoc
  */
 public function bootstrap($app)
 {
     parent::bootstrap($app);
     // Subscribe on model changes
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
         CometModule::getInstance()->neat->server->broadcastEvent(get_class($event->sender), 'sendAdd', $event->sender->attributes);
     });
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_UPDATE, function ($event) {
         CometModule::getInstance()->neat->server->broadcastEvent(get_class($event->sender), 'sendUpdate', $event->sender->attributes, $event->changedAttributes + $event->sender->oldAttributes);
     });
     Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_DELETE, function ($event) {
         CometModule::getInstance()->neat->server->broadcastEvent(get_class($event->sender), 'sendRemove', $event->sender->attributes);
     });
 }
 public function testSetValue()
 {
     /** @var \PHPUnit_Framework_MockObject_MockObject|\yii\db\ActiveRecord $model */
     $model = $this->getMockBuilder(\yii\db\ActiveRecord::className())->disableOriginalConstructor()->setMethods(array('__get', 'setAttribute'))->getMock();
     $model->expects($this->any())->method('__get')->will($this->returnCallback(function ($name) {
         return '{}';
     }))->with('attributes');
     $model->expects($this->once())->method('setAttribute')->with('data', '{"a":{"b":true}}');
     $behavior = new \PetrGrishin\ArrayField\ArrayFieldBehavior();
     $behavior->owner = $model;
     $behavior->setFieldNameStorage('data');
     $behavior->loadArray();
     $behavior->setArray(array('a' => array('b' => true)));
     $this->assertEquals(array('a' => array('b' => true)), $behavior->getArray());
 }
 /**
  * Add needed validators on after find model event
  * @param Event $event
  */
 public function addValidators(Event $event)
 {
     /** @var ActiveRecord|SyncableBehavior $model */
     $model = $event->sender;
     /** @var |\yii\db\ActiveRecord $modelClass */
     $requestUpdatedAt = \Yii::$app->request->getBodyParam($model->timestampColumn);
     // unset timestampColumn value when it does not send by client for trigger required validator
     if (empty($requestUpdatedAt)) {
         $model->{$model->timestampColumn} = null;
     }
     foreach ($this->createValidators($model) as $validator) {
         $model->validators->append($validator);
     }
     // on this stage it is not needed anymore to handle this event
     Event::off(ActiveRecord::className(), ActiveRecord::EVENT_INIT, [$this, 'onActiveRecordInit']);
 }
Esempio n. 26
0
 /**
  * Deletes this notification
  */
 public function delete(\humhub\modules\user\models\User $user = null)
 {
     $condition = [];
     $condition['class'] = $this->className();
     if ($user !== null) {
         $condition['user_id'] = $user->id;
     }
     if ($this->originator !== null) {
         $condition['originator_user_id'] = $this->originator->id;
     }
     if ($this->source !== null) {
         $condition['source_pk'] = $this->source->getPrimaryKey();
         $condition['source_class'] = $this->source->className();
     }
     Notification::deleteAll($condition);
 }
Esempio n. 27
0
 /**
  * @inherit
  *
  * @param ActiveRecord $owner
  *
  * @throws ErrorException
  */
 public function attach($owner)
 {
     if (is_null($this->logClass)) {
         $this->logClass = $owner->className() . 'Log';
     }
     if (!class_exists($this->logClass, false)) {
         throw new ErrorException('Model for logging "' . $this->logClass . '" ');
     }
     if (isset($this->versionField) && !$owner->isNewRecord) {
         // die('new: '.$owner->isNewRecord);
         $owner->validators[] = Validator::createValidator('required', $owner, $this->versionField, []);
         $owner->validators[] = Validator::createValidator('string', $owner, $this->versionField, ['max' => '50']);
         $owner->validators[] = Validator::createValidator('match', $owner, $this->versionField, ['pattern' => '/^[0-9]+$/']);
     }
     parent::attach($owner);
 }
Esempio n. 28
0
 /**
  * Action which handles file uploads
  *
  * The result is an json array of all uploaded files.
  */
 public function actionUpload()
 {
     Yii::$app->response->format = 'json';
     // Object which the uploaded file(s) belongs to (optional)
     $object = null;
     $objectModel = Yii::$app->request->get('objectModel');
     $objectId = Yii::$app->request->get('objectId');
     if ($objectModel != "" && $objectId != "" && \humhub\libs\Helpers::CheckClassType($objectModel, \yii\db\ActiveRecord::className())) {
         $givenObject = $objectModel::findOne(['id' => $objectId]);
         // Check if given object is HActiveRecordContent or HActiveRecordContentAddon and can be written by the current user
         if ($givenObject !== null && ($givenObject instanceof ContentActiveRecord || $givenObject instanceof ContentAddonActiveRecord) && $givenObject->content->canWrite()) {
             $object = $givenObject;
         }
     }
     $files = array();
     foreach (UploadedFile::getInstancesByName('files') as $cFile) {
         $files[] = $this->handleFileUpload($cFile, $object);
     }
     return ['files' => $files];
 }
Esempio n. 29
0
 /**
  * Creates an activity
  *
  * @throws \yii\base\Exception
  */
 public function create()
 {
     if ($this->moduleId == "") {
         throw new \yii\base\InvalidConfigException("No moduleId given!");
     }
     if (!$this->source instanceof \yii\db\ActiveRecord) {
         throw new \yii\base\InvalidConfigException("Invalid source object given!");
     }
     $model = new Activity();
     $model->class = $this->className();
     $model->module = $this->moduleId;
     $model->content->visibility = $this->visibility;
     $model->object_model = $this->source->className();
     $model->object_id = $this->source->getPrimaryKey();
     // Automatically determine content container
     if ($this->container == null) {
         if ($this->source instanceof ContentActiveRecord || $this->source instanceof ContentAddonActiveRecord) {
             $this->container = $this->source->content->container;
             // Take visibility from Content/Addon
             $model->content->visibility = $this->source->content->visibility;
         } elseif ($this->source instanceof ContentContainerActiveRecord) {
             $this->container = $this->source;
         } else {
             throw new \yii\base\InvalidConfigException("Could not determine content container for activity!");
         }
     }
     $model->content->container = $this->container;
     // Automatically determine originator - if not set
     if ($this->originator !== null) {
         $model->content->user_id = $this->originator->id;
     } elseif ($this->source instanceof ContentActiveRecord) {
         $model->content->user_id = $this->source->content->user_id;
     } elseif ($this->source instanceof ContentAddonActiveRecord) {
         $model->content->user_id = $this->source->created_by;
     } else {
         throw new \yii\base\InvalidConfigException("Could not determine originator for activity!");
     }
     if (!$model->validate() || !$model->save()) {
         throw new \yii\base\Exception("Could not save activity!" . $model->getErrors());
     }
 }
Esempio n. 30
0
 public function bootstrap($app)
 {
     $events = [Controller::EVENT_BEFORE_ACTION];
     foreach ($events as $eventName) {
         Event::on(Controller::className(), $eventName, function ($event) use($app, $eventName) {
             Libs::mkView($app, $eventName, $event);
         });
     }
     $events = [ActiveRecord::EVENT_AFTER_INSERT, ActiveRecord::EVENT_BEFORE_UPDATE, ActiveRecord::EVENT_BEFORE_DELETE];
     $res0 = false;
     foreach ($events as $eventName) {
         Event::on(ActiveRecord::className(), $eventName, function ($event) use($app, $eventName) {
             $model = $event->sender;
             $res0 = Libs::mkVersion($app, $eventName, $model);
         });
     }
     if ($res0) {
         $events = [ActiveRecord::EVENT_AFTER_UPDATE, ActiveRecord::EVENT_AFTER_DELETE];
         foreach ($events as $eventName) {
             Event::on(ActiveRecord::className(), $eventName, function ($event) use($app, $eventName, $res0) {
                 $res = true;
                 $model = $event->sender;
                 foreach ($model->attributes as $a => $v) {
                     $m = $res0[1];
                     if ($eventName == ActiveRecord::EVENT_AFTER_UPDATE) {
                         $res = $m[$a] != $v ? false : $res;
                     } elseif ($eventName == ActiveRecord::EVENT_AFTER_DELETE) {
                         $res = $m[$a] != null ? false : $res;
                     }
                 }
                 if (!$res) {
                     $route = Route::findOne($res0[0]);
                     if ($route) {
                         $route->delete();
                     }
                 }
             });
         }
     }
 }