예제 #1
0
파일: Create.php 프로젝트: t4web/base
 protected function trigger(EntityInterface $entity)
 {
     if (!$this->eventManager) {
         return;
     }
     $this->eventManager->trigger('create:post', $this, compact('entity'));
 }
예제 #2
0
 /**
  * {@inheritDoc}
  */
 public function trigger(EventInterface $event)
 {
     if ($event instanceof ZendEventInterface) {
         $this->eventManager->trigger($event);
     }
     return $this;
 }
예제 #3
0
파일: Delete.php 프로젝트: t4web/base
 protected function trigger($event, $values, $nameForReturnValue)
 {
     if (!$this->eventManager) {
         return;
     }
     $this->eventManager->trigger($event, $this, array($nameForReturnValue => $values));
 }
예제 #4
0
파일: Sender.php 프로젝트: t4web/mail
 public function send($to, $templateName, array $data = [])
 {
     $template = $this->templateBuilder->get($templateName);
     $message = $this->mailAssembler->assemble($to, $template, $data);
     $this->mailTransport->send($message);
     $event = new Event('mail-send:post', $this, ['to' => $to, 'template' => $template, 'message' => $message, 'data' => $data]);
     $this->eventManager->trigger($event);
 }
예제 #5
0
파일: Manager.php 프로젝트: qshurick/event
 /**
  * @param EventInterface    $event
  * @param null|callable     $callback
  * @throws \Exception
  */
 public function trigger($event, $callback = null)
 {
     try {
         $this->manager->trigger($event, null, null, $callback);
     } catch (\Exception $ex) {
         $this->logger->error($ex);
         throw $ex;
     }
 }
예제 #6
0
 /**
  * 
  * @param ClassScanner[] $classes
  */
 public function parse($classes)
 {
     $config = array();
     foreach ($classes as $class) {
         $classAnnotationHolder = $this->parseClass($class);
         $event = new ParseEvent(ParseEvent::EVENT_CLASS_PARSED, $classAnnotationHolder, array('config' => $this->config));
         $this->eventManager->trigger($event);
         $config = ArrayUtils::merge($config, $event->getResult());
     }
     return $config;
 }
예제 #7
0
 public function inAction()
 {
     if (!$this->getRequest()->isPost()) {
         // just show the login form
         return array();
     }
     $username = $this->params()->fromPost('username');
     $password = $this->params()->fromPost('password');
     $auth = $this->serviceLocator->get('auth');
     $authAdapter = $auth->getAdapter();
     // below we pass the username and the password to the authentication adapter for verification
     $authAdapter->setIdentity($username);
     $authAdapter->setCredential($password);
     // here we do the actual verification
     $result = $auth->authenticate();
     $isValid = $result->isValid();
     if ($isValid) {
         // upon successful validation the getIdentity method returns
         // the user entity for the provided credentials
         $user = $result->getIdentity();
         // @todo: upon successful validation store additional information about him in the auth storage
         $this->flashmessenger()->addSuccessMessage(sprintf('Welcome %s. You are now logged in.', $user->getName()));
         return $this->redirect()->toRoute('user/default', array('controller' => 'account', 'action' => 'me'));
     } else {
         $event = new EventManager('user');
         $event->trigger('log-fail', $this, array('username' => $username));
         return array('errors' => $result->getMessages());
     }
 }
