Prepare an event for emitting.

@param string|EventInterface $event

@return array
346588
protected function prepareEvent($event)
    {
        $event = $this->ensureEvent($event);
        $name = $event->getName();
        $event->setEmitter($this);

        return [$name, $event];
    }
569079
public function getListeners($event = null)
	{
		$event = $this->resolveEventName($event);

		if ($event)
		{
			if (isset($this->listeners[$event]))
			{
				return $this->listeners[$event]->getAll();
			}
			return array();
		}

		return $this->listeners;
	}
1320312
public function listenersOfEvent(Event $event)
    {
        $event_name = get_class($event);
        $this->lazyLoad($event_name);

        return array_values($this->listeners[$event_name]);
    }
375875
public function handle(EventInterface $event)
    {

        try {
            // load the application server instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();

            // write a log message that the event has been invoked
            $applicationServer->getSystemLogger()->info($event->getName());

            // and initialize a console for each node found in the configuration
            /** @var \AppserverIo\Psr\Cli\Configuration\ConsoleConfigurationInterface $consoleNode */
            foreach ($applicationServer->getSystemConfiguration()->getConsoles() as $consoleNode) {
                /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleFactoryInterface $consoleFactory */
                $consoleFactory = $consoleNode->getFactory();

                // use the factory if available
                /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleInterface $console */
                $console = $consoleFactory::factory($applicationServer, $consoleNode);

                // register the console as service
                $applicationServer->bindService(ApplicationServerInterface::ADMINISTRATION, $console);
            }

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
1139123
public function triggerEvent($event)
	{
		if (!($event instanceof EventInterface))
		{
			if (isset($this->events[$event]))
			{
				$event = $this->events[$event];
			}

			else
			{
				$event = new Event($event);
			}
		}

		if (isset($this->listeners[$event->getName()]))
		{
			foreach ($this->listeners[$event->getName()] as $listener)
			{
				if ($event->isStopped())
				{
					return $event;
				}

				if ($listener instanceof Closure)
				{
					call_user_func($listener, $event);
				}

				else
				{
					call_user_func(array($listener, $event->getName()), $event);
				}
			}
		}

		return $event;
	}
646709
public function handle(EventInterface $event)
    {
        $dir = yii::getAlias('@runtime');

        FileHelper::createDirectory($dir);
        file_put_contents($dir . DIRECTORY_SEPARATOR . 'events.log', $this->serializeEvent($event) . PHP_EOL, FILE_APPEND | LOCK_EX);
    }
614918
public function getEventCallbacks($event = null)
    {
        if ($event === null) {
            return $this->eventCallbacks;
        }

        return $this->eventCallbacks[strtolower($event)] ?? [];
    }
570296
public function handle(EventInterface $event)
    {

        try {
            // load the application server instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();

            // unbind the loggers from the naming directory
            foreach (array_keys($applicationServer->getLoggers()) as $name) {
                $applicationServer->getNamingDirectory()->unbind(sprintf('php:global/log/%s', $name));
            }

            // set the initialized loggers finally
            $applicationServer->setLoggers(array());

        } catch (\Exception $e) {
            error_log($e->__toString());
        }
    }
916672
public function setHeaders(EventInterface $event) {
        $method = $event->getRequest()->getMethod();

        // Obviously we shouldn't bother doing any HTTP caching logic for non-GET/HEAD requests
        if ($method !== 'GET' && $method !== 'HEAD') {
            return;
        }

        $response = $event->getResponse();
        $headers = $event->getResponse()->headers;

        // Imbo defaults to 'public' as cache-control value - if it has changed from this value,
        // assume the resource requested has explicitly defined its own caching rules and fall back
        if ($headers->get('Cache-Control') !== 'public') {
            return;
        }

        // Get configured HTTP cache defaults from configuration, then apply them
        $config = $event->getConfig()['httpCacheHeaders'];

        if (isset($config['maxAge'])) {
            $response->setMaxAge((int) $config['maxAge']);
        }

        if (isset($config['sharedMaxAge'])) {
            $response->setSharedMaxAge($config['sharedMaxAge']);
        }

        if (isset($config['public']) && $config['public']) {
            $response->setPublic();
        } else if (isset($config['public'])) {
            $response->setPrivate();
        }

        if (isset($config['mustRevalidate']) && $config['mustRevalidate']) {
            $headers->addCacheControlDirective('must-revalidate');
        }
    }
479954
public function beforePrepare(Event $event)
	{
		$command = $event['command'];
		$operation = $command->getOperation();

		if ($command->getName() !== 'updateEntity' && $command->offsetExists('_id') === true) return;

		$operation->addParam(new Parameter(array(
			'name' => 'body_id',
			'location' => 'json',
			'type' => 'string',
			'default' => $command->offsetGet('_id'),
			'static' => true,
			'sentAs' => '_id'
		)));
	}
401054
public function containsEvent(EventInterface $event)
    {
        return
            $event->containsPeriod($this) ||
            $event->isDuring($this) ||
            $this->contains($event->getBegin()) ||
            ($event->getEnd() && $this->contains($event->getEnd())  && $event->getEnd()->format('c') !== $this->begin->format('c'))
        ;
    }
316771
public function handle(EventInterface $event)
    {
        $events = array_filter($this->listener, function (string $eventName) use ($event): bool {
            return fnmatch($eventName, $event->getName());
        }, ARRAY_FILTER_USE_KEY);

        $events = array_reduce($events, 'array_merge', []);

        array_walk(
            $events,
            /**
             * @param mixed $item
             * @return void
             */
            function ($item) use ($event) {
                if ($item instanceof ListenerInterface) {
                    $item->handle($event);

                    return;
                }
                if (\is_callable($item)) {
                    $item($event);
                }
            }
        );
    }
1126777
public function format(EventInterface $event) {
        $response = $event->getResponse();
        $model = $response->getModel();

        if ($response->getStatusCode() === 204 || !$model) {
            // No content to write
            return;
        }

        $request = $event->getRequest();

        // If we are dealing with an image we want to trigger an event that handles a possible
        // conversion
        if ($model instanceof Model\Image) {
            $outputConverterManager = $event->getOutputConverterManager();
            $eventManager = $event->getManager();

            if (
                ($model->getExtension() !== $this->formatter) &&
                ($outputConverterManager->getMimeTypeFromExtension($this->formatter) !== $model->getMimeType()) &&
                $outputConverterManager->supportsExtension($this->formatter)
            ) {
                $outputConverterManager->convert($model, $this->formatter);
            // for clarity - if we just have a requested compression / quality value, we still have to invoke the
            // conversion / writer for the existing format
            } else if (
                $model->getOutputQualityCompression() &&
                $outputConverterManager->supportsExtension($this->formatter)
            ) {
                $outputConverterManager->convert($model, $this->formatter);
            }

            // Finished transforming the image
            $eventManager->trigger('image.transformed', ['image' => $model]);

            $formattedData = $model->getBlob();
            $contentType = $model->getMimeType();
        } else {
            // Create an instance of the formatter
            $formatter = $this->formatters[$this->formatter];

            $formattedData = $formatter->format($model);
            $contentType = $formatter->getContentType();
        }

        if ($contentType === 'application/json') {
            foreach (['callback', 'jsonp', 'json'] as $validParam) {
                if ($request->query->has($validParam)) {
                    $formattedData = sprintf("%s(%s)", $request->query->get($validParam), $formattedData);
                    break;
                }
            }
        }

        $response->headers->add([
            'Content-Type' => $contentType,
            'Content-Length' => strlen($formattedData),
        ]);

        if ($request->getMethod() !== 'HEAD') {
            $response->setContent($formattedData);
        }
    }
1291501
public function loadStats(EventInterface $event) {
        $response = $event->getResponse();
        $database = $event->getDatabase();

        $statsModel = new Model\Stats();
        $statsModel->setNumUsers($database->getNumUsers());
        $statsModel->setNumBytes($database->getNumBytes());
        $statsModel->setNumImages($database->getNumImages());

        $response->setModel($statsModel);
    }
249656
public function handle(EventInterface $event)
    {

        try {
            // load the application server, naming directory and system configuration instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */
            $namingDirectory = $applicationServer->getNamingDirectory();
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */
            $systemConfiguration = $applicationServer->getSystemConfiguration();

            // initialize the loggers
            $loggers = array();
            foreach ($systemConfiguration->getLoggers() as $loggerNode) {
                $loggers[$loggerNode->getName()] = LoggerFactory::factory($loggerNode);
            }

            // register the logger callbacks in the naming directory
            foreach ($loggers as $name => $logger) {
                $namingDirectory->bind(sprintf('php:global/log/%s', $name), $logger);
            }

            // set the initialized loggers finally
            $applicationServer->setLoggers($loggers);

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
1075425
public function process(EventInterface $event)
    {
        $events = $this->getEventManager();
        $mapper = $this->getMapper();
        $optionsProvider = $this->getOptionsProvider();
        $translator = $this->getTranslator();
        $pane = $event->getParam('pane');
        if (! $optionsProvider->hasIdentifier($pane)) {
            return;
        }
        $options = $optionsProvider->getOptions($pane);
        if ($options->getType() == 'search' || $options->getRoot() == 'site') {
            return;
        }
        try {
            $mapper->beginTransaction();
            $tid = $mapper->getTransactionIdentifier();
            $events->trigger(
                __FUNCTION__ . '.clean.pre',
                null,
                [
                    'tid' => $tid,
                ]
            );
            $mapper->clean($tid);
            $mapper->commit();
        } catch (Exception $e) {
            if (DEBUG_MODE) {
                throw new DebugException(
                    $translator->translate('Error: ') . $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            $meta = $mapper->findMetaById($id);
            $name = isset($meta['title']) ? $meta['title'] : $id;
            $this->setValue($name)->error(self::UnexpectedError);
        }

        return $this->redirect($event, 'sc-admin/file/delete');
    }
209013
public function handle(EventInterface $event)
    {

        try {
            // load the application server and the naming directory instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */
            $namingDirectory = $applicationServer->getNamingDirectory();

            // load the configuration filename
            $configurationFilename = $applicationServer->getConfigurationFilename();

            // write a log message that the event has been invoked
            $applicationServer->getSystemLogger()->info($event->getName());

            // load the setup mode from the naming directory
            $setupMode = $namingDirectory->search('php:env/args/s');
            $currentUser = $namingDirectory->search('php:env/currentUser');

            // load the service instance and switch to the new setup mode
            /** @var \AppserverIo\Appserver\Core\Api\ContainerService $service */
            $service = $applicationServer->newService('AppserverIo\Appserver\Core\Api\ContainerService');
            $service->switchSetupMode($setupMode, $configurationFilename, $currentUser);

        } catch (NamingException $ne) {
            $applicationServer->getSystemLogger()->error('Please specify a setup mode, e. g. \'./server.php -s prod\'');
        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }