Event PHP Class Code Examples

This page contains top rated real world PHP examples of class Event extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: AddTrait.php Project: jxav/cakephp-api
0
 /**
  * __addAction
  *
  * Execute action for the add-action
  *
  * @return void
  */
 private function __addAction()
 {
     $controller = $this->Controller;
     $model = $this->getModel();
     $entity = $model->newEntity($controller->request->data);
     // add.beforeSave event
     if ($this->config('add.beforeSave')) {
         $controller->eventManager()->on('Controller.Api.beforeSave', [$controller, $this->config('add.beforeSave')]);
         $event = new \Cake\Event\Event('Controller.Api.beforeSave', $this, ['entity' => $entity]);
         $eventManager = $controller->eventManager();
         $eventManager->dispatch($event);
         if (!is_null($event->result['entity'])) {
             $entity = $event->result['entity'];
         }
     }
     if ($model->save($entity)) {
         $data = $model->get($entity->get('id'));
         $this->setStatusCode(200);
     } else {
         $data = $entity->errors();
         $this->setStatusCode(400);
     }
     // set data variable
     if (!$this->_viewVarExists('data')) {
         $controller->set('data', $data);
     }
     // add.aftersave event
     if ($this->config('add.afterSave')) {
         $controller->eventManager()->on('Controller.Api.afterSave', [$controller, $this->config('add.afterSave')]);
         $event = new \Cake\Event\Event('Controller.Api.afterSave', $this, ['entity' => $entity]);
         $eventManager = $controller->eventManager();
         $eventManager->dispatch($event);
     }
 }
Example #2
Show file File: api.php Project: wAmpIre/netmon
0
 private function event()
 {
     if ($this->get_request_method() == "GET" && isset($this->_request['id'])) {
         $event = new Event((int) $this->_request['id']);
         if ($event->fetch()) {
             $domxmldata = $event->getDomXMLElement($this->domxml);
             $this->response($this->finishxml($domxmldata), 200);
         } else {
             $this->error_code = 1;
             $this->error_message = "Event not found";
             $this->response($this->finishxml(), 404);
         }
     } elseif ($this->get_request_method() == "POST" or $this->get_request_method() == "GET" && !isset($this->_request['id']) && count($_GET) > 1) {
         if ($this->isApiKeyValid($this->api_key)) {
             $data = !empty($_POST) ? $_POST : $_GET;
             $event = new Event(false, false, $this->_request['object'], (int) $this->_request['object_id'], $this->_request['action'], $this->_request['data']);
             $event_id = $event->store();
             if ($event_id != false) {
                 header('Location: ' . ConfigLine::configByName('url_to_netmon') . '/api/rest/event/' . $event_id);
             } else {
                 $this->authentication = false;
                 $this->error_code = 2;
                 $this->error_message = "The Event could not be created. Your request seems to miss some data.";
                 $this->response($this->finishxml(), 400);
             }
         } else {
             $this->error_code = 2;
             $this->error_message = "The api_key is not valid.";
             $this->response($this->finishxml(), 401);
         }
     } else {
         $this->response('', 406);
     }
 }
Example #3
Show file File: ForumPostsTable.php Project: edukondaluetg/Xeta
0
 /**
  * AfterSave callback.
  *
  * @param \Cake\Event\Event $event   The afterSave event that was fired.
  * @param \Cake\ORM\Entity $entity  The entity that was saved.
  * @param \ArrayObject $options The options passed to the callback.
  *
  * @return bool
  */
 public function afterSave(Event $event, Entity $entity, ArrayObject $options)
 {
     if ($entity->isNew()) {
         $this->eventManager()->attach(new Badges());
         $event = new Event('Model.ForumPosts.reply', $this, ['post' => $entity]);
         $this->eventManager()->dispatch($event);
     }
     return true;
 }
Example #4
Show file File: Document.php Project: agolomazov/php-mongo
0
 /**
  * Manually trigger defined events
  * @param string $eventName event name
  * @return \Sokil\Mongo\Event
  */
 public function triggerEvent($eventName, Event $event = null)
 {
     if (!$event) {
         $event = new Event();
     }
     $event->setTarget($this);
     return $this->eventDispatcher->dispatch($eventName, $event);
 }