예제 #8
0
 public function addAction()
 {
     // The annotation builder help us create a form from the annotations in the user entity.
     $builder = new AnnotationBuilder();
     $entity = $this->serviceLocator->get('user-entity');
     $form = $builder->createForm($entity);
     $form->add(array('name' => 'password_verify', 'type' => 'Zend\\Form\\Element\\Password', 'attributes' => array('placeholder' => 'Verify Password Here...', 'required' => 'required'), 'options' => array('label' => 'Verify Password')), array('priority' => $form->get('password')->getOption('priority')));
     // This is the special code that protects our form being submitted from automated scripts
     $form->add(array('name' => 'csrf', 'type' => 'Zend\\Form\\Element\\Csrf'));
     // This is the submit button
     $form->add(array('name' => 'submit', 'type' => 'Zend\\Form\\Element\\Submit', 'attributes' => array('value' => 'Submit', 'required' => 'false')));
     // We bind the entity to the user. If the form tries to read/write data from/to the entity
     // it will use the hydrator specified in the entity to achieve this. In our case we use ClassMethods
     // hydrator which means that reading will happen calling the getter methods and writing will happen by
     // calling the setter methods.
     $form->bind($entity);
     if ($this->getRequest()->isPost()) {
         $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
         $form->setData($data);
         if ($form->isValid()) {
             // We use now the Doctrine 2 entity manager to save user data to the database
             $entityManager = $this->serviceLocator->get('entity-manager');
             $entityManager->persist($entity);
             $entityManager->flush();
             $this->flashmessenger()->addSuccessMessage('User was added successfully.');
             $event = new EventManager('user');
             $event->trigger('register', $this, array('user' => $entity));
             // redirect the user to the view user action
             return $this->redirect()->toRoute('user/default', array('controller' => 'account', 'action' => 'view', 'id' => $entity->getId()));
         }
     }
     // pass the data to the view for visualization
     return array('form1' => $form);
 }
 /**
  * 测试AuthLoggerListener::onFailure()
  */
 public function testOnFailure()
 {
     $e = new Event();
     $e->setFailure(new Failure('Test', array('result' => '123456')));
     $this->events->trigger(Event::EVENT_FAILURE, $e);
     $this->assertStringMatchesFormat('%s WARN (4): Test {"result":"123456"}%w', file_get_contents($this->destfile));
 }
예제 #10
0
 /**
  * @param \Phpro\SmartCrud\Gateway\CrudGatewayInterface $gateway
  * @param \Zend\EventManager\EventManager               $eventManager
  * @param \Zend\Form\Form                               $form
  * @param \Phpro\SmartCrud\Service\SmartServiceResult   $result
  */
 public function it_should_handle_valid_data($gateway, $eventManager, $form, $result)
 {
     $entity = new \StdClass();
     $postData = $this->getMockPostData();
     $gateway->loadEntity('entityKey', null)->shouldBecalled()->willReturn($entity);
     $gateway->delete($entity, $postData)->shouldBecalled()->willReturn(true);
     $result->setSuccess(true)->shouldBeCalled();
     $result->setEntity($entity)->shouldBeCalled();
     $this->setEntityKey('entityKey');
     $this->setGateway($gateway);
     $this->setResult($result);
     $this->setForm($form);
     $this->run(null, $this->getMockPostData())->shouldReturn($result);
     $eventManager->trigger(Argument::which('getName', CrudEvent::INVALID_DELETE))->shouldNotBeCalled();
     $eventManager->trigger(Argument::which('getName', CrudEvent::BEFORE_DELETE))->shouldBeCalled();
     $eventManager->trigger(Argument::which('getName', CrudEvent::AFTER_DELETE))->shouldBeCalled();
 }
예제 #11
0
 /**
  * @param \Phpro\SmartCrud\Gateway\CrudGatewayInterface $gateway
  * @param \Zend\EventManager\EventManager               $eventManager
  * @param \Phpro\SmartCrud\Service\SmartServiceResult   $result
  */
 public function it_should_return_a_result($gateway, $eventManager, $result)
 {
     $entity = new \StdClass();
     $entity->id = 1;
     $postData = null;
     $gateway->loadEntity('entityKey', $entity->id)->shouldBecalled()->willReturn($entity);
     $result->setSuccess(Argument::any())->shouldBeCalled();
     $result->setForm(Argument::any())->shouldNotBeCalled();
     $result->setEntity($entity)->shouldBeCalled();
     $this->setEntityKey('entityKey');
     $this->setGateway($gateway);
     $this->setResult($result);
     $this->run($entity->id, $postData)->shouldReturn($result);
     $eventManager->trigger(Argument::which('getName', CrudEvent::BEFORE_DATA_VALIDATION))->shouldNotBeCalled();
     $eventManager->trigger(Argument::which('getName', CrudEvent::BEFORE_READ))->shouldBeCalled();
     $eventManager->trigger(Argument::which('getName', CrudEvent::AFTER_READ))->shouldBeCalled();
 }
