trigger() public static method

This method will cause invocation of event handlers that are attached to the named event for the specified class and all its parent classes.
public static trigger ( string | object $class, string $name, Event $event = null )
$class string | object the object or the fully qualified class name specifying the class-level event.
$name string the event name.
$event Event the event parameter. If not set, a default [[Event]] object will be created.
コード例 #1
0
ファイル: Less.php プロジェクト: dfatt/yii2-asset-converter
 /**
  * Parse a Less file to CSS
  */
 public function parse($src, $dst, $options)
 {
     $this->auto = isset($options['auto']) ? $options['auto'] : $this->auto;
     $variables = $this->variables;
     $assetManager = Yii::$app->assetManager;
     // Final url of the file being compiled
     $assetUrl = substr($dst, strpos($assetManager->basePath, $assetManager->baseUrl));
     $variables['published-url'] = '"' . $assetUrl . '"';
     // Root for the published folder
     $variables['published-base-url'] = '"/' . implode('/', array_slice(explode('/', ltrim($assetUrl, '/')), 0, 2)) . '"';
     $less = new \lessc();
     $less->setVariables($variables);
     // Compressed setting
     if ($this->compressed) {
         $less->setFormatter('compressed');
     }
     \Less_Parser::$default_options['compress'] = $this->compressed;
     \Less_Parser::$default_options['relativeUrls'] = $this->relativeUrls;
     // Send out pre-compile event
     $event = new \yii\base\Event();
     $this->runtime = ['sourceFile' => $src, 'destinationFile' => $dst, 'compiler' => $less];
     $event->sender = $this;
     Event::trigger($this, self::EVENT_BEFORE_COMPILE, $event);
     try {
         if ($this->auto) {
             /* @var FileCache $cacheMgr */
             $cacheMgr = Yii::createObject('yii\\caching\\FileCache');
             $cacheMgr->init();
             $cacheId = 'less#' . $dst;
             $cache = $cacheMgr->get($cacheId);
             if ($cache === false || @filemtime($dst) < @filemtime($src)) {
                 $cache = $src;
             }
             $newCache = $less->cachedCompile($cache);
             if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
                 $cacheMgr->set($cacheId, $newCache);
                 file_put_contents($dst, $newCache['compiled']);
             }
         } else {
             $less->compileFile($src, $dst);
         }
         // If needed, respect the users configuration
         if ($assetManager->fileMode !== null) {
             @chmod($dst, $assetManager->fileMode);
         }
         unset($this->less);
     } catch (\Exception $e) {
         throw new \Exception(__CLASS__ . ': Failed to compile less file : ' . $e->getMessage() . '.');
     }
 }
コード例 #2
0
 /**
  * Displays page where user can update account settings (username, email or password).
  * @return string|\yii\web\Response
  */
 public function actionAccount()
 {
     $profileModel = $this->finder->findProfileById(\Yii::$app->user->identity->getId());
     $accountModel = \Yii::createObject(SettingsForm::className());
     $this->performAjaxValidation($profileModel);
     $this->performAjaxValidation($accountModel);
     if ($profileModel->load(\Yii::$app->request->post()) && $accountModel->load(\Yii::$app->request->post())) {
         if ($profileModel->validate() && $accountModel->validate() && $profileModel->save() && $accountModel->save()) {
             Event::trigger(BaseController::class, BaseController::EVENT_MODEL_UPDATED, new MessageEvent($profileModel));
             \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'Your account has been updated'));
             return $this->refresh();
         }
     }
     return $this->render('account', ['profileModel' => $profileModel, 'accountModel' => $accountModel]);
 }
コード例 #3
0
ファイル: ListField.php プロジェクト: gromver/yii2-models
 private function fetchItems()
 {
     $items = is_array($this->items) ? $this->items : $this->invoke($this->items);
     if (isset($this->empty)) {
         $items = ArrayHelper::merge(['' => empty($this->empty) ? Yii::t('gromver.models', 'Select...') : $this->empty], $items);
     }
     if (isset($this->editable) && !isset($this->multiple) && ($value = $this->getValue()) && !array_key_exists($value, $items)) {
         $items[$value] = $value;
     }
     if ($this->getModel() instanceof ObjectModelInterface) {
         preg_match_all('/\\[([a-zA-Z]\\w*)\\]/', Html::getInputName($this->getModel(), $this->getAttribute()), $matches);
         $event = new ListItemsEvent(['items' => $items, 'model' => $this->getModel()->getObjectModel(), 'attribute' => end($matches[1])]);
         Event::trigger(static::className(), self::EVENT_FETCH_ITEMS, $event);
         return $event->items;
     }
     return $items;
 }