Example #5
Show file File: UserToolComponent.php Project: nielin/cakephp-user-tools
0
 /**
  * Login
  *
  * @var array
  * @return bool
  */
 public function login($options = [])
 {
     $options = Hash::merge($this->_config['login'], $options);
     $entity = $this->UserTable->newEntity([], ['validate' => false]);
     if ($this->request->is('post')) {
         $entity = $this->UserTable->patchEntity($entity, $this->request->data, ['validate' => false]);
         $event = new Event('User.beforeLogin', $this, ['options' => $options, 'entity' => $entity]);
         $this->eventManager()->dispatch($event);
         if ($event->isStopped()) {
             return $event->result;
         }
         $Auth = $this->_getAuthObject();
         $user = $Auth->identify();
         if ($user) {
             $event = new Event('User.afterLogin', $this, ['options' => $options]);
             $this->eventManager()->dispatch($event);
             if ($event->isStopped()) {
                 return $event->result;
             }
             $Auth->setUser($user);
             if ($options['successRedirectUrl'] === null) {
                 $options['successRedirectUrl'] = $Auth->redirectUrl();
             }
             $this->handleFlashAndRedirect('success', $options);
             return true;
         } else {
             $this->handleFlashAndRedirect('error', $options);
         }
     }
     if ($options['setEntity']) {
         $this->_controller->set('userEntity', $entity);
     }
     return false;
 }
Example #6
Show file File: ContainerAwareEventDispatcher.php Project: akapivo/www.dmi.be
0
 /**
  * {@inheritdoc}
  */
 public function dispatch($event_name, Event $event = NULL)
 {
     if ($event === NULL) {
         $event = new Event();
     }
     $event->setDispatcher($this);
     $event->setName($event_name);
     if (isset($this->listeners[$event_name])) {
         // Sort listeners if necessary.
         if (isset($this->unsorted[$event_name])) {
             krsort($this->listeners[$event_name]);
             unset($this->unsorted[$event_name]);
         }
         // Invoke listeners and resolve callables if necessary.
         foreach ($this->listeners[$event_name] as $priority => &$definitions) {
             foreach ($definitions as $key => &$definition) {
                 if (!isset($definition['callable'])) {
                     $definition['callable'] = [$this->container->get($definition['service'][0]), $definition['service'][1]];
                 }
                 $definition['callable']($event, $event_name, $this);
                 if ($event->isPropagationStopped()) {
                     return $event;
                 }
             }
         }
     }
     return $event;
 }
Example #7
Show file File: MapReduceTest.php Project: Wizkunde/mongodb-odm
0
 public function testMapReduce2()
 {
     $user = new User();
     $user->setUsername('bob');
     $event1 = new Event();
     $event1->setUser($user);
     $event1->setType('sale');
     $event1->setTitle('Test 1');
     $event2 = new Event();
     $event2->setUser($user);
     $event2->setType('sale');
     $event2->setTitle('Test 2');
     $event3 = new Event();
     $event3->setUser($user);
     $event3->setType('sale');
     $event3->setTitle('Test 2');
     $this->dm->persist($user);
     $this->dm->persist($event1);
     $this->dm->persist($event2);
     $this->dm->persist($event3);
     $this->dm->flush();
     $qb = $this->dm->createQueryBuilder('Documents\\Event')->field('type')->equals('sale')->map('function() { emit(this.user.$id, 1); }')->reduce("function(k, vals) {\n                var sum = 0;\n                for (var i in vals) {\n                    sum += vals[i];\n                }\n                return sum;\n            }");
     $query = $qb->getQuery();
     $user2 = $query->getSingleResult();
     $this->assertEquals($user->getId(), (string) $user2['_id']);
     $this->assertEquals(3, $user2['value']);
 }