예제 #12
0
 /**
  * @param \Zend\EventManager\EventManager $eventManager
  * @param \Zend\Form\FormInterface $form
  * @param \ArrayAccess $spec
  */
 public function it_should_trigger_events_during_form_configuration($eventManager, $form, $spec)
 {
     $this->configureForm($form, $spec);
     $triggeredEvents = array(FormEvent::EVENT_CONFIGURE_ELEMENT_PRE, FormEvent::EVENT_CONFIGURE_ELEMENT_POST);
     $eventManager->trigger(Argument::that(function ($event) use($form, $spec, $triggeredEvents) {
         return $event instanceof FormEvent && in_array($event->getName(), $triggeredEvents) && $event->getTarget() == $form->getWrappedObject() && $event->getParam('spec') == $spec->getWrappedObject();
     }))->shouldBeCalledTimes(count($triggeredEvents));
 }
예제 #13
0
 /**
  * @param \Zend\EventManager\EventManager $eventManager
  */
 public function it_should_trigger_events_while_creating_form($eventManager)
 {
     $this->mockConfiguration();
     $this->createForm('stdClass');
     $eventManager->trigger(Argument::that(function ($event) {
         $validEvents = array(FormEvent::EVENT_FORM_CREATE_PRE, FormEvent::EVENT_FORM_CREATE_POST);
         return $event instanceof FormEvent && in_array($event->getName(), $validEvents);
     }))->shouldBeCalledTimes(2);
 }
예제 #14
0
 /**
  * Test if firewall is on
  */
 public function testFirewallOn()
 {
     self::setUpFirewallOn();
     $spyListener = new SpyingFirewallListener();
     $spyListener->setServiceLocator($this->getServiceManager());
     $eventManager = new EventManager();
     $eventManager->attach($spyListener);
     $eventManager->trigger(FirewallEvent::EVENT_FIREWALL_DISPATCH);
     $this->assertTrue($spyListener->isFirewallEnabled());
 }
예제 #15
0
파일: Node.php 프로젝트: GeeH/zend-ldap
 /**
  * Trigger an event
  *
  * @param  string             $event Event name
  * @param  array|\ArrayAccess $argv  Array of arguments; typically, should be associative
  */
 protected function triggerEvent($event, $argv = [])
 {
     if (null === $this->events) {
         if (class_exists('\\Zend\\EventManager\\EventManager')) {
             $this->events = new EventManager(__CLASS__);
         } else {
             return;
         }
     }
     $this->events->trigger($event, $this, $argv);
 }
예제 #16
0
 public function trigger($event, $target = null, $argv = [], $callback = null)
 {
     if (!$event instanceof EventInterface && !$target instanceof EventInterface && !$argv instanceof EventInterface) {
         /*
          * Create the event from the prototype, and not
          * from eventClass as the parent implementation does.
          */
         $e = $this->getEvent($event, $target, $argv);
         return parent::trigger($e, $callback);
     }
     return parent::trigger($event, $target, $argv, $callback);
 }