コード例 #4
0
ファイル: Widget.php プロジェクト: SimonBaeumer/humhub
 /**
  * Creates a widget instance and runs it.
  * 
  * The widget rendering result is returned by this method.
  * @param array $config name-value pairs that will be used to initialize the object properties
  * @return string the rendering result of the widget.
  * @throws \Exception
  */
 public static function widget($config = [])
 {
     if (!isset($config['class'])) {
         $config['class'] = get_called_class();
     }
     Event::trigger(self::className(), self::EVENT_CREATE, new WidgetCreateEvent($config));
     ob_start();
     ob_implicit_flush(false);
     try {
         /* @var $widget Widget */
         $widget = Yii::createObject($config);
         $out = $widget->run();
     } catch (\Exception $e) {
         // close the output buffer opened above if it has not been closed already
         if (ob_get_level() > 0) {
             ob_end_clean();
         }
         throw $e;
     }
     $widget->trigger(self::EVENT_AFTER_RUN);
     return ob_get_clean() . $out;
 }
コード例 #5
0
 /**
  * @param $id
  * @param $rating
  */
 private function _createRatingAddEvent($id, $rating)
 {
     $event = new RatingAddEvent();
     $event->recordId = $id;
     $event->rating = $rating;
     $event->userId = \Yii::$app->user->id;
     Event::trigger(RatingModule::className(), RatingModule::EVENT_RATING_ADD, $event);
 }
コード例 #6
0
ファイル: Component.php プロジェクト: xinyifuyun/code-yii
 /**
  * 触发事件(对象的触发)
  * @param $name
  */
 public function trigger($name, Event $event = null)
 {
     $this->ensureBehaviors();
     if (!empty($this->_events[$name])) {
         //存在该事件名称
         if ($event === null) {
             $event = new Event();
         }
         if ($event->sender === null) {
             $event->sender = $this;
         }
         $event->handled = false;
         $event->name = $name;
         foreach ($this->_events[$name] as $handler) {
             $event->data = $handler[1];
             call_user_func($handler[0], $event);
             if ($event->handled) {
                 return;
             }
         }
     }
     /**
      * 触发该对象的类的事件,如果该类的每个对象都需要绑定该事件,则把该事件绑定到该类上面,当触发该对象的事件时,则会自动触发该对象的类事件,避免每个类都需要进行绑定
      */
     Event::trigger($this, $name, $event);
 }
コード例 #7
0
ファイル: Activity.php プロジェクト: frenzelgmbh/cm-activity
 /**
  * changed beforeSave as I want to trigger an individual event for this
  * @param  [type] $insert [description]
  * @return boolean         [description]
  */
 public function beforeSave($insert)
 {
     if (parent::beforeSave($insert)) {
         Event::trigger(self::className(), self::EVENT_ACTIVITY_UPDATE, new Event(['sender' => $this]));
         \Yii::trace('The Event ' . self::EVENT_ACTIVITY_UPDATE . ' should be fired, pls. check!');
         $nextDate = new DateTime($this->next_at);
         $this->next_at = $nextDate->format('U');
         if (is_null($this->next_by)) {
             $this->next_by = $this->created_by;
         }
         return true;
     }
     return false;
 }
