Create the Listener

@return$this
@throws ConsoleException
490227
private function createEventListener(): self
    {
        $aFields  = $this->getArguments();
        $aCreated = [];

        try {

            $aToCreate  = [];
            $aListeners = array_filter(
                array_map(function ($sListener) {
                    return implode('/', array_map('ucfirst', explode('/', ucfirst(trim($sListener)))));
                }, explode(',', $aFields['NAME']))
            );

            sort($aListeners);

            foreach ($aListeners as $sListener) {

                $aListenerBits = explode('/', $sListener);
                $aListenerBits = array_map('ucfirst', $aListenerBits);

                $sNamespace     = $this->generateNamespace($aListenerBits);
                $sClassName     = $this->generateClassName($aListenerBits);
                $sClassNameFull = $sNamespace . '\\' . $sClassName;
                $sFilePath      = $this->generateFilePath($aListenerBits);

                //  Test it does not already exist
                if (file_exists($sFilePath)) {
                    throw new ConsoleException(
                        'An event listener at "' . $sFilePath . '" already exists'
                    );
                }

                $aToCreate[] = [
                    'NAMESPACE' => $sNamespace,
                    'CLASS_NAME' => $sClassName,
                    'CLASS_NAME_FULL' => $sClassNameFull,
                    'FILE_PATH' => $sFilePath,
                    'DIRECTORY' => dirname($sFilePath) . DIRECTORY_SEPARATOR,
                ];
            }

            $this->oOutput->writeln('The following event listeners(s) will be created:');
            foreach ($aToCreate as $aConfig) {
                $this->oOutput->writeln('');
                $this->oOutput->writeln('Class: <info>' . $aConfig['CLASS_NAME_FULL'] . '</info>');
                $this->oOutput->writeln('Path:  <info>' . $aConfig['FILE_PATH'] . '</info>');
            }
            $this->oOutput->writeln('');

            if ($this->confirm('Continue?', true)) {
                foreach ($aToCreate as $aConfig) {
                    $this->oOutput->writeln('');
                    $this->oOutput->write('Creating event listener <comment>' . $aConfig['CLASS_NAME_FULL'] . '</comment>... ');
                    $this->createPath($aConfig['DIRECTORY']);
                    $this->createFile(
                        $aConfig['FILE_PATH'],
                        $this->getResource('template/event_listener.php', $aConfig)
                    );
                    $aCreated[] = $aConfig['FILE_PATH'];
                    $this->oOutput->writeln('<info>done!</info>');

                    //  @todo (Pablo - 2019-04-30) - Add to src/Events.php if properly configured
                }
            }

        } catch (ConsoleException $e) {
            $this->oOutput->writeln('<error>failed!</error>');
            //  Clean up created services
            if (!empty($aCreated)) {
                $this->oOutput->writeln('<error>Cleaning up - removing newly created files</error>');
                foreach ($aCreated as $sPath) {
                    @unlink($sPath);
                }
            }
            throw new ConsoleException($e->getMessage());
        }

        return $this;
    }
459712
final public function notify()
  {
    $observers = array_values($this->_observers);
    foreach ($observers as $observer) {
      switch (false) {
        case is_array($observer):
        case isset($observer[0]):
        case isset($observer[1]):
        case is_string($observer[0]):
          break;
        default:
          Loader::loadClass($observer[0]);
          break;
      }

      if (!is_callable($observer)) {
        continue;
      }

      call_user_func($observer, $this);
    }

    return $this;
  }
227470
public function setEventListener($listener)
	{
		$this->ensureEventListeners();
		
		$this->_eventListeners[Ioc::resolveClassName($listener)] =  $listener;
		
		return $this;
	}
166160
protected function attachSelfToEventManager()
    {
        if (!$this->listener_attached) {
            if ($this->event_manager instanceof ListenerAwareInterface &&
                $this instanceof ListenerInterface
            ) {
                $this->event_manager->attachListener($this);
            }
            $this->listener_attached = true;
        }
    }