예제 #17
0
파일: PluginManager.php 프로젝트: reliv/rcm
 /**
  * Get a plugin instance rendered view.
  *
  * @param string  $pluginName           Plugin name
  * @param integer $pluginInstanceId     Plugin Instance Id
  * @param array   $pluginInstanceConfig Plugin Instance Config
  *
  * @return array
  * @throws \Rcm\Exception\InvalidPluginException
  * @throws \Rcm\Exception\PluginReturnedResponseException
  */
 public function getPluginViewData($pluginName, $pluginInstanceId, $pluginInstanceConfig)
 {
     /** @var \Rcm\Plugin\PluginInterface $controller */
     $controller = $this->getPluginController($pluginName);
     if (!is_a($controller, '\\Rcm\\Plugin\\PluginInterface')) {
         throw new InvalidPluginException('Plugin ' . $controller . ' must implement the PluginInterface');
     }
     $controller->setRequest($this->request);
     $response = new Response();
     $controller->setResponse($response);
     /** @var \Zend\Mvc\MvcEvent $event */
     $event = $controller->getEvent();
     $event->setRequest($this->request);
     $event->setResponse($response);
     $controller->setEvent($event);
     $viewModel = $controller->renderInstance($pluginInstanceId, $pluginInstanceConfig);
     if ($viewModel instanceof ResponseInterface) {
         $event = new ViewEvent();
         $event->setResponse($viewModel);
         $this->eventManager->trigger(ViewEvent::EVENT_RESPONSE, $event);
         return null;
     }
     /** @var \Zend\View\Helper\Headlink $headlink */
     $headlink = $this->renderer->plugin('headlink');
     /** @var \Zend\View\Helper\HeadScript $headScript */
     $headScript = $this->renderer->plugin('headscript');
     $oldContainer = $headlink->getContainer();
     $linkContainer = new Container();
     $headlink->setContainer($linkContainer);
     $oldScriptContainer = $headScript->getContainer();
     $headScriptContainer = new Container();
     $headScript->setContainer($headScriptContainer);
     $html = $this->renderer->render($viewModel);
     $css = $headlink->getContainer()->getArrayCopy();
     $script = $headScript->getContainer()->getArrayCopy();
     $return = ['html' => $html, 'css' => $this->getContainerSrc($css), 'js' => $this->getContainerSrc($script), 'editJs' => '', 'editCss' => '', 'displayName' => '', 'tooltip' => '', 'icon' => '', 'siteWide' => false, 'md5' => '', 'fromCache' => false, 'canCache' => false, 'pluginName' => $pluginName, 'pluginInstanceId' => $pluginInstanceId];
     if (isset($this->config['rcmPlugin'][$pluginName]['display'])) {
         $return['displayName'] = $this->config['rcmPlugin'][$pluginName]['display'];
     }
     if (isset($this->config['rcmPlugin'][$pluginName]['tooltip'])) {
         $return['tooltip'] = $this->config['rcmPlugin'][$pluginName]['tooltip'];
     }
     if (isset($this->config['rcmPlugin'][$pluginName]['icon'])) {
         $return['icon'] = $this->config['rcmPlugin'][$pluginName]['icon'];
     }
     if (isset($this->config['rcmPlugin'][$pluginName]['canCache'])) {
         $return['canCache'] = $this->config['rcmPlugin'][$pluginName]['canCache'];
     }
     $headlink->setContainer($oldContainer);
     $headScript->setContainer($oldScriptContainer);
     return $return;
 }
예제 #18
0
 public function indexAction()
 {
     $events = new EventManager();
     $events->attach('do', function ($e) {
         $event = $e->getName();
         $params = $e->getParams();
         printf('Handled event "%s" with parameter "%s"', $event, json_encode($params));
     });
     $params = array('foo' => 'bar', 'baz' => 'bat');
     $events->trigger('do', null, $params);
     //event, target, parameter
     //print : Handled event "do" with parameter "{"foo":"bar","baz":"bat"}"
 }
예제 #19
0
 /**
  * @param AdapterInterface|null $adapter
  * @return AuthResult
  */
 public function authenticate(AdapterInterface $adapter = null)
 {
     $event = new AuthenticationEvent();
     $event->setTarget($this);
     if (!$adapter) {
         $adapter = $this->adapter;
     }
     if ($adapter) {
         $event->setAdapter($adapter);
     }
     $eventManager = new EventManager();
     $eventManager->setIdentifiers(get_class($this));
     $eventManager->trigger($event);
     return $event->getResult();
 }
