public function work(GearmanJob $job) { $workload = $job->workload(); $json = json_decode($workload, true); if (!json_last_error()) { $workload = $json; } $eventManager = new CakeEventManager(); $eventManager->dispatch(new CakeEvent('Gearman.beforeWork', $this, $workload)); $data = call_user_func($this->_workers[$job->functionName()], $job, $workload); $eventManager->dispatch(new CakeEvent('Gearman.afterWork', $this, $workload)); return $data; }
/** * testProcessVersion * * @return void */ public function testProcessVersion() { $this->Image->create(); $result = $this->Image->save(array('foreign_key' => 'test-1', 'model' => 'Test', 'file' => array('name' => 'titus.jpg', 'size' => 332643, 'tmp_name' => CakePlugin::path('FileStorage') . DS . 'Test' . DS . 'Fixture' . DS . 'File' . DS . 'titus.jpg', 'error' => 0))); $result = $this->Image->find('first', array('conditions' => array('id' => $this->Image->getLastInsertId()))); $this->assertTrue(!empty($result) && is_array($result)); $this->assertTrue(file_exists($this->testPath . $result['ImageStorage']['path'])); $path = $this->testPath . $result['ImageStorage']['path']; $Folder = new Folder($path); $folderResult = $Folder->read(); $this->assertEqual(count($folderResult[1]), 3); Configure::write('Media.imageSizes.Test', array('t200' => array('thumbnail' => array('mode' => 'outbound', 'width' => 200, 'height' => 200)))); ClassRegistry::init('FileStorage.ImageStorage')->generateHashes(); $Event = new CakeEvent('ImageVersion.createVersion', $this->Image, array('record' => $result, 'storage' => StorageManager::adapter('Local'), 'operations' => array('t200' => array('thumbnail' => array('mode' => 'outbound', 'width' => 200, 'height' => 200))))); CakeEventManager::instance()->dispatch($Event); $path = $this->testPath . $result['ImageStorage']['path']; $Folder = new Folder($path); $folderResult = $Folder->read(); $this->assertEqual(count($folderResult[1]), 4); $Event = new CakeEvent('ImageVersion.removeVersion', $this->Image, array('record' => $result, 'storage' => StorageManager::adapter('Local'), 'operations' => array('t200' => array('thumbnail' => array('mode' => 'outbound', 'width' => 200, 'height' => 200))))); CakeEventManager::instance()->dispatch($Event); $path = $this->testPath . $result['ImageStorage']['path']; $Folder = new Folder($path); $folderResult = $Folder->read(); $this->assertEqual(count($folderResult[1]), 3); }
public function changeStatus(Model $Model, $status, $id = null, $force = false) { if ($id === null) { $id = $Model->getID(); } if ($id === false) { return false; } $force = true; $Model->id = $id; if (!$Model->exists()) { throw new NotFoundException(); } if ($force !== true) { $modelData = $Model->read(); if ($modelData[$Model->alias]['status'] === $status) { CakeLog::write(LOG_WARNING, __d('webshop', 'The status of %1$s with id %2$d is already set to %3$s. Not making a change', strtolower(Inflector::humanize(Inflector::underscore($Model->name))), $id, $status), array('webshop')); return false; } } else { CakeLog::write(LOG_WARNING, __d('webshop', 'Status change of %1$s with id %2$d is being forced to %3$s', strtolower(Inflector::humanize(Inflector::underscore($Model->name))), $id, $status), array('webshop')); } $Model->saveField('status', $status); CakeLog::write(LOG_INFO, __d('webshop', 'Changed status of %1$s with id %2$d to %3$s', strtolower(Inflector::humanize(Inflector::underscore($Model->name))), $id, $status), array('webshop')); $eventData = array(); $eventData[Inflector::underscore($Model->name)]['id'] = $id; $eventData[Inflector::underscore($Model->name)]['status'] = $status; $overallEvent = new CakeEvent($Model->name . '.statusChanged', $this, $eventData); $specificEvent = new CakeEvent($Model->name . '.statusChangedTo' . Inflector::camelize($status), $this, $eventData); CakeEventManager::instance()->dispatch($overallEvent); CakeEventManager::instance()->dispatch($specificEvent); return true; }
/** * Import exchange rate for the euro. */ public function import() { $exchangeRateImporter = new EcbExchangeRateImporter(); $exchangeRateImporter->import(); $event = new CakeEvent('ExchangeRateImport.completed', $this); CakeEventManager::instance()->dispatch($event); }
public function onProductBought($event) { $this->Product->id = $event->data['product']['id']; $this->Product->recursive = 2; $product = $this->Product->read(); if ($product[$this->Product->WebhostingProduct->alias]['id'] === null) { return; } $this->Product->WebhostingProduct->HostGroup->id = $product['HostGroup']['id']; $this->Product->WebhostingProduct->HostGroup->recursive = 2; $hostGroup = $this->Product->WebhostingProduct->HostGroup->read(); $WebhostingProvider = BasicWebhostingProvider::get($hostGroup['Host'][0]['Provider']['class']); $webhostingPackage = $this->WebhostingPackage->createFromWebhostingProduct($product['WebhostingProduct'], $event->data['customer']['id'], $hostGroup['Host'][0]['id']); $webhostingDetails = $WebhostingProvider->createPackage($webhostingPackage['WebhostingPackage']['id']); if ($webhostingDetails === false) { CakeLog::write(LOG_ERROR, __d('pltfrm', 'Webhosting provider %1$s could not create webhosting package with id %2$d owned by %3$s', $hostGroup['Host'][0]['Provider']['class'], $webhostingPackage['WebhostingPackage']['id'], $webhostingPackage['Customer']['name']), array('webhosting', 'pltfrm')); return false; } $eventData = array(); $eventData['webhosting']['id'] = $webhostingPackage['WebhostingPackage']['id']; $eventData['details'] = $webhostingDetails; $eventData['metadata'] = array(); $webhostingCreatedEvent = new CakeEvent('Webhosting.created', $this, $eventData); CakeEventManager::instance()->dispatch($webhostingCreatedEvent); CakeLog::write(LOG_INFO, __d('pltfrm', 'Webhosting provider %1$s created webhosting package with id %2$d', $hostGroup['Host'][0]['Provider']['class'], $webhostingPackage['WebhostingPackage']['id']), array('webhosting', 'pltfrm')); if (isset($event->data['order'])) { $this->OrderProduct->changeStatus('delivered', $event->data['order']['product_id']); } return true; }
/** * Syntactic sugar improving the readability for on* methods * * @param string $eventName * @param CakeWampAppServer $scope * @param array $params */ public function dispatchEvent($eventName, $scope, $params) { $event = new CakeEvent($eventName, $scope, $params); $this->outVerbose('Event begin: ' . $eventName); $this->_eventManager->dispatch($event); $this->outVerbose('Event end: ' . $eventName); return $event; }
/** * Dispatch event * * @param string $name Name of the event * @param object $subject the object that this event applies to (usually the object that is generating the event) * @param mixed $data any value you wish to be transported with this event to it can be read by listeners */ public static function dispatchEvent($name, $subject = null, $data = []) { $event = new CakeEvent($name, $subject, $data); if (!$subject) { CakeEventManager::instance()->dispatch($event); } else { $subject->getEventManager()->dispatch($event); } }
/** * Constructor * Overridden to provide Twig loading * * @param Controller $Controller Controller */ public function __construct(Controller $Controller = null) { $this->Twig = new Twig_Environment(new Twig_Loader_Cakephp(array()), array('cache' => Configure::read('TwigView.Cache'), 'charset' => strtolower(Configure::read('App.encoding')), 'auto_reload' => Configure::read('debug') > 0, 'autoescape' => false, 'debug' => Configure::read('debug') > 0)); CakeEventManager::instance()->dispatch(new CakeEvent('Twig.TwigView.construct', $this, array('TwigEnvironment' => $this->Twig))); parent::__construct($Controller); if (isset($Controller->theme)) { $this->theme = $Controller->theme; } $this->ext = self::EXT; }
/** * Default settings * * @var array */ public function initialize(Controller $Controller) { $this->settings = array_merge($this->_defaultSettings, $this->settings); $this->Controller = $Controller; $this->_EventManager = CakeEventManager::instance(); if (empty($this->settings['model'])) { $this->settings['model'] = $this->Controller->modelClass; } $this->sessionKey = $this->settings['sessionKey']; }
/** * Returns the globally available instance of a CakeEventManager * this is used for dispatching events attached from outside the scope * other managers were created. Usually for creating hook systems or inter-class * communication * * If called with a first params, it will be set as the globally available instance * * @param CakeEventManager $manager * @return CakeEventManager the global event manager */ public static function instance($manager = null) { if ($manager instanceof CakeEventManager) { self::$_generalManager = $manager; } if (empty(self::$_generalManager)) { self::$_generalManager = new CakeEventManager(); } self::$_generalManager->_isGlobal = true; return self::$_generalManager; }
/** * Starts the websocket server * * @return void */ public function start() { $this->__loop = LoopFactory::create(); if ($this->__loop instanceof \React\EventLoop\StreamSelectLoop) { $this->out('<warning>Your configuration doesn\'t seem to support \'ext-libevent\'. It is highly reccomended that you install and configure it as it provides significant performance gains over stream select!</warning>'); } $socket = new Reactor($this->__loop); $socket->listen(Configure::read('Ratchet.Connection.websocket.port'), Configure::read('Ratchet.Connection.websocket.address')); $this->__ioServer = new IoServer(new HttpServer(new WsServer(new SessionProvider(new WampServer(new CakeWampAppServer($this, $this->__loop, CakeEventManager::instance(), $this->params['verbose'])), new CakeWampSessionHandler(), [], new PhpSerializeHandler()))), $socket, $this->__loop); $this->__loop->run(); }
/** * Detaches all listeners from the Cart events to avoid application level events changing the tests * * @return void */ protected function _detachAllListeners() { $EventManager = CakeEventManager::instance(); $events = array('Cart.beforeCalculateCart', 'Cart.applyTaxRules', 'Cart.applyDiscounts', 'Cart.afterCalculateCart'); foreach ($events as $event) { $listeners = $EventManager->listeners($event); foreach ($listeners as $listener) { foreach ($listener['callable'] as $callable) { $EventManager->detach($callable); } } } }
public function testConstruct() { $this->_hibernateListeners('Twig.TwigView.construct'); $callbackFired = false; $that = $this; $eventCallback = function ($event) use($that, &$callbackFired) { $that->assertInstanceof('Twig_Environment', $event->data['TwigEnvironment']); $callbackFired = true; }; CakeEventManager::instance()->attach($eventCallback, 'Twig.TwigView.construct'); $TwigView = new TwigView(); CakeEventManager::instance()->detach($eventCallback, 'Twig.TwigView.construct'); $this->_wakeupListeners('Twig.TwigView.construct'); $this->assertTrue($callbackFired); }
/** * Triggers a Crud event by creating a new subject and filling it with $data * if $data is an instance of CrudSubject it will be reused as the subject * object for this event. * * If Event listeners return a CakeResponse object, the this method will throw an * exception and fill a 'response' property on it with a reference to the response * object. * * @param string $eventName * @param array $data * @throws Exception if any event listener return a CakeResponse object * @return CrudSubject */ public function trigger($eventName, $data = array()) { $subject = $data instanceof CrudSubject ? $data : $this->_getSubject($data); $event = new CakeEvent($this->config('eventPrefix') . '.' . $eventName, $subject); $this->_eventManager->dispatch($event); if ($event->result instanceof CakeResponse) { $exception = new Exception(); $exception->response = $event->result; throw $exception; } $subject->stopped = false; if ($event->isStopped()) { $subject->stopped = true; } return $subject; }
/** * URL * * @param array $image FileStorage array record or whatever else table that matches this helpers needs without the model, we just want the record fields * @param string $version Image version string * @param array $options HtmlHelper::image(), 2nd arg options array * @throws InvalidArgumentException * @return string */ public function imageUrl($image, $version = null, $options = array()) { if (empty($image) || empty($image['id'])) { return false; } if (!empty($version)) { $hash = Configure::read('Media.imageHashes.' . $image['model'] . '.' . $version); if (empty($hash)) { throw new \InvalidArgumentException(__d('file_storage', 'No valid version key (%s %s) passed!', @$image['model'], $version)); } } else { $hash = null; } $Event = new CakeEvent('FileStorage.ImageHelper.imagePath', $this, array('hash' => $hash, 'image' => $image, 'version' => $version, 'options' => $options)); CakeEventManager::instance()->dispatch($Event); if ($Event->isStopped()) { return $this->normalizePath($Event->data['path']); } else { return false; } }
protected function _expectedEventCalls(&$asserts, $events) { $cbi = []; foreach ($events as $eventName => $event) { $this->__preservedEventListeners[$eventName] = CakeEventManager::instance()->listeners($eventName); foreach ($this->__preservedEventListeners[$eventName] as $eventListener) { $this->eventManager->detach($eventListener['callable'], $eventName); } $count = count($events[$eventName]['callback']); for ($i = 0; $i < $count; $i++) { $asserts[$eventName . '_' . $i] = false; } $cbi[$eventName] = 0; $this->eventManager->attach(function ($event) use(&$events, $eventName, &$asserts, &$cbi) { $asserts[$eventName . '_' . $cbi[$eventName]] = true; call_user_func($events[$eventName]['callback'][$cbi[$eventName]], $event); $cbi[$eventName]++; }, $eventName); } return $asserts; }
/** * Default callback entry point for API callbacks for payment processors * * @param null $token * @throws NotFoundException * @internal param string $processor * @return void */ public function callback($token = null) { $order = $this->Order->find('first', array('contain' => array(), 'conditions' => array('Order.token' => $token))); if (empty($order)) { throw new NotFoundException(__d('cart', 'Invalid payment token %s!', $token)); } try { $Processor = $this->_loadPaymentProcessor($order['Order']['processor']); $status = $Processor->notificationCallback($order); $transactionId = $Processor->getTransactionId(); if (empty($order['Order']['payment_reference']) && !empty($transactionId)) { $order['Order']['payment_reference'] = $transactionId; } $result = $this->Order->save(array('Order' => array('id' => $order['Order']['id'], 'payment_status' => $status, 'payment_reference' => $order['Order']['payment_reference'])), array('validate' => false, 'callbacks' => false)); } catch (Exception $e) { $this->log($e->getMessage(), 'payment-error'); $this->log($this->request, 'payment-error'); } $Event = new CakeEvent('Payment.callback', $this->request); CakeEventManager::dispatch($Event, $this, array($result)); $this->_stop(); }
/** * {@inheritdoc} * * @return void */ public function execute() { $tasks = array(); $this->TaskServer->killZombies(); while ($this->TaskServer->freeSlots() > 0 && ($task = $this->TaskServer->getPending())) { $tasks[] = $task; } if (empty($tasks)) { return; } $events = (array) Configure::read('Task.processEvents'); $models = array(); foreach ($events as $event) { $models[$event['model']] = ClassRegistry::init($event['model']); CakeEventManager::instance()->attach($models[$event['model']], $event['key'], $event['options']); } foreach ($tasks as $task) { $this->_run($task); } foreach ($events as $event) { CakeEventManager::instance()->detach($models[$event['model']], $event['key'], $event['options']); } }
/** * Load a CrudAction instance. * * @param string $name The controller action name. * @return CrudAction * @throws CakeException If action is not mapped. */ protected function _loadAction($name) { if (!isset($this->_actionInstances[$name])) { $config = $this->config('actions.' . $name); if (empty($config)) { throw new CakeException(sprintf('Action "%s" has not been mapped', $name)); } list($plugin, $class) = pluginSplit($config['className'], true); $class = ucfirst($class); if (in_array($class, array('Index', 'View', 'Add', 'Edit', 'Delete'))) { if (!empty($plugin) && $plugin !== 'Crud.') { throw new CakeException('The build-in CrudActions (Index, View, Add, Edit and Delete) must be loaded from the Crud plugin'); } $plugin = 'Crud.'; } $class .= 'CrudAction'; App::uses($class, $plugin . 'Controller/Crud/Action'); $subject = $this->getSubject(array('action' => $name)); $this->_actionInstances[$name] = new $class($subject, $config); $this->_eventManager->attach($this->_actionInstances[$name]); } return $this->_actionInstances[$name]; }
/** * dispatch * * 命名規則に従ったイベント名で、イベントをディスパッチする * * @param string $name * @param Object $subject * @param array $params * @param array $options * @return boolean|\CakeEvent */ public static function dispatch($name, $subject, $params = array(), $options = array()) { $options = array_merge(array('modParams' => 0, 'layer' => '', 'plugin' => $subject->plugin, 'class' => $subject->name), $options); extract($options); if ($layer && !preg_match('/^' . $layer . './', $name)) { $evnetName = $layer; if ($plugin) { $evnetName .= '.' . $plugin; } if ($class) { $evnetName .= '.' . $class; } $evnetName .= '.' . $name; } $EventManager = CakeEventManager::instance(); if (!$EventManager->listeners($evnetName)) { return false; } $event = new CakeEvent($evnetName, $subject, $params); $event->modParams = $modParams; $EventManager->dispatch($event); return $event; }
/** * Removes a listener from the active listeners. * @see CakeEventManager::detach() * @return void */ public function detach($callable, $eventKey = null) { if (is_object($callable)) { $key = get_class($callable); unset($this->_listenersMap[$key]); } parent::detach($callable, $eventKey); }
/** * Returns the CakeEventManager manager instance that is handling any callbacks. * You can use this instance to register any new listeners or callbacks to the * controller events, or create your own events and trigger them at will. * * @return CakeEventManager */ public function getEventManager() { if (empty($this->_eventManager)) { $this->_eventManager = new CakeEventManager(); $this->_eventManager->attach($this->Components); $this->_eventManager->attach($this); } return $this->_eventManager; }
*/ if (BC_INSTALLED && !$isUpdater && !$isMaintenance) { App::build(array('Plugin' => array_merge(array(BASER_THEMES . $bcSite['theme'] . DS . 'Plugin' . DS), App::path('Plugin')))); $plugins = getEnablePlugins(); foreach ($plugins as $plugin) { loadPlugin($plugin['Plugin']['name'], $plugin['Plugin']['priority']); } $plugins = Hash::extract($plugins, '{n}.Plugin.name'); Configure::write('BcStatus.enablePlugins', $plugins); /** * イベント登録 */ App::uses('BcControllerEventDispatcher', 'Event'); App::uses('BcModelEventDispatcher', 'Event'); App::uses('BcViewEventDispatcher', 'Event'); $CakeEvent = CakeEventManager::instance(); $CakeEvent->attach(new BcControllerEventDispatcher()); $CakeEvent->attach(new BcModelEventDispatcher()); $CakeEvent->attach(new BcViewEventDispatcher()); /** * テーマの bootstrap を実行する */ $themePath = WWW_ROOT . 'theme' . DS . Configure::read('BcSite.theme') . DS; $themeBootstrap = $themePath . 'Config' . DS . 'bootstrap.php'; if (file_exists($themeBootstrap)) { include $themeBootstrap; } } /** * 文字コードの検出順を指定 */
/** * Attaches all event listeners for this dispatcher instance. Loads the * dispatcher filters from the configured locations. * * @param CakeEventManager $manager * @return void * @throws MissingDispatcherFilterException */ protected function _attachFilters($manager) { $filters = Configure::read('Dispatcher.filters'); if (empty($filters)) { return; } foreach ($filters as $filter) { if (is_string($filter)) { $filter = array('callable' => $filter); } if (is_string($filter['callable'])) { list($plugin, $callable) = pluginSplit($filter['callable'], true); App::uses($callable, $plugin . 'Routing/Filter'); if (!class_exists($callable)) { throw new MissingDispatcherFilterException($callable); } $manager->attach(new $callable()); } else { $on = strtolower($filter['on']); $options = array(); if (isset($filter['priority'])) { $options = array('priority' => $filter['priority']); } $manager->attach($filter['callable'], 'Dispatcher.' . $on . 'Dispatch', $options); } } }
<?php App::uses('FileStorageUtils', 'FileStorage.Lib/Utility'); App::uses('StorageManager', 'FileStorage.Lib'); App::uses('LocalImageProcessingListener', 'FileStorage.Event'); //App::uses('LocalFileStorageListener', 'FileStorage.Event'); App::uses('CakeEventManager', 'Event'); spl_autoload_register(__NAMESPACE__ . '\\FileStorageUtils::gaufretteLoader'); $listener = new LocalImageProcessingListener(); CakeEventManager::instance()->attach($listener);
/** * Returns the CakeEventManager manager instance that is handling any callbacks. * You can use this instance to register any new listeners or callbacks to the * controller events, or create your own events and trigger them at will. * * @return CakeEventManager */ public function getEventManager() { if (empty($this->_eventManager)) { $this->_eventManager = new CakeEventManager(); } if (!$this->_eventManagerConfigured) { $this->_eventManager->attach($this->Helpers); $this->_eventManagerConfigured = true; } return $this->_eventManager; }
* */ /** * Plugins need to be loaded manually, you can either load them one by one or all of them in a single call * Uncomment one of the lines below, as you need. make sure you read the documentation on CakePlugin to use more * advanced ways of loading plugins * * CakePlugin::loadAll(); // Loads all plugins at once * CakePlugin::load('DebugKit'); //Loads a single plugin named DebugKit * */ //CakePlugin::load('Crud'); if (php_sapi_name() !== 'cli' && Configure::read('debug') && in_array('DebugKit', App::objects('plugin'))) { CakePlugin::load('DebugKit'); App::uses('CakeEventManager', 'Event'); CakeEventManager::instance()->attach(function ($event) { $controller = $event->subject(); if (!isset($controller->Crud)) { return; } $controller->Toolbar = $controller->Components->load('DebugKit.Toolbar', ['panels' => ['Crud.Crud']]); $controller->Crud->addListener('DebugKit', 'Crud.DebugKit'); }, 'Controller.initialize'); } /** * You can attach event listeners to the request lifecycle as Dispatcher Filter . By Default CakePHP bundles two filters: * * - AssetDispatcher filter will serve your asset files (css, images, js, etc) from your themes and plugins * - CacheDispatcher filter will read the Cache.check configure variable and try to serve cached content generated from controllers * * Feel free to remove or add filters as you see fit for your application. A few examples:
/** * Tests that stopping an event will not notify the rest of the listeners * * @return void */ public function testStopPropagation() { $manager = new CakeEventManager(); $listener = new CakeEventTestListener(); $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); $manager->attach(array($listener, 'stopListener'), 'fake.event', array('priority' => 8)); $manager->attach(array($listener, 'secondListenerFunction'), 'fake.event', array('priority' => 5)); $event = new CakeEvent('fake.event'); $manager->dispatch($event); $expected = array('secondListenerFunction'); $this->assertEquals($expected, $listener->callStack); }
/** * Test that events are dispatched properly when there are global and local * listeners at the same priority. * * @return void */ public function testDispatchWithGlobalAndLocalEvents() { $listener = new CustomTestEventListener(); CakeEventManager::instance()->attach($listener); $listener2 = new CakeEventTestListener(); $manager = new CakeEventManager(); $manager->attach(array($listener2, 'listenerFunction'), 'fake.event'); $manager->dispatch(new CakeEvent('fake.event', $this)); $this->assertEquals(array('listenerFunction'), $listener->callStack); $this->assertEquals(array('listenerFunction'), $listener2->callStack); }
/** * Tets helper. Makes task runner mock * * @param array $processEvents * @return object */ protected function _makeRunner(array $processEvents) { return function () use($processEvents) { $Runner = $this->getMockBuilder('TaskRunner')->setMethods(array('start'))->disableOriginalConstructor()->getMock(); $Runner->expects($this->once())->method('start')->willReturnCallback(function () use($processEvents) { foreach ($processEvents as $processEvent) { CakeEventManager::instance()->dispatch(new CakeEvent($processEvent['key'], $this, array())); } }); return $Runner; }; }