Example #8
Show file File: SortableTest.php Project: bantudevelopment/polysmis
0
 /**
  * @test
  */
 public function shouldGroupByDateTimeValue()
 {
     $event1 = new Event();
     $event1->setDateTime(new \DateTime("2012-09-15 00:00:00"));
     $event1->setName("Event1");
     $this->em->persist($event1);
     $event2 = new Event();
     $event2->setDateTime(new \DateTime("2012-09-15 00:00:00"));
     $event2->setName("Event2");
     $this->em->persist($event2);
     $event3 = new Event();
     $event3->setDateTime(new \DateTime("2012-09-16 00:00:00"));
     $event3->setName("Event3");
     $this->em->persist($event3);
     $this->em->flush();
     $event4 = new Event();
     $event4->setDateTime(new \DateTime("2012-09-15 00:00:00"));
     $event4->setName("Event4");
     $this->em->persist($event4);
     $event5 = new Event();
     $event5->setDateTime(new \DateTime("2012-09-16 00:00:00"));
     $event5->setName("Event5");
     $this->em->persist($event5);
     $this->em->flush();
     $this->assertEquals(0, $event1->getPosition());
     $this->assertEquals(1, $event2->getPosition());
     $this->assertEquals(0, $event3->getPosition());
     $this->assertEquals(2, $event4->getPosition());
     $this->assertEquals(1, $event5->getPosition());
 }
Example #9
Show file File: ImportTask.php Project: transomdesign/transom-craft-starter
0
 /**
  * Run step.
  *
  * @param int $step
  *
  * @return bool
  */
 public function runStep($step)
 {
     // Get settings
     $settings = $this->getSettings();
     // Backup?
     if ($settings->backup && !$step) {
         // Do the backup
         $backup = new DbBackup();
         $this->backupFile = $backup->run();
     }
     // Open file
     $data = craft()->import->data($settings->file);
     // On start
     if (!$step) {
         // Fire an "onImportStart" event
         $event = new Event($this, array('settings' => $settings));
         craft()->import->onImportStart($event);
     }
     // Check if row exists
     if (isset($data[$step])) {
         // Import row
         craft()->import->row($step, $data[$step], $settings);
     }
     // When finished
     if ($step == $settings->rows - 1) {
         // Finish
         craft()->import->finish($settings, $this->backupFile);
         // Fire an "onImportFinish" event
         $event = new Event($this, array('settings' => $settings));
         craft()->import->onImportFinish($event);
     }
     return true;
 }
Example #10
Show file File: OAuthController.php Project: laughingpain/oauth-server
0
 /**
  * @return \Cake\Network\Response|void
  * @throws \League\OAuth2\Server\Exception\InvalidGrantException
  */
 public function authorize()
 {
     if (!($authParams = $this->OAuth->checkAuthParams('authorization_code'))) {
         return;
     }
     if (!$this->Auth->user()) {
         $query = $this->request->query;
         $query['redir'] = 'oauth';
         return $this->redirect(['plugin' => false, 'controller' => 'Users', 'action' => 'login', '?' => $query]);
     }
     $event = new Event('OAuthServer.beforeAuthorize', $this);
     EventManager::instance()->dispatch($event);
     $serializeKeys = [];
     if (is_array($event->result)) {
         $this->set($event->result);
         $serializeKeys = array_keys($event->result);
     }
     if ($this->request->is('post') && $this->request->data['authorization'] === 'Approve') {
         $ownerModel = isset($this->request->data['owner_model']) ? $this->request->data['owner_model'] : 'Users';
         $ownerId = isset($this->request->data['owner_id']) ? $this->request->data['owner_id'] : $this->Auth->user('id');
         $redirectUri = $this->OAuth->Server->getGrantType('authorization_code')->newAuthorizeRequest($ownerModel, $ownerId, $authParams);
         $event = new Event('OAuthServer.afterAuthorize', $this);
         EventManager::instance()->dispatch($event);
         return $this->redirect($redirectUri);
     } elseif ($this->request->is('post')) {
         $event = new Event('OAuthServer.afterDeny', $this);
         EventManager::instance()->dispatch($event);
         $error = new AccessDeniedException();
         $redirectUri = RedirectUri::make($authParams['redirect_uri'], ['error' => $error->errorType, 'message' => $error->getMessage()]);
         return $this->redirect($redirectUri);
     }
     $this->set('authParams', $authParams);
     $this->set('user', $this->Auth->user());
     $this->set('_serialize', array_merge(['user', 'authParams'], $serializeKeys));
 }