예제 #20
0
 /**
  * @param \Phpro\SmartCrud\Gateway\CrudGatewayInterface $gateway
  * @param \Zend\EventManager\EventManager               $eventManager
  * @param \Phpro\SmartCrud\Service\PaginatorServiceFactory $paginatorFactory
  * @param \Phpro\SmartCrud\Service\SmartServiceResult   $result
  * @param \Zend\Paginator\Paginator $paginator
  * @param \Phpro\SmartCrud\Query\QueryProviderInterface $queryProvider
  */
 public function it_should_return_a_result($gateway, $eventManager, $paginatorFactory, $result, $paginator, $queryProvider)
 {
     $getData = array();
     $list = array();
     $this->setQueryProvider($queryProvider);
     $gateway->getList('entityKey', $getData, $queryProvider)->willReturn($list);
     $paginatorFactory->createPaginator($list, Argument::cetera())->willReturn($paginator);
     $this->setPaginatorFactory($paginatorFactory);
     $result->setSuccess(Argument::any())->shouldBeCalled();
     $result->setForm(Argument::any())->shouldNotBeCalled();
     $result->setList($paginator)->shouldBeCalled();
     $this->setEntityKey('entityKey');
     $this->setGateway($gateway);
     $this->setResult($result);
     $this->run(Argument::any(), $getData)->shouldReturn($result);
     $eventManager->trigger(Argument::which('getName', CrudEvent::BEFORE_LIST))->shouldBeCalled();
     $eventManager->trigger(Argument::which('getName', CrudEvent::AFTER_LIST))->shouldBeCalled();
 }
예제 #21
0
 public function onBootstrap(MvcEvent $event)
 {
     $services = $event->getApplication()->getServiceManager();
     $sharedEventManager = $event->getApplication()->getEventManager()->getSharedManager();
     $sharedEventManager->attach('exam', 'certificate-generated', function ($event) use($services) {
         $mail = $services->get('mail');
         $user = $event->getParam('user');
         $exam = $event->getParam('exam');
         $pdf = $event->getParam('pdf');
         $mail->sendCertificate($user, $exam, $pdf);
     });
     $sharedEventManager->attach('exam', 'taken-excellent', function ($event) use($services) {
         $user = $event->getParam('user');
         $exam = $event->getParam('exam');
         $pdf = $services->get('pdf');
         $pdfDocument = $pdf->generateCertificate($user, $exam['name']);
         $newEvent = new EventManager('exam');
         $newEvent->trigger('certificate-generated', $this, array('user' => $event->getParam('user'), 'exam' => $event->getParam('exam'), 'pdf' => $pdfDocument));
     });
 }
예제 #22
0
 public function index01Action()
 {
     $eventManager = new \Zend\EventManager\EventManager();
     //        $eventManager->attach('oneEvent', function(){
     //            echo '<h3 style="color:red;">OneEvent</h3>';
     //        });
     $listenerA = $eventManager->attach('oneEvent', function () {
         echo '<h3 style="color:red;">OneEvent</h3>';
     });
     //$eventManager->trigger('oneEvent');
     $listenerB = $eventManager->attach('twoEvent', function () {
         echo '<h3 style="color:red;">TwoEvent</h3>';
     });
     //$eventManager->trigger('twoEvent');
     /** THÊM MỘT CÔNG VIỆC CHO SỰ KIỆN oneEvent */
     $eventManager->attach('oneEvent', function () {
         echo '<h3 style="color:red">EventOneContinue</h3>';
     });
     /** THÊM MỘT CÔNG VIỆC CHO CẢ 2 SỰ KIỆN => oneEvent và twoEvent */
     /** OneEvent => OneEvent, EventOneCon */
     /** TwoEvent => TwoEvent*/
     $eventManager->attach(array('oneEvent', 'twoEvent'), function () {
         echo '<h3 style="color:blue;">Event one Event and two Event</h3>';
     });
     //$eventManager->trigger('oneEvent');
     //$eventManager->trigger('twoEvent');
     /** THÊM MỘT CÔNG VIỆC CHO CẢ NHIỀU SỰ KIỆN => oneEvent và twoEvent */
     /** OneEvent => OneEvent, EventOneCon */
     /** TwoEvent => TwoEvent*/
     $eventManager->attach('treeEvent', function () {
         echo '<h3 style="color:blue;">Event Three - Doing</h3>';
     });
     $eventManager->attach('*', function () {
         echo '<h3 style="color:blue;">Doing</h3>';
     });
     $eventManager->trigger('oneEvent');
     return $this->response;
     /** Không cần layout và view */
 }