コード例 #8
0
ファイル: CartController.php プロジェクト: lzpfmh/dotplant2
 /**
  * @return array
  * @throws NotFoundHttpException
  * @throws \Exception
  */
 public function actionClear()
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     $result = [];
     $order = $this->loadOrder();
     if (null === $order->stage || true === $order->getImmutability(Order::IMMUTABLE_USER)) {
         throw new BadRequestHttpException();
     }
     $products = array_reduce($order->items, function ($res, $item) {
         $res[] = ['model' => $item->product, 'quantity' => $item->quantity, 'orderItem' => $item];
         return $res;
     }, []);
     /** @var OrderItem $item */
     foreach ($order->items as $item) {
         $item->delete();
     }
     Order::clearStaticOrder();
     $order = $this->loadOrder();
     $result['success'] = $order->calculate(true);
     $event = new CartActionEvent($order, $products);
     Event::trigger($this, self::EVENT_ACTION_CLEAR, $event);
     $result['additional'] = $event->getEventData();
     $result['products'] = $this->productsModelsToArray($products);
     return $result;
 }
コード例 #9
0
 public function test()
 {
     Event::trigger(TestEvent::className(), self::TEST);
 }
コード例 #10
0
 /**
  * Triggers an event.
  * This method represents the happening of an event. It invokes
  * all attached handlers for the event including class-level handlers.
  * @param string $name the event name
  * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
  */
 public function trigger($name, Event $event = null)
 {
     // 保证 behaviors 都加载进来了
     $this->ensureBehaviors();
     if (!empty($this->_events[$name])) {
         // 构建Event对象,为传入到handler函数中做准备
         if ($event === null) {
             $event = new Event();
         }
         if ($event->sender === null) {
             $event->sender = $this;
         }
         $event->handled = false;
         $event->name = $name;
         foreach ($this->_events[$name] as $handler) {
             // 给event的data属性赋值
             $event->data = $handler[1];
             // handler的函数中传入了一个Event对象
             call_user_func($handler[0], $event);
             // stop further handling if the event is handled
             // 事件是否被handle,当handled被设置为true时,执行到这个event的时候,会停止,并忽略剩下的event
             if ($event->handled) {
                 return;
             }
         }
     }
     // invoke class-level attached handlers
     // 触发class级别的handler
     Event::trigger($this, $name, $event);
 }
コード例 #11
0
 /**
  * @param $recordId
  * @param $type
  */
 private function _createComplaintAddEvent($recordId, $type)
 {
     $event = new ComplaintAddEvent();
     $event->recordId = $recordId;
     $event->type = $type;
     $event->userId = \Yii::$app->user->id;
     $event->total = Complaint::find()->where(['record_id' => $recordId, 'type' => $type])->count();
     Event::trigger(ComplainModule::className(), ComplainModule::EVENT_COMPLAINT_ADD, $event);
 }
コード例 #12
0
ファイル: CommentWidget.php プロジェクト: MaizerGomes/openbay
 /**
  *
  */
 private function _createCommentAddEvent()
 {
     $event = new CommentAddEvent();
     $event->recordId = $this->_model->record_id;
     $event->userId = $this->_model->user_id;
     Event::trigger(CommentModule::className(), CommentModule::EVENT_COMMENT_ADD, $event);
 }
コード例 #13
0
 public function actionProcessConfigControl()
 {
     $request = \Yii::$app->request;
     $actionType = $request->post('actionType');
     $response = ['isSuccessful' => true];
     try {
         $group = new ProcessConfig($request->post('groupName'));
         if ($group->hasMethod($actionType)) {
             $group->{$actionType}();
         }
         Event::trigger(Supervisor::className(), Supervisor::EVENT_CONFIG_CHANGED);
     } catch (SupervisorException $error) {
         $response = ['isSuccessful' => false, 'error' => $error->getMessage()];
     }
     return $response;
 }
コード例 #14
0
ファイル: Hooks.php プロジェクト: AtuinCMS/engine
 /**
  * Triggers an event.
  * This method represents the happening of an event. It invokes
  * all attached handlers for the event including class-level handlers.
  * @param string $name the event name
  * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
  * @return array|mixed
  */
 public function trigger($name, Event $event = null)
 {
     $return_data = [];
     if (!empty($this->_events[$name])) {
         if ($event === null) {
             $event = new Event();
         }
         if ($event->sender === null) {
             $event->sender = $this;
         }
         $event->handled = false;
         $event->name = $name;
         foreach ($this->_events[$name] as $handler) {
             $event->data = $handler[1];
             $return_data[] = call_user_func($handler[0], $event);
             // stop further handling if the event is handled
             if ($event->handled) {
                 break;
             }
         }
     }
     // invoke class-level attached handlers
     // but won't return anything in this case...
     Event::trigger($this, $name, $event);
     return $return_data;
 }