Example #11
Show file File: EventDispatcher.php Project: shabbirvividads/magento2
0
 /**
  * Dispatch a script event.
  *
  * @param string       $eventName The constant in ScriptEvents
  * @param Script\Event $event
  */
 public function dispatchScript($eventName, Script\Event $event = null)
 {
     if (null == $event) {
         $event = new Script\Event($eventName, $this->composer, $this->io);
     }
     $this->doDispatch($event);
 }
Example #12
Show file File: Component.php Project: glcode/yii2-2.0.3-annotated
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);
 }
Example #13
Show file File: AppController.php Project: jxav/cakephp-cakeadmin
0
 public function beforeRender(Event $event)
 {
     $this->set('authUser', $this->authUser);
     $this->set('title', $this->name);
     $event = new Event('CakeAdmin.Controller.beforeRender', $this);
     EventManager::instance()->dispatch($event);
 }
Example #14
Show file File: BaseTraitTest.php Project: OrigamiStructures/users
0
 /**
  * mock utility
  *
  * @param Event $event event
  * @return void
  */
 protected function _mockDispatchEvent(Event $event = null)
 {
     if (is_null($event)) {
         $event = new Event('cool-name-here');
     }
     $this->Trait->expects($this->any())->method('dispatchEvent')->will($this->returnValue($event));
 }
Example #15
Show file File: comment.php Project: DarneoStudio/bitrix
0
 public function moderate($show)
 {
     if ($this->message === null) {
         $this->errorCollection->addOne(new Error(Loc::getMessage("FORUM_CM_ERR_COMMENT_IS_LOST3"), self::ERROR_MESSAGE_IS_NULL));
     } else {
         $fields = array("APPROVED" => $show ? "Y" : "N");
         if ($this->message["ID"] == $fields["APPROVED"] || ($mid = \CForumMessage::Update($this->message["ID"], $fields)) > 0) {
             $this->setComment($this->message["ID"]);
             /***************** Events ******************************************/
             /***************** Event onMessageModerate *************************/
             $event = new Event("forum", "onMessageModerate", array($this->message["ID"], $show ? "SHOW" : "HIDE", $this->message, $this->topic));
             $event->send();
             /***************** Events OnAfterCommentUpdate *********************/
             $fields = array($this->entity->getType(), $this->entity->getId(), array("TOPIC_ID" => $this->topic["ID"], "MESSAGE_ID" => $this->message["ID"], "MESSAGE" => $this->getComment(), "ACTION" => $show ? "SHOW" : "HIDE", "PARAMS" => $fields));
             $event = new Event("forum", "OnAfterCommentUpdate", $fields);
             $event->send();
             /***************** Events OnCommentModerate ************************/
             $event = new Event("forum", "OnCommentModerate", $fields);
             $event->send();
             /***************** /Events *****************************************/
             $res = serialize(array("ID" => $this->message["ID"], "AUTHOR_NAME" => $this->message["AUTHOR_NAME"], "POST_MESSAGE" => $this->message["POST_MESSAGE"], "TITLE" => $this->topic["TITLE"], "TOPIC_ID" => $this->topic["ID"], "FORUM_ID" => $this->topic["FORUM_ID"]));
             \CForumMessage::SendMailMessage($this->message["ID"], array(), false, $show ? "NEW_FORUM_MESSAGE" : "EDIT_FORUM_MESSAGE");
             \CForumEventLog::Log("message", $show ? "approve" : "unapprove", $this->message["ID"], $res);
             return $this->getComment();
         } else {
             $text = Loc::getMessage("FORUM_CM_ERR_MODERATE");
             if (($ex = $this->getApplication()->getException()) && $ex) {
                 $text = $ex->getString();
             }
             $this->errorCollection->addOne(new Error($text, self::ERROR_PARAMS_MESSAGE));
         }
     }
     return false;
 }