예제 #23
0
 public function indexAction()
 {
     /*$foo = new SimpleEvent();
       $foo->getEventManager()->attach('echoHello_pre', function($e){
           echo "Wow! ";
       });
       $foo->getEventManager()->attach('echoHello_post', function($e){
           echo ". This example is very good! \n";
       });
       $foo->getEventManager()->attach('echoHello_post', function($e){
           echo "<br/>by gianarb92@gmail.com";
       }, -10);
       $foo->echoHello();*/
     $events = new EventManager();
     $events->attach('do', function ($e) {
         $event = $e->getName();
         $params = $e->getParams();
         printf('Handled event "%s" with parameter "%s"', $event, json_encode($params));
     });
     $params = array('foo' => 'bar', 'baz' => 'bat');
     $events->trigger('do', null, $params);
     //event, target, parameter
     //print : Handled event "do" with parameter "{"foo":"bar","baz":"bat"}"
 }
예제 #24
0
 /** \Zend\EventManager\EventInterface */
 public function index05Action()
 {
     $eventManager = new EventManager();
     $eventManager->attach('eventOne', function (\Zend\EventManager\EventInterface $e) {
     });
     $listener01 = function (\Zend\EventManager\EventInterface $e) {
         echo '<pre>';
         print_r($e);
         echo '</pre>';
         $name = $e->getName();
         $params = $e->getParams();
         $target = $e->getTarget();
         $e->setParam('course', 'default');
         echo $param_name = $e->getParam('course', 'default');
     };
     $eventManager->attach('eventOne', $listener01);
     $params = array('course' => 'Zend Framework 2', 'year' => '2015');
     $eventManager->trigger('eventOne', this, $params);
     return $this->response;
 }
예제 #25
0
<?php

/**
 * Copyright (c) 2014 Keith Casey
 *
 * This code is designed to accompany the lynda.com video course "Design Patterns in PHP"
 *   by Keith Casey. If you've received this code without seeing the videos, go watch the
 *   videos. It will make way more sense and be more useful in general.
 */
require 'vendor/autoload.php';
use Zend\EventManager\EventManager;
$events = new EventManager();
$events->attach('load', function ($e) {
    $event = $e->getName();
    $params = $e->getParams();
    echo "Just captured event {$event} with these parameters: " . json_encode($params) . "\n";
});
$params = array('city' => 'Austin', 'state' => 'Texas');
$events->trigger('load', null, $params);
$events->trigger('test', null, $params);
예제 #26
0
 /**
  * Get the event manager
  *
  * @return EventManager
  * @throws Exception\MissingDependencyException
  */
 public function getEventManager()
 {
     if ($this->eventManager instanceof EventManager) {
         return $this->eventManager;
     }
     if (!class_exists('Zend\\EventManager\\EventManager')) {
         throw new Exception\MissingDependencyException('Zend\\EventManager\\EventManager not found');
     }
     // create a new event manager object
     $eventManager = new EventManager();
     // trigger change event on change of a base capability
     if ($this->baseCapabilities && $this->baseCapabilities->hasEventManager()) {
         $onChange = function ($event) use($eventManager) {
             $eventManager->trigger('change', $event->getTarget(), $event->getParams());
         };
         $this->baseCapabilities->getEventManager()->attach('change', $onChange);
     }
     // register event manager
     $this->eventManager = $eventManager;
     return $this->eventManager;
 }
 /**
  * {@inheritDoc}
  */
 public function dispatch($eventName, SymfonyEvent $event = null)
 {
     $decoratedEvent = DecoratorFactory::decorate($event);
     $decoratedEvent->setName($eventName);
     return $this->eventManager->trigger($decoratedEvent);
 }