895850
public function run()
	{
		// Trigger event!
		$this->dispatch($this->listeners[self::LISTENER_STARTUP], [$this]);

		// Create initial request & response (PSR7!)
		$request = $this->createInitialRequest();
		$response = $this->createInitialResponse();

		try {
			// Trigger event!
			$this->dispatch($this->listeners[self::LISTENER_REQUEST], [$this, $request, $response]);

			// Right to the cycle
			$response = call_user_func(
				$this->chain,
				$request,
				$response,
				function (ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {
					return $response;
				}
			);

			// Response validation check
			if (!isset($response) || $response === null) {
				throw new RuntimeException('Final response cannot be NULL or unset');
			}
		} catch (Throwable $e) {
			// Trigger event! In case of manual handling error, returned object is passed.
			$res = $this->dispatch($this->listeners[self::LISTENER_ERROR], [$this, $e, $request, $response]);
			if ($res !== null && $res !== false) {
				return $res;
			}

			// Throw exception again if it's not caught
			if ($this->catchExceptions !== true) {
				throw $e;
			}
		}

		// Trigger event! In case of manual finalizing, returned object is passed.
		$res = $this->dispatch($this->listeners[self::LISTENER_RESPONSE], [$this, $request, $response]);
		if ($res !== null && $res !== false) {
			return $res;
		}

		// Send to finalizer (simple send response)
		return $this->finalize($request, $response);
	}
318088
public function initialize()
    {
        Notifire::reset();

        $manager = new NotificationManager();
        $manager->setThrowIfNotNotified(true);
        foreach ($this->handlers as $handler) {
            $manager->addHandler($handler);
        }

        if (null === $this->dispatcher) {
            $this->dispatcher = new EventDispatcher();
        }

        $manager->setEventDispatcher($this->dispatcher);
        foreach ($this->notifications as $notificationName => $notificationClass) {
            Notifire::addNotification($notificationName, $notificationClass);
        }

        Notifire::setManager($manager);
    }
768797
public function notifyListeners() {

        foreach ($this->listeners as $listener) {

            $listenerClass = $listener['listener'];
            $handler = array($listenerClass, 'on_' . $this->state);
            if(!class_exists($listenerClass)) {
                throw new \Exception($listenerClass . ' does not exist');
            }

            if ($this->state == $listener['event'] && is_callable($handler)) {
                unset($listener['listener']);     
                
                $eventListener = new $listenerClass($this->logger, $this->request, $this->response);
                $eventListener->setDatasources($this->datasourceFactory, $this->datasources);
                $eventListener->setDatasourceKey($this->datasourceKey);
                $eventListener->setEventDispatcher($this->eventDispatcher);
                $eventListener->setConfig($listener);
                $eventListener->setCacheManager($this->cacheManager);
                $eventListener->setContainer($this->container);

                $eventListener->execute($this->state, $this->event);

            }
        }
      
     
    }
225916
public function init()
    {
        if (Console::isCli()) {
            // fix for fcgi
            defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));

            if (!isset($_SERVER['argv'])) {
                die('This script must be run from the command line.');
            }
            $this->_runner = $this->createCommandRunner();
            $this->_runner->commands = $this->commandMap;
            $this->_runner->addCommands($this->getCommandPath());

            $env = @getenv('CONSOLE_COMMANDS');
            if (!empty($env)) {
                $this->_runner->addCommands($env);
            }

            foreach ($this->modules as $name => $settings) {
                $modulePath = Alias::get("Modules." . $name . ".Commands");
                if ($modulePath) {
                    $this->_runner->addCommands($modulePath);
                }
            }
        } else {
            // preload 'request' so that it has chance to respond to onBeginRequest event.
            $this->getComponent('request');
        }
    }
878932
public function initEventsManager()
    {
        $taskListener = new TaskListener();

        //extracts default events manager
        $eventsManager = $this->di->getShared('eventsManager');
        //attaches new event console:beforeTaskHandle and console:afterTaskHandle
        $eventsManager->attach(
            'console:beforeHandleTask', $taskListener->beforeHandleTask($this->arguments)
        );
        $eventsManager->attach(
            'console:afterHandleTask', $taskListener->afterHandleTask()
        );
        $this->application->setEventsManager($eventsManager);
    }
