/** * Initializes this sfLogger instance. * * Available options: * * - level: The log level. * * @param sfEventDispatcher $dispatcher A sfEventDispatcher instance * @param array $options An array of options. * * @return Boolean true, if initialization completes successfully, otherwise false. * * @throws <b>sfInitializationException</b> If an error occurs while initializing this sfLogger. */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { if (isset($options['level'])) { $this->setLogLevel($options['level']); } $dispatcher->connect('application.log', array($this, 'listenToLogEvent')); }
/** * Main entry point into the application. * * @return void */ public function main() { $runner = new DocBlox_Task_Runner($_SERVER['argc'] == 1 ? false : $_SERVER['argv'][1], 'project:run'); $task = $runner->getTask(); $threshold = DocBlox_Core_Log::WARN; if (!$task->getQuiet()) { DocBlox_Core_Application::renderVersion(); } else { $threshold = DocBlox_Core_Log::QUIET; } if ($task->getVerbose()) { $threshold = DocBlox_Core_Log::DEBUG; } $dispatcher = new sfEventDispatcher(); $logger = new DocBlox_Core_Log(DocBlox_Core_Log::FILE_STDOUT); $logger->setThreshold($threshold); $dispatcher->connect('system.log', array($logger, 'log')); DocBlox_Parser_Abstract::$event_dispatcher = $dispatcher; DocBlox_Transformer_Abstract::$event_dispatcher = $dispatcher; DocBlox_Reflection_Abstract::$event_dispatcher = $dispatcher; try { $task->execute(); } catch (Exception $e) { if (!$task->getQuiet()) { echo 'ERROR: ' . $e->getMessage() . PHP_EOL . PHP_EOL; echo $task->getUsageMessage(); } die(1); } }
/** * @see xfLogger */ public function log($message, $section = 'sfSearch') { $message = preg_replace('/"(.+?)"/e', '$this->formatter->format("\\1", array("fg" => "blue", "bold" => true));', $message); $message = preg_replace('/\\.{3}$/e', '$this->formatter->format("...", array("fg" => "red", "bold" => true));', $message); $message = preg_replace('/(Warning|Error)!/e', '$this->formatter->format("\\1!", array("fg" => "red", "bold" => true));', $message); $this->dispatcher->notify(new sfEvent($this, 'command.log', array($this->formatter->format($section, array('fg' => 'green', 'bold' => true)) . ' >> ' . $message))); }
public static function notifyPostExecuteActionEvent($subject, sfEventDispatcher $dispatcher, sfAction $actionInstance, $result) { $moduleName = $actionInstance->getModuleName(); $actionName = $actionInstance->getActionName(); $params = array('moduleName' => $moduleName, 'actionName' => $actionName, 'actionInstance' => $actionInstance, 'result' => $result); $dispatcher->notify(new sfEvent($subject, 'op_action.post_execute_' . $moduleName . '_' . $actionName, $params)); $dispatcher->notify(new sfEvent($subject, 'op_action.post_execute', $params)); }
protected function _start() { $formatter = new sfFormatter(80); $dispatcher = new sfEventDispatcher(); $dispatcher->connect('command.log', array($this, "logTask")); $this->taskLog = array(); $this->task = new InstallNotifierTask($dispatcher, $formatter); }
/** * Initializes this logger. * * Available options: * * - logger_service_id: The service id to use as the logger. Default: logger.psr * - auto_connect: If we must connect automatically to the context.load_factories to set the logger. Default: true * * @param sfEventDispatcher $dispatcher * @param array $options * * @return void */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { if (isset($options['logger_service_id'])) { $this->loggerServiceId = $options['logger_service_id']; } if (!isset($options['auto_connect']) || $options['auto_connect']) { $dispatcher->connect('context.load_factories', array($this, 'listenContextLoadFactoriesEvent')); } parent::initialize($dispatcher, $options); }
/** * Initializes this logger. * * Available options: * * - web_debug_class: The web debug class (sfWebDebug by default). * * @param sfEventDispatcher $dispatcher A sfEventDispatcher instance * @param array $options An array of options. * * @return Boolean true, if initialization completes successfully, otherwise false. * * @see sfVarLogger */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { $this->context = sfContext::getInstance(); $this->dispatcher = $dispatcher; $this->webDebugClass = isset($options['web_debug_class']) ? $options['web_debug_class'] : 'sfWebDebug'; if (sfConfig::get('sf_web_debug')) { $dispatcher->connect('response.filter_content', array($this, 'filterResponseContent')); } return parent::initialize($dispatcher, $options); }
/** * Initialize symfony propel * * @param sfEventDispatcher $dispatcher * @param string $culture * * @deprecated Moved to {@link sfPropelPluginConfiguration} */ public static function initialize(sfEventDispatcher $dispatcher, $culture = null) { $dispatcher->notify(new sfEvent(__CLASS__, 'application.log', array(__METHOD__ . '() has been deprecated. Please call sfPropel::setDefaultCulture() to set the culture.', 'priority' => sfLogger::NOTICE))); if (null !== $culture) { self::setDefaultCulture($culture); } else { if (class_exists('sfContext', false) && sfContext::hasInstance() && ($user = sfContext::getInstance()->getUser())) { self::setDefaultCulture($user->getCulture()); } } }
/** * Initializes this logger. * * Available options: * * * web_debug_class: The web debug class (sfWebDebug by default) * * @param sfEventDispatcher $dispatcher A sfEventDispatcher instance * @param array $options An array of options. * * @return Boolean true, if initialization completes successfully, otherwise false. * * @see sfVarLogger */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { $this->context = sfContext::getInstance(); $this->webDebugClass = isset($options['web_debug_class']) ? $options['web_debug_class'] : 'sfWebDebug'; if (sfConfig::get('sf_web_debug')) { $dispatcher->connect('context.load_factories', array($this, 'listenForLoadFactories')); $dispatcher->connect('response.filter_content', array($this, 'filterResponseContent')); } $this->registerErrorHandler(); return parent::initialize($dispatcher, $options); }
/** * Dispatches an event to the Event Dispatcher. * * This method tries to dispatch an event; if no Event Dispatcher has been * set than this method will explicitly not fail and return null. * * By not failing we make the Event Dispatcher optional and is it easier * for people to re-use this component in their own application. * * @param string $name Name of the event to dispatch. * @param string[] $arguments Arguments for this event. * * @throws DocBlox_Parser_Exception if there is a dispatcher but it is not * of type sfEventDispatcher * * @return mixed|null */ public function dispatch($name, $arguments) { if (!self::$event_dispatcher) { return null; } if (!self::$event_dispatcher instanceof sfEventDispatcher) { throw new DocBlox_Parser_Exception('Expected the event dispatcher to be an instance of ' . 'sfEventDispatcher'); } $event = self::$event_dispatcher->notify(new sfEvent($this, $name, $arguments)); return $event ? $event->getReturnValue() : null; }
public static function initialize(sfEventDispatcher $dispatcher, $culture = null) { $dispatcher->connect('user.change_culture', array('sfPropel', 'listenToChangeCultureEvent')); if (!is_null($culture)) { self::setDefaultCulture($culture); } else { if (class_exists('sfContext', false) && sfContext::hasInstance() && ($user = sfContext::getInstance()->getUser())) { self::setDefaultCulture($user->getCulture()); } } self::$initialized = true; }
public function initialize(sfEventDispatcher $dispatcher, $options = array()) { $this->sfFire = sfFirePHP::getInstance(true); if (isset($options['processor'])) { sfFirePHP::setProcessor($options['processor'] . '?' . time()); } if (isset($options['renderer'])) { sfFirePHP::setRenderer($options['renderer'] . '?' . time()); } $dispatcher->connect('response.filter_content', array($this, 'filterResponseContent')); $this->dispatcher = $dispatcher; return parent::initialize($dispatcher, $options); }
/** * Constructor. * * Available options: * * * charset: The default charset to use for messages * * logging: Whether to enable logging or not * * delivery_strategy: The delivery strategy to use * * spool_class: The spool class (for the spool strategy) * * spool_arguments: The arguments to pass to the spool constructor * * delivery_address: The email address to use for the single_address strategy * * transport: The main transport configuration * * * class: The main transport class * * * param: The main transport parameters * * @param sfEventDispatcher $dispatcher An event dispatcher instance * @param array $options An array of options */ public function __construct(sfEventDispatcher $dispatcher, $options) { // options $options = array_merge(array('charset' => 'UTF-8', 'logging' => false, 'delivery_strategy' => 'realtime', 'transport' => array('class' => 'Swift_MailTransport', 'param' => array())), $options); $constantName = 'sfMailer::' . strtoupper($options['delivery_strategy']); $this->strategy = defined($constantName) ? constant($constantName) : false; if (!$this->strategy) { throw new InvalidArgumentException(sprintf('Unknown mail delivery strategy "%s" (should be one of realtime, spool, single_address, or none)', $options['delivery_strategy'])); } // transport $class = $options['transport']['class']; $transport = new $class(); if (isset($options['transport']['param'])) { foreach ($options['transport']['param'] as $key => $value) { $method = 'set' . ucfirst($key); if (method_exists($transport, $method)) { $transport->{$method}($value); } elseif (method_exists($transport, 'getExtensionHandlers')) { foreach ($transport->getExtensionHandlers() as $handler) { if (in_array(strtolower($method), array_map('strtolower', (array) $handler->exposeMixinMethods()))) { $transport->{$method}($value); } } } } } $this->realtimeTransport = $transport; if (sfMailer::SPOOL == $this->strategy) { if (!isset($options['spool_class'])) { throw new InvalidArgumentException('For the spool mail delivery strategy, you must also define a spool_class option'); } $arguments = isset($options['spool_arguments']) ? $options['spool_arguments'] : array(); if ($arguments) { $r = new ReflectionClass($options['spool_class']); $this->spool = $r->newInstanceArgs($arguments); } else { $this->spool = new $options['spool_class'](); } $transport = new Swift_SpoolTransport($this->spool); } elseif (sfMailer::SINGLE_ADDRESS == $this->strategy) { if (!isset($options['delivery_address'])) { throw new InvalidArgumentException('For the single_address mail delivery strategy, you must also define a delivery_address option'); } $this->address = $options['delivery_address']; $transport->registerPlugin($this->redirectingPlugin = new Swift_Plugins_RedirectingPlugin($this->address)); } parent::__construct($transport); // logger if ($options['logging']) { $this->logger = new sfMailerMessageLoggerPlugin($dispatcher); $transport->registerPlugin($this->logger); } if (sfMailer::NONE == $this->strategy) { // must be registered after logging $transport->registerPlugin(new Swift_Plugins_BlackholePlugin()); } // preferences Swift_Preferences::getInstance()->setCharset($options['charset']); $dispatcher->notify(new sfEvent($this, 'mailer.configure')); }
/** * Initializes this logger. * * @param sfEventDispatcher $dispatcher A sfEventDispatcher instance * @param array $options An array of options. * * @return Boolean true, if initialization completes successfully, otherwise false. */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { $this->context = sfContext::getInstance(); $this->dispatcher = $dispatcher; $class = isset($options['web_debug_class']) ? $options['web_debug_class'] : 'sfWebDebug'; $this->webDebug = new $class($dispatcher); $dispatcher->connect('response.filter_content', array($this, 'filterResponseContent')); if (isset($options['xdebug_logging'])) { $this->xdebugLogging = $options['xdebug_logging']; } // disable xdebug when an HTTP debug session exists (crashes Apache, see #2438) if (isset($_GET['XDEBUG_SESSION_START']) || isset($_COOKIE['XDEBUG_SESSION'])) { $this->xdebugLogging = false; } return parent::initialize($dispatcher, $options); }
public function handleEventMessage(sfEvent $event) { $message = $this->notifier()->decoratedMessage($event->getSubject()); $message->addSection('Message Details', $event->getParameters()); $message->addSection('Server', $this->notifier()->helper()->formatServer()); $this->dispatcher->notify(new sfEvent($message, 'notify.decorate_message')); $this->notifier()->driver()->notify($message); }
/** * Подготовить таск (мок), запустить и проверить вызовы методов * * @param array $ntfnList - Массив OperationNotification * @param bool $isOk - Успешно отправить уведомления */ private function runAndCheckTask(array $ntfnList, $isOk) { // Мок таска - перекроем 'getEventsFromQueue', чтобы изолировать логику // выборки уведомлений. И будем свои уведомления на отправку $task = $this->getMock('myOperationNotificationTask', array('getEventsFromQueue'), array($dispatcher = new sfEventDispatcher(), new sfFormatter())); $task->expects($this->once())->method('getEventsFromQueue')->will($this->returnValue($ntfnList)); // Создаем и регистрируем обработчик уведомлении и будем проверять его вызовы $handler = $this->getMock('myNotificationHandlerInterface', array('run')); $handler->expects($this->exactly(count($ntfnList)))->method('run')->will($this->returnValue($isOk)); foreach ($ntfnList as $ntfn) { $task->registerHandler($ntfn->getType(), $handler); } // Повесим собственный обработчик на логи таска, чтобы их сохранять и проверять $dispatcher->connect('command.log', array($this, 'handleTaskLogs')); // Запустить таск $task->run($args = array(), $options = array('env' => 'test')); }
/** * * @param Exception $e * * @return void */ public function handleException(Exception $e) { $message = $this->notifier()->decoratedMessage($e->getMessage()); $message->addSection('Exception', $this->notifier()->helper()->formatException($e)); $message->addSection('Server', $this->notifier()->helper()->formatServer()); $this->dispatcher->notify(new sfEvent($message, 'notify.exception')); $this->notifier()->driver()->notify($message); }
public function register($file) { if (!file_exists($file) || !is_readable($file)) { throw new Exception('The plugin file "' . $file . '" must exist and be readable'); } $reflection = new DocBlox_Reflection_File($file); $classes = $reflection->getClasses(); if (count($classes) > 1) { throw new Exception('Plugin file should only contain one class'); } /** @var DocBlox_Reflection_Class $listener_definition */ $listener_definition = reset($classes); // initialize the plugin / event listener include_once $file; $listener_name = $listener_definition->getName(); $listener = new $listener_name($this->event_dispatcher); // connect all events of the each method to the event_dispatcher foreach ($listener_definition->getMethods() as $method) { /** @var DocBlox_Reflection_Tag $event */ foreach ($method->getDocBlock()->getTagsByName('event') as $event) { $this->event_dispatcher->connect($event->getDescription(), array($listener, $method->getName())); } } }
/** * Initialize sfymfony propel * * @param sfEventDispatcher $dispatcher * @param string $culture */ public static function initialize(sfEventDispatcher $dispatcher, $culture = null) { if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) { // add propel logger Propel::setLogger(new sfPropelLogger($dispatcher)); } // propel initialization $configuration = sfPropelDatabase::getConfiguration(); if ($configuration) { Propel::setConfiguration($configuration); if (!Propel::isInit()) { Propel::initialize(); } } $dispatcher->connect('user.change_culture', array('sfPropel', 'listenToChangeCultureEvent')); if (!is_null($culture)) { self::setDefaultCulture($culture); } else { if (class_exists('sfContext', false) && sfContext::hasInstance() && ($user = sfContext::getInstance()->getUser())) { self::setDefaultCulture($user->getCulture()); } } self::$initialized = true; }
/** * Returns whether or not inline editing should be enabled. * * This method can be called "in general" (no $obj passed) or answered * for a very specific object being modified. * * @param Object $object The Object being edited - could be a Doctrine_Record, Doctrine_Collection * @return boolean */ public function shouldShowEditor($obj = null, $forceRefresh = false) { $key = $obj === null ? 'generic' : spl_object_hash($obj); if (!isset($this->_shouldShowEditor[$key]) || $forceRefresh) { $credential = $this->getOption('admin_credential'); if ($credential) { $shouldShow = $this->_user->hasCredential($credential); } else { // even if no credential were passed, still require a login at least $shouldShow = $this->_user->isAuthenticated(); } $event = new sfEvent($this, 'editable_content.should_show_editor', array('user' => $this->_user, 'object' => $obj)); $this->_dispatcher->filter($event, $shouldShow); $this->_shouldShowEditor[$key] = $event->getReturnValue(); } return $this->_shouldShowEditor[$key]; }
/** * Initializes this logger. * * @param sfEventDispatcher $dispatcher A sfEventDispatcher instance * @param array $options An array of options. */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { $dispatcher->connect('command.log', array($this, 'listenToLogEvent')); return parent::initialize($dispatcher, $options); }
public function notify(sfEvent $event) { $this->_events[] = $event; return parent::notify($event); }
/** * Notify all listeners of the event, through the event dispatcher instance for the class. This is just a convenience method to * avoid accessing the event dispatcher directly * * @param sfEvent $event The event that has occured */ function notify($event) { $this->eventdispatcher->notify($event); }
public function connect(sfEventDispatcher $dispatcher) { $dispatcher->connect('routing.load_configuration', array($this, 'updateDefaultConfig')); }
$dispatcher = new sfEventDispatcher(); $dispatcher->connect('foo', array($listener, 'listenToFooBis')); $dispatcher->connect('foo', array($listener, 'listenToFoo')); $e = $dispatcher->notifyUntil($event = new sfEvent(new stdClass(), 'foo')); $t->is($listener->getValue(), 'listenToFooBis', '->notifyUntil() notifies all registered listeners in order and stops if it returns true'); // ->filter() $t->diag('->filter()'); $listener->reset(); $dispatcher = new sfEventDispatcher(); $dispatcher->connect('foo', array($listener, 'filterFoo')); $dispatcher->connect('foo', array($listener, 'filterFooBis')); $e = $dispatcher->filter($event = new sfEvent(new stdClass(), 'foo'), 'foo'); $t->is($e->getReturnValue(), '-*foo*-', '->filter() filters a value'); $t->is($e, $event, '->filter() returns the event object'); $listener->reset(); $dispatcher = new sfEventDispatcher(); $dispatcher->connect('foo', array($listener, 'filterFooBis')); $dispatcher->connect('foo', array($listener, 'filterFoo')); $e = $dispatcher->filter($event = new sfEvent(new stdClass(), 'foo'), 'foo'); $t->is($e->getReturnValue(), '*-foo-*', '->filter() filters a value'); class Listener { protected $value = ''; function filterFoo(sfEvent $event, $foo) { return "*{$foo}*"; } function filterFooBis(sfEvent $event, $foo) { return "-{$foo}-"; }
/** * @package sfLucenePlugin * @subpackage Test * @author Carl Vondrick * @version SVN: $Id: sfLuceneEventConnectorTest.php 7108 2008-01-20 07:44:42Z Carl.Vondrick $ */ require dirname(__FILE__) . '/../../bootstrap/unit.php'; $t = new limeade_test(5, limeade_output::get()); $limeade = new limeade_sf($t); $app = $limeade->bootstrap(); class FooListener { public $event; public function listen($event) { $this->event = $event; } } $source = new sfEventDispatcher(); $target = new sfEventDispatcher(); $connector = new sfLuceneEventConnector($source, 'foo', $target, 'bar'); $t->ok($source->hasListeners('foo'), '__construct() connects a listener to the source'); $subject = 'Fabien'; $params = array('a', 'b', 'c'); $listener = new FooListener(); $target->connect('bar', array($listener, 'listen')); $source->notify(new sfEvent($subject, 'foo', $params)); $t->isa_ok($listener->event, 'sfEvent', 'calling a linked event calls target'); $t->is($listener->event->getSubject(), $subject, 'calling a linked event sends correct subject'); $t->is($listener->event->getName(), 'bar', 'calling a linked event sends correct name'); $t->is($listener->event->getParameters(), $params, 'calling a linked event sends correct parameters');
/** * This file is part of the sfSearch package. * (c) Carl Vondrick <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require dirname(__FILE__) . '/../../bootstrap/unit.php'; require 'log/xfLogger.interface.php'; require 'log/xfLoggerTask.class.php'; require 'event/sfEvent.class.php'; require 'event/sfEventDispatcher.class.php'; require 'command/sfFormatter.class.php'; $t = new lime_test(3, new lime_output_color()); $formatter = new sfFormatter(); $dispatcher = new sfEventDispatcher(); function handle(sfEvent $event = null) { static $got; if ($event) { $got = $event; } else { return $got; } } $dispatcher->connect('command.log', 'handle'); $logger = new xfLoggerTask($dispatcher, $formatter); $logger->log('Did something', 'MySearch'); $t->is(handle()->getSubject(), $logger, '->log() logs with the logger as the subject'); $t->is(handle()->getParameters(), array('MySearch >> Did something'), '->log() formats the message'); $t->is(handle()->getName(), 'command.log', '->log() notifies the correct event');
public function connect(sfEventDispatcher $dispatcher) { $dispatcher->connect('template.filter_parameters', array($this, 'filterParameters')); }
// ->getCurrentInternalUri() $t->diag('->getCurrentInternalUri()'); $r->clearRoutes(); $r->connect('test2', new sfRoute('/module/action/:id', array('module' => 'foo', 'action' => 'bar'))); $r->connect('test', new sfRoute('/:module', array('action' => 'index'))); $r->connect('test1', new sfRoute('/:module/:action/*', array())); $r->connect('test3', new sfRoute('/', array())); $r->parse('/'); $t->is($r->getCurrentInternalUri(), 'default/index', '->getCurrentInternalUri() returns the internal URI for last parsed URL'); $r->parse('/foo/bar/bar/foo/a/b'); $t->is($r->getCurrentInternalUri(), 'foo/bar?a=b&bar=foo', '->getCurrentInternalUri() returns the internal URI for last parsed URL'); $r->parse('/module/action/2'); $t->is($r->getCurrentInternalUri(true), '@test2?id=2', '->getCurrentInternalUri() returns the internal URI for last parsed URL'); // Lazy routes config cache $t->diag('Lazy Routes Config Cache'); $dispatcher = new sfEventDispatcher(); $dispatcher->connect('routing.load_configuration', 'configureRouting'); function configureRouting($event) { $event->getSubject()->connect('first', new sfRoute('/first')); $event->getSubject()->connect('second', new sfRoute('/', array())); } // these tests are against r7363 $t->is($r->getCurrentInternalUri(false), 'foo/bar?id=2', '->getCurrentInternalUri() returns the internal URI for last parsed URL'); $t->is($r->getCurrentInternalUri(true), '@test2?id=2', '->getCurrentInternalUri() returns the internal URI for last parsed URL'); $t->is($r->getCurrentInternalUri(false), 'foo/bar?id=2', '->getCurrentInternalUri() returns the internal URI for last parsed URL'); // regression for ticket #3423 occuring when cache is used. (for the test its enough to have it non null) $rCached = new sfPatternRoutingTest(new sfEventDispatcher(), new sfNoCache(), $options); $rCached->connect('test', new sfRoute('/:module', array('action' => 'index'))); $rCached->connect('test2', new sfRoute('/', array())); $rCached->parse('/');
/** * @see xfLogger */ public function log($message, $section = 'sfSearch') { $this->dispatcher->notify(new sfEvent($this, $this->event, array($message, 'section' => $section))); }