Command handler

@param KCommandInterface         $command    The command
@param KCommandChainInterface    $chain      The chain executing the command
@return mixed|null If a handler breaks, returns the break condition. NULL otherwise.
487861
public function execute(KCommandInterface $command, KCommandChainInterface $chain)
    {
        $type    = '';
        $package = '';
        $subject = '';

        if ($command->getSubject())
        {
            $identifier = $command->getSubject()->getIdentifier()->toArray();
            $package    = $identifier['package'];

            if ($identifier['path'])
            {
                $type    = array_shift($identifier['path']);
                $subject = $identifier['name'];
            }
            else $type = $identifier['name'];
        }

        $parts  = explode('.', $command->getName());
        $when   = array_shift($parts);               // Before or After
        $name   = KStringInflector::implode($parts); // Read Dispatch Select etc.

        // Create Specific and Generic event names
        $event_specific = 'on'.ucfirst($when).ucfirst($package).ucfirst($subject).ucfirst($type).$name;
        $event_generic  = 'on'.ucfirst($when).ucfirst($type).$name;

        // Clone the context
        if($this->_immutable) {
            $event = clone($command);
        } else {
            $event = $command;
        }

        // Create event object to check for propagation
        $event = $this->getEventPublisher()->publishEvent($event_specific, $event->getAttributes(), $event->getSubject());

        // Ensure event can be propagated and event name is different
        if ($event->canPropagate() && $event_specific != $event_generic)
        {
            $event->setName($event_generic);
            $this->getEventPublisher()->publishEvent($event);
        }
    }
1058565
public function findCommandHandlerFor(Command $command)
    {
        if (!isset($this->subscriptions[$command->commandName()])) {
            throw new CommandHandlerNotFoundException(sprintf('No handler was found for command %s', $command->commandName()));
        }

        return $this->subscriptions[$command->commandName()];
    }
821528
private function execute(CommandInterface $command)
    {
        $handler = $this->locator->locate($command);

        if (!$handler->supports($command)) {
            throw new InvalidCommandException(sprintf('The registered command handler doesn\'t support "%s"', get_class($command)));
        }

        $this->executing = true;

        $handler->execute($command);

        $this->executing = false;
    }
515953
public function execute($command, callable $next)
    {
        if (! $command instanceof NamedCommand) {
            throw new \InvalidArgumentException('Command must be a NamedCommand');
        }

        $this->queuePublisher->publish($this->serializer->serialize($command), $command->getCommandName());
    }
776095
public function runCommand(Command $command, InputInterface $input, OutputInterface $output) {
    return $this->doRunCommand($command, $input, $output);
  }
52117
public function handle(Command $command, UnitOfWork $unitOfWork, InterceptorChain $interceptorChain)
    {
        $auditListener = new AuditUnitOfWorkListener($command, $this->auditDataProvider, $this->auditLogger);
        $unitOfWork->registerListener($auditListener);

        $result = $interceptorChain->proceed();
        $auditListener->setResult($result);

        return $result;
    }
381798
public function execute($command)
    {
        $this->executeDecorators($command);

        $handler = $this->commandTranslator->toCommandHandler($command);

        return $this->app->make($handler)->handle($command);
    }
1135683
public function execute($command, $context)
    {
        if (!$context instanceof  AnCommandContext) {
            $context = new AnCommandContext($context);
        }

        $parts = explode('.', $command);
        $method = '_'.$parts[0].'Entity'.ucfirst($parts[1]);
        $result = null;

        if (method_exists($this, $method)) {
            $result = $this->$method($context);
        }

        return $result;
    }
805130
public function handle(CommandInterface $command)
    {
        $object = $command->getParameter('data');

        if ($command->hasParameter('class')) {
            $class = $command->getParameter('class');
            if (!($object instanceof $class)) {
                return CommandResult::error('invalid_instance');
            }
        }

        $this->objectManager->persist($object);
        $this->objectManager->flush();
    }
884313
public function dispatch(CommandInterface $command, bool $qeueEvents = false): void
    {
        try {
            if ($command instanceof CommandInterface) {
                // Reset aggregates.
                $this->aggregates = [];

                /**
                 * Get Handler for Command.
                 *
                 * @var HandlerInterface $handler
                 */
                $handlerClass = $command->getHandlerClass();
                $handler = new $handlerClass($this->messageBus, $this->aggregateFactory);

                if ($handler instanceof HandlerInterface) {
                    // Invoke Handler.
                    $handler($command, $this->aggregates);

                    // Check for events on aggregates, pass them to EventBus#publish()
                    $events = [];

                    /** @var AggregateInterface $aggregate */
                    foreach ($this->aggregates as $aggregate) {
                        /** @var array $pendingEvents */
                        $pendingEvents = $aggregate->getPendingEvents();

                        $events += $pendingEvents;
                    }

                    $this->eventBus->publish($events, $this, $qeueEvents);
                } else {
                    throw new InterfaceException(\get_class($handler).' must implement '.HandlerInterface::class);
                }
            } else {
                throw new InterfaceException(\get_class($command).' must implement '.CommandInterface::class);
            }
        } catch (InterfaceException $e) {
            $this->messageBus->dispatch(new Message(
                $e->getMessage(),
                $e->getCode(),
                $command->getUuid(),
                $command->getAggregateUuid(),
                $e
            ));
        }
    }