Example #16
Show file File: object.php Project: DarneoStudio/bitrix
0
 /**
  * Usage: only if you want to update "unnormalized" attributes (symlink object)
  * @param array $attributes
  * @param array $filter
  * @return \Bitrix\Main\Entity\Result
  * @internal
  */
 public static function updateAttributesByFilter(array $attributes, array $filter)
 {
     $entity = static::getEntity();
     $result = new Result();
     $event = new Event($entity, self::EVENT_ON_BEFORE_UPDATE_ATTR_BY_FILTER, array('fields' => $attributes, 'filter' => $filter));
     $event->send();
     $event->getErrors($result);
     $attributes = $event->mergeFields($attributes);
     //static::checkFields($result, null, $attributes);
     if (!$result->isSuccess(true)) {
         return $result;
     }
     $event = new Event($entity, self::EVENT_ON_UPDATE_ATTR_BY_FILTER, array('fields' => $attributes, 'filter' => $filter));
     $event->send();
     $connection = Main\Application::getConnection();
     $helper = $connection->getSqlHelper();
     $tableName = static::getEntity()->getDBTableName();
     $update = $helper->prepareUpdate($tableName, $attributes);
     $filterAttributes = array();
     foreach ($filter as $k => $v) {
         $filterAttributes[] = $helper->prepareAssignment($tableName, $k, $v);
     }
     $where = implode(' AND ', $filterAttributes);
     $sql = "UPDATE " . $tableName . " SET " . $update[0] . " WHERE " . $where;
     $connection->queryExecute($sql, $update[1]);
     $event = new Event($entity, self::EVENT_ON_AFTER_UPDATE_ATTR_BY_FILTER, array('fields' => $attributes, 'filter' => $filter));
     $event->send();
     return $result;
 }
Example #17
Show file File: datamanager.php Project: Satariall/izurit
0
 /**
  * Deletes row in entity table by primary key
  *
  * @param mixed $primary
  *
  * @return DeleteResult
  *
  * @throws \Exception
  */
 public static function delete($primary)
 {
     global $USER_FIELD_MANAGER;
     // check primary
     static::normalizePrimary($primary);
     static::validatePrimary($primary);
     $entity = static::getEntity();
     $result = new DeleteResult();
     try {
         //event before delete
         $event = new Event($entity, self::EVENT_ON_BEFORE_DELETE, array("id" => $primary));
         $event->send();
         $event->getErrors($result);
         //event before delete (modern with namespace)
         $event = new Event($entity, self::EVENT_ON_BEFORE_DELETE, array("id" => $primary, "primary" => $primary), true);
         $event->send();
         $event->getErrors($result);
         // return if any error
         if (!$result->isSuccess(true)) {
             return $result;
         }
         //event on delete
         $event = new Event($entity, self::EVENT_ON_DELETE, array("id" => $primary));
         $event->send();
         //event on delete (modern with namespace)
         $event = new Event($entity, self::EVENT_ON_DELETE, array("id" => $primary, "primary" => $primary), true);
         $event->send();
         // delete
         $connection = $entity->getConnection();
         $helper = $connection->getSqlHelper();
         $tableName = $entity->getDBTableName();
         $replacedPrimary = static::replaceFieldName($primary);
         $id = array();
         foreach ($replacedPrimary as $k => $v) {
             $id[] = $helper->prepareAssignment($tableName, $k, $v);
         }
         $where = implode(' AND ', $id);
         $sql = "DELETE FROM " . $tableName . " WHERE " . $where;
         $connection->queryExecute($sql);
         // delete uf data
         if (static::getEntity()->getUfId()) {
             $USER_FIELD_MANAGER->delete(static::getEntity()->getUfId(), end($primary));
         }
         //event after delete
         $event = new Event($entity, self::EVENT_ON_AFTER_DELETE, array("id" => $primary));
         $event->send();
         //event after delete (modern with namespace)
         $event = new Event($entity, self::EVENT_ON_AFTER_DELETE, array("id" => $primary, "primary" => $primary), true);
         $event->send();
     } catch (\Exception $e) {
         // check result to avoid warning
         $result->isSuccess();
         throw $e;
     }
     return $result;
 }
Frequently Used Methods