639207
public function listen()
    {
        $this->connection->enableQueryLog();

        $this->connection->listen(function (QueryExecuted $event) {
            $this->logQuery($event->connectionName, $event->sql, $event->bindings, $event->time);
        });
    }
231007
public function attachDefaultListeners()
    {
        parent::attachDefaultListeners();
        $events          = $this->getEventManager();
        $this->defaultListener->attach($events);
        return $this;
    }
772246
function Listener() {
		// setup abstract layer
		core.ListenerAbstract.apply(this, arguments);

		var self = this;

		// in case the process die, the connection will be severed
		this.object.on('exit', function () {
			if (self.online === true) {
				this.emit('close');
			}
		});

		process.nextTick(function () {
			// setup a new connection with the object
			self.emit('listening');

			// setup a new connection with the object
			self.emit('connection', self.object);
		});
	}
239752
private function registerListenerMakeCommand()
    {
        $this->app->bindShared('command.make.package.listener', function ($app)
        {
            return new ListenerMakeCommand($app['files'], $app['packages']);
        });

        $this->commands('command.make.package.listener');
    }
817498
public function getConsole()
  {
    if(!$this->_console)
    {
      $this->_console = new Console("Cubex Console", "4.0");
      $this->_console->setAutoExit(false);
      $this->_console->setContext($this->getContext());
      $this->_eventChannel->trigger(ConsoleCreateEvent::i($this->getContext(), $this->_console));
    }
    return $this->_console;
  }
716903
public function create()
    {
        event(new BeforeCreate($this));

        $this->beforeCreate();

        $this->doCreate();

        $this->afterCreate();

        event(new AfterCreate($this));
    }
658088
public static function instance(): self
    {
        if (!self::$instance) {
            self::$instance = new self(CallEventFactory::instance());
        }

        return self::$instance;
    }
1142519
public function listen()
    {
        if (!$this->_socketName) {
            return;
        }

        // Autoload.
        Autoloader::setRootPath($this->_autoloadRootPath);

        if (!$this->_mainSocket) {
            // Get the application layer communication protocol and listening address.
            list($scheme, $address) = explode(':', $this->_socketName, 2);
            // Check application layer protocol class.
            if (!isset(static::$_builtinTransports[$scheme])) {
                $scheme         = ucfirst($scheme);
                $this->protocol = substr($scheme,0,1)==='\\' ? $scheme : '\\Protocols\\' . $scheme;
                if (!class_exists($this->protocol)) {
                    $this->protocol = "\\Workerman\\Protocols\\$scheme";
                    if (!class_exists($this->protocol)) {
                        throw new Exception("class \\Protocols\\$scheme not exist");
                    }
                }

                if (!isset(static::$_builtinTransports[$this->transport])) {
                    throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
                }
            } else {
                $this->transport = $scheme;
            }

            $local_socket = static::$_builtinTransports[$this->transport] . ":" . $address;

            // Flag.
            $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
            $errno = 0;
            $errmsg = '';
            // SO_REUSEPORT.
            if ($this->reusePort) {
                stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
            }

            // Create an Internet or Unix domain server socket.
            $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
            if (!$this->_mainSocket) {
                throw new Exception($errmsg);
            }

            if ($this->transport === 'ssl') {
                stream_socket_enable_crypto($this->_mainSocket, false);
            } elseif ($this->transport === 'unix') {
                $socketFile = substr($address, 2);
                if ($this->user) {
                    chown($socketFile, $this->user);
                }
                if ($this->group) {
                    chgrp($socketFile, $this->group);
                }
            }

            // Try to open keepalive for tcp and disable Nagle algorithm.
            if (function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
                set_error_handler(function(){});
                $socket = socket_import_stream($this->_mainSocket);
                socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
                socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
                restore_error_handler();
            }

            // Non blocking.
            stream_set_blocking($this->_mainSocket, 0);
        }

        $this->resumeAccept();
    }