コード例 #15
0
ファイル: Component.php プロジェクト: hucongyang/woaipai
 /**
  * Triggers an event.
  * This method represents the happening of an event. It invokes
  * all attached handlers for the event including class-level handlers.
  * @param string $name the event name
  * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
  */
 public function trigger($name, Event $event = null)
 {
     $this->ensureBehaviors();
     if (!empty($this->_events[$name])) {
         if ($event === null) {
             $event = new Event();
         }
         if ($event->sender === null) {
             $event->sender = $this;
         }
         $event->handled = false;
         $event->name = $name;
         foreach ($this->_events[$name] as $handler) {
             // 遍历handler数组,并依次调用
             $event->data = $handler[1];
             call_user_func($handler[0], $event);
             // 使用 PHP 的call_user_func调用handler
             // stop further handling if the event is handled     // 如果在某一handler中,将$event->handled 设为true,
             if ($event->handled) {
                 // 就不再调用后续的handler
                 return;
             }
         }
     }
     // invoke class-level attached handlers
     Event::trigger($this, $name, $event);
     // 触发类一级的事件
 }
コード例 #16
0
 /**
  * Updates an existing User model.
  * If update is successful, the browser will be redirected to the 'index' page.
  * @param  integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $user = $this->findModel($id);
     $user->scenario = 'update';
     $profile = $this->finder->findProfileById($id);
     $r = \Yii::$app->request;
     $this->performAjaxValidation([$user, $profile]);
     if ($user->load($r->post()) && $profile->load($r->post()) && $user->save() && $profile->save()) {
         Event::trigger(BaseController::class, BaseController::EVENT_MODEL_UPDATED, new MessageEvent($profile));
         $this->trigger(BaseController::EVENT_MODEL_UPDATED, new MessageEvent($user));
         \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been updated'));
         return $this->redirect(['index']);
     }
     return $this->render('update', ['user' => $user, 'profile' => $profile, 'module' => $this->module]);
 }
コード例 #17
0
 public function eat()
 {
     echo 'This is person eating.<br><br>';
     /* $this->trigger(self::ACTION_EAT);*/
     Event::trigger(Person::className(), self::ACTION_EAT);
 }
コード例 #18
0
ファイル: Component.php プロジェクト: hakudjin/yii2
 /**
  * Triggers an event.
  * This method represents the happening of an event. It invokes
  * all attached handlers for the event including class-level handlers.
  * @param string $name the event name
  * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
  */
 public function trigger($name, Event $event = null)
 {
     $this->ensureBehaviors();
     if (!empty($this->_events[$name])) {
         if ($event === null) {
             $event = new Event();
         }
         if ($event->sender === null) {
             $event->sender = $this;
         }
         $event->handled = false;
         $event->name = $name;
         foreach ($this->_events[$name] as $handler) {
             $event->data = $handler[1];
             call_user_func($handler[0], $event);
             // stop further handling if the event is handled
             if ($event->handled) {
                 return;
             }
         }
     }
     // invoke class-level attached handlers
     Event::trigger($this, $name, $event);
 }
コード例 #19
0
 /**
  * This static method is called at the end of work of [[saveMultiple()]] method and after calling [[afterSaveMultiple($insert)]] methods for each models saved.
  * The default implementation will trigger an [[EVENT_SAVED_MULTIPLE]]
  * When overriding this method, make sure you call the parent implementation so that
  * the event is triggered.
  */
 public static function savedMultiple()
 {
     $event = new ModelEvent(['sender' => static::className()]);
     Event::trigger(static::className(), self::EVENT_SAVED_MULTIPLE, $event);
     static::clearSaveMultiple();
 }
コード例 #20
-1
 protected function initDefaultButtons()
 {
     parent::initDefaultButtons();
     $this->buttons['custom'] = function ($url, $model) {
         $event = new CustomActionEvent(['module' => \Yii::$app->controller->getUniqueId(), 'model' => $model]);
         Event::trigger($this, self::EVENT_CUSTOM_ACTION, $event);
         return implode(' ', $event->buttons);
     };
 }