예제 #28
0
 public function protectPage(MvcEvent $event)
 {
     $match = $event->getRouteMatch();
     if (!$match) {
         // we cannot do anything without a resolved route
         return;
     }
     $controller = $match->getParam('controller');
     $action = $match->getParam('action');
     $namespace = $match->getParam('__NAMESPACE__');
     $parts = explode('\\', $namespace);
     $moduleNamespace = $parts[0];
     $services = $event->getApplication()->getServiceManager();
     $config = $services->get('config');
     $auth = $services->get('auth');
     $acl = $services->get('acl');
     // get the role of the current user
     $currentUser = $services->get('user');
     $role = $currentUser->getRole();
     // This is how we add default acl and role to the navigation view helpers
     \Zend\View\Helper\Navigation\AbstractHelper::setDefaultAcl($acl);
     \Zend\View\Helper\Navigation\AbstractHelper::setDefaultRole($role);
     // check if the current module wants to use the ACL
     $aclModules = $config['acl']['modules'];
     if (!empty($aclModules) && !in_array($moduleNamespace, $aclModules)) {
         return;
     }
     // Get the short name of the controller and use it as resource name
     // Example: User\Controller\Course -> course
     $resourceAliases = $config['acl']['resource_aliases'];
     if (isset($resourceAliases[$controller])) {
         $resource = $resourceAliases[$controller];
     } else {
         $resource = strtolower(substr($controller, strrpos($controller, '\\') + 1));
     }
     // If a resource is not in the ACL add it
     if (!$acl->hasResource($resource)) {
         $acl->addResource($resource);
     }
     try {
         if ($acl->isAllowed($role, $resource, $action)) {
             return;
         }
     } catch (AclException $ex) {
         // @todo: log in the warning log the missing resource
     }
     // If the role is not allowed access to the resource we have to redirect the
     // current user to the log in page.
     $e = new EventManager('user');
     $e->trigger('deny', $this, array('match' => $match, 'role' => $role, 'acl' => $acl));
     // Set the response code to HTTP 403: Forbidden
     $response = $event->getResponse();
     $response->setStatusCode(403);
     // and redirect the current user to the denied action
     $match->setParam('controller', 'User\\Controller\\Account');
     $match->setParam('action', 'denied');
 }
 /**
  * Execute/Dispatch the request.
  * @param Client $client
  * @param Request $request
  * @throws \Exception
  * @return \FrontCore\Models\ApiRequestModel
  */
 private function executeRequest(Client $client, $request = NULL)
 {
     //check if api location isset
     if ($this->api_url == "") {
         throw new \Exception(__CLASS__ . " : Line " . __LINE__ . " : Request could not be performed, API Location is not set", 500);
     }
     //end if
     //should session login information be disabled?
     if ($this->api_session_login === TRUE) {
         //load user session data
         $objUserSession = FrontUserSession::isLoggedIn();
         //check if this is a user or site call
         if ($this->api_pword == "" || !$this->api_pword) {
             //try to extract from session
             if (is_object($objUserSession)) {
                 $this->setAPIUserPword($objUserSession->pword);
             }
             //end if
         }
         //end if
         //set api username
         if ($this->api_user == "" || !$this->api_user) {
             //is api key encoded?
             if (is_object($objUserSession)) {
                 if (isset($objUserSession->api_key_encoded) && $objUserSession->api_key_encoded === TRUE) {
                     $key = $this->getServiceLocator()->get("FrontCore\\Models\\FrontCoreSecurityModel")->decodeValue($objUserSession->uname);
                     $this->setAPIUser($key);
                 } else {
                     //try to extract from session
                     $this->setAPIUser($objUserSession->uname);
                 }
                 //end if
             }
             //end if
         }
         //end if
         //set api key
         if ($this->api_key == "" || !$this->api_key) {
             //is api key encoded?
             if (is_object($objUserSession)) {
                 if (isset($objUserSession->api_key_encoded) && $objUserSession->api_key_encoded === TRUE) {
                     $key = $this->getServiceLocator()->get("FrontCore\\Models\\FrontCoreSecurityModel")->decodeValue($objUserSession->api_key);
                     $this->setAPIKey($key);
                 } else {
                     //try to extract from session
                     $this->setAPIKey($objUserSession->api_key);
                 }
                 //end if
             }
             //end if
         }
         //end if
         require "./config/helpers/ob1.php";
         //@TODO - create own api authentication logic
         // throw new \Exception(__CLASS__ . " : Line " . __LINE__ . ": Implement your api request header logic here", 9999);
     } else {
         if ($this->api_key != "") {
             require "./config/helpers/ob2.php";
             //@TODO - create own api authentication logic
             //throw new \Exception(__CLASS__ . " : Line " . __LINE__ . ": Implement your api request header logic here", 9999);
         } else {
             //bypass to perform info request
             $arr_headers = array();
         }
         //end if
     }
     //end if
     //use manually set headers and then clear them
     if (is_array($this->arr_manual_request_headers)) {
         $arr_headers = $this->arr_manual_request_headers;
         $this->arr_manual_request_headers = FALSE;
     }
     //end if
     try {
         //set user logged in flag for submit to api
         if ($objUserSession) {
             $arr_headers["m3userloggedin"] = time();
         }
         //end if
         //set origin url
         $arr_headers['m3originurl'] = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
         //load event manager
         $event = new EventManager();
         //trigger pre event
         $result = $event->trigger("apiCallExecuted.pre", $this, array("objClient" => $client, "objRequest" => $request, 'url' => self::buildURI()));
         //set timeout
         $client->setOptions(array("timeout" => 60, "sslverifypeer" => FALSE));
         if ($request instanceof Request) {
             $client->setHeaders($arr_headers);
             $response = $client->dispatch($request);
         } else {
             $client->setUri(self::buildURI());
             $client->setHeaders($arr_headers);
             $response = $client->send();
         }
         //end if
         $arr_api_data = array("url" => self::buildURI(), "response" => $response->getBody());
         //trigger post event
         $result = $event->trigger("apiCallExecuted.pre", $this, array("objApiData" => (object) $arr_api_data, "objResponse" => $response, "objClient" => $client, "objRequest" => $request, 'url' => self::buildURI()));
         $event->trigger("apiCallExecuted", $this, array("objApiData" => (object) $arr_api_data, "objResponse" => $response));
         //resest the module indicator where set to null
         if (is_null($this->api_module)) {
             $this->api_module = "api";
         }
         //end if
         return self::processResponse($response);
     } catch (\Exception $e) {
         throw new \Exception(__CLASS__ . " : Line " . __LINE__ . " : An error occured performing api request. URL : " . self::buildURI() . " : Error ||" . $e->getMessage(), $e->getCode());
     }
     //end function
 }
예제 #30
0
 public function index12Action()
 {
     $eventHost = new EventManager();
     $shareEventManager = $eventHost->getSharedManager();
     $shareEventManager->attach("emOne", "eventOne", function ($e) {
         echo "<h3 style='color:red;font-weight:bold'>eventManagerOne - eventOne - Do 1</h3>";
     });
     $shareEventManager->attach(array("emTwo", "emThree"), "eventNew", function ($e) {
         echo "<h3 style='color:red;font-weight:bold'>eventManagerOne - eventNew - Do 1</h3>";
     });
     $eventManager = new EventManager(array("emOne", "emThree"));
     //$eventManager->setSharedManager($shareEventManager);<---không cần thiết xem lại action 10
     $eventManager->trigger("eventOne");
     $eventManager->trigger("eventNew");
     $eventManager = new EventManager("emTwo");
     //$eventManager->setSharedManager($shareEventManager);<---không cần thiết xem lại action 10
     $eventManager->trigger("eventNew");
     return false;
 }