1055162
final public function handle(CommandInterface $command)
    {
        $this->validateCommand($command);

        try {
            // @todo - Update this to return the succes event object, rather than using the getSuccessEvent() method
            $this->_handle($command);
        } catch (\Exception $exception) {

            // Log exception
            $commandClass = get_class($command);
            $this->logError(
                "Exception throw while handling {$commandClass} command... {$exception->getMessage()}\n",
                $exception
            );

            // Fire failure event
            $this->emit($this->getFailureEvent($exception));

            throw $exception;
        }

        $event = $this->getSuccessEvent($command);
        $this->emit($event);
    }
1271894
public function execute($command, callable $next)
    {
        if ($this->authorizationChecker->isGranted('handle', $command)) {
            return $next($command);
        }

        throw new AccessDeniedException(
            sprintf('The current user is not allowed to handle command of type \'%s\'', get_class($command))
        );
    }
774847
public function resolve(Command $command)
    {
        $commandName = get_class($command);

        // Find the CommandHandler if it has been manually defined using pushHandler()
        foreach ($this->handlers as $handlerCommand => $handler) {
            if ($handlerCommand == $commandName) {
                return $handler;
            }
        }

        // If the Command also implements CommandHandler, then it can handle() itself
        if ($command instanceof CommandHandler) {
            return $command;
        }

        // Try and guess the handler's name in the same namespace with suffix "Handler"
        $class = $commandName . 'Handler';
        if (class_exists($class)) {
            return $this->container->make($class);
        }

        // Try and guess the handler's name in nested "Handlers" namespace with suffix "Handler"
        $classParts = explode('\\', $commandName);
        $commandNameWithoutNamespace = array_pop($classParts);
        $class = implode('\\', $classParts) . '\\Handlers\\' . $commandNameWithoutNamespace . 'Handler';
        if (class_exists($class)) {
            return $this->container->make($class);
        }

        throw new UnresolvableCommandHandlerException('Could not resolve a handler for [' . get_class($command) . ']');
    }
400420
public function executeCommand(CommandInterface $command)
    {
        $this->initialize();

        if ($this->state->isCAS()) {
            return $this->client->executeCommand($command);
        }

        $response = $this->client->getConnection()->executeCommand($command);

        if ($response instanceof StatusResponse && $response == 'QUEUED') {
            $this->commands->enqueue($command);
        } elseif ($response instanceof ErrorResponseInterface) {
            throw new AbortedMultiExecException($this, $response->getMessage());
        } else {
            $this->onProtocolError('The server did not return a +QUEUED status response.');
        }

        return $this;
    }
919250
protected function runCommand(ICommand $command, $isolate = true) {
        try {
            if ( ! $command->isGlobal()) {
                $this->commandExecutionLock->lockCommand($command, $this->getAllowParallel());
            }

            if ($isolate) {
                $input = clone $this->input;
                $output = clone $this->output;
            } else {
                $input = $this->input;
                $output = $this->output;
            }

            $input->setCommand($command);

            return $this->commandInvoker->run(
                $command->getHandler(), $input, $output, $this
            );
        } catch (Exception $ex) {
            if ($this->getCatchErrors()) {
                $widget = new ExceptionWidget($this->input, $this->output);
                $widget->render($ex);
            } else {
                throw $ex;
            }
        }
    }
971132
public function handle(CommandInterface $command)
    {
        $class = $command->getParameter('class');
        $object = $command->hasParameter('object') ? $command->getParameter('object') : null;

        // if no object has been given, try loading it using a query object
        if (!$object) {
            $object = $this->queryExecutor->execute($command->getParameter('query_object'));
        }

        // try removing the object if it is valid
        if ($object instanceof $class) {
            try {
                $this->objectManager->remove($object);
                $this->objectManager->flush();
            } catch (ForeignKeyConstraintViolationException $e) {
                return CommandResult::error('constraint_violation');
            }
        }
    }
14276
protected function doSendCommand(Command $command): void
    {
        if (!$this->shouldUseGearman()) {
            $this->locator->getCommandBus()->receiveCommand($command);
            return;
        }

        $envelope = new TransportEnvelope($command, 'php');
        $channel = $this->router->forCommand($command);

        try {
            $client = $this->getClient();
            @$client->doBackground($channel, $envelope->toString(), (string)$command->get('command_id'));
            $this->validateReturnCode($client, $channel);
        } catch (\GearmanException $ge) {
            if (isset(self::$reconnectCodes[$ge->getCode()])) {
                $this->destroyClient();
                $this->locator->getCommandBus()->receiveCommand($command);
                return;
            }

            throw $ge;
        } catch (\Throwable $e) {
            throw $e;
        }
    }