Executes a command and optionally returns a value

@param object   $command
@param callable $next

@return mixed

@throws CanNotInvokeHandlerException
517716
public function execute($command, callable $next)
    {
        $commandName = $this->commandNameExtractor->extract($command);
        $handler = $this->handlerLocator->getHandlerForCommand($commandName);
        $methodName = $this->methodNameInflector->inflect($command, $handler);

        // is_callable is used here instead of method_exists, as method_exists
        // will fail when given a handler that relies on __call.
        if (!is_callable([$handler, $methodName])) {
            throw CanNotInvokeHandlerException::forCommand(
                $command,
                "Method '{$methodName}' does not exist on handler"
            );
        }

        return $handler->{$methodName}($command);
    }
782678
public function handle($request, Closure $next)
    {
        if (!in_array($method = \Request::getMethod(), Verbs::getDefinedConstants())) {
            throw new MethodNotAllowedHttpException(Verbs::getDefinedConstants(),
                "Invalid or unsupported verb '$method' used in request.");
        }

        //  Allow console requests through
        if (env('DF_IS_VALID_CONSOLE_REQUEST', false)) {
            return $next($request);
        }

        try {
            // if the request provides a JWT and it is bad, throw reason first
            if (Session::getBool('token_expired')) {
                throw new UnauthorizedException(Session::get('token_expired_msg'));
            } elseif (Session::getBool('token_blacklisted')) {
                throw new ForbiddenException(Session::get('token_blacklisted_msg'));
            } elseif (Session::getBool('token_invalid')) {
                throw new UnauthorizedException(Session::get('token_invalid_msg'));
            }

            /** @var Router $router */
            $router = app('router');
            // root of API gives available service listing
            if (empty($service = strtolower($router->input('service')))) {
                return $next($request);
            }

            $component = strtolower($router->input('resource'));
            $requestor = Session::getRequestor();
            $permException = null;
            try {
                Session::checkServicePermission($method, $service, $component, $requestor);

                return $next($request);
            } catch (RestException $e) {

                $permException = $e;
            }

            // No access allowed, figure out the best error response
            $apiKey = Session::getApiKey();
            $token = Session::getSessionToken();
            $roleId = Session::getRoleId();
            $callFromLocalScript = (ServiceRequestorTypes::SCRIPT == $requestor);

            if (!$callFromLocalScript && empty($apiKey) && empty($token)) {
                $msg = 'No session token (JWT) or API Key detected in request. ' .
                    'Please send in X-DreamFactory-Session-Token and/or X-DreamFactory-API-Key request header. ' .
                    'You can also use URL query parameters session_token and/or api_key.';
                throw new BadRequestException($msg);
            } elseif (empty($roleId)) {
                if (empty($apiKey)) {
                    throw new BadRequestException(
                        "No API Key provided. Please provide a valid API Key using X-DreamFactory-API-Key request header or 'api_key' url query parameter."
                    );
                } elseif (empty($token)) {
                    throw new BadRequestException(
                        "No session token (JWT) provided. Please provide a valid JWT using X-DreamFactory-Session-Token request header or 'session_token' url query parameter."
                    );
                } else {
                    throw new ForbiddenException(
                        "Role not found. A role may not be assigned to you or your application."
                    );
                }
            } elseif (!Role::getCachedInfo($roleId, 'is_active')) {
                throw new ForbiddenException("Access Forbidden. The role assigned to you or your application or the default role of your application is not active.");
            } elseif (!Session::isAuthenticated()) {
                throw new UnauthorizedException('Unauthorized. User is not authenticated.');
            } else {
                if ($permException) {
                    // Try to get a detail error message if possible.
                    $permException->setMessage('Access Forbidden. ' . $permException->getMessage());
                    throw $permException;
                }
                $msg = 'Access Forbidden. You do not have enough privileges to access this resource.';
                throw new ForbiddenException($msg);
            }
        } catch (\Exception $e) {
            return ResponseFactory::sendException($e);
        }
    }
698293
public function execute($command, callable $next)
    {
        $class = get_class($command);
        $this->logger->log("Command execution started: {$class}", $this->level, $this->category);
        if ($this->forceFlush) {
            $this->logger->flush($final = false);
        }
        $result = $next($command);
        $this->logger->log("Command execution ended: {$class}", $this->level, $this->category);
        if ($this->forceFlush) {
            $this->logger->flush($final = false);
        }
        return $result;
    }
1275535
public function execute($command, callable $next)
    {
        try {
            return $next($command);
        } catch (ExceptionInterface $exception) {
            throw $exception;
        } catch (ValidationException $exception) {
            $this->exceptionHandler->throwServiceExceptionFromViolationException($exception);
        } catch (RequestException $exception) {
            $this->exceptionHandler->throwServiceExceptionFromRequestException($exception);
        } catch (\Throwable $exception) {
            $this->exceptionHandler->throwServiceException($exception);
        }
    }
1355203
public function invoke($context, callable $next)
    {
        $messageId = $context->getMessageId();
        $physicalMessageContext = $this->incomingContextFactory->createPhysicalMessageContext($context);

        $deduplicationEntry = $this->outboxStorage->get($messageId);
        $pendingTransportOperations = $physicalMessageContext->getPendingTransportOperations();

        if (!$deduplicationEntry) {
            $this->outboxStorage->beginTransaction();

            try {
                $next($physicalMessageContext);

                $outboxOperations = $this->operationsConverter->convertToOutboxOperations($pendingTransportOperations);

                $outboxMessage = new OutboxMessage($messageId, $outboxOperations);
                $this->outboxStorage->store($outboxMessage);
                $this->outboxStorage->commit();
            } catch (\Throwable $t) {
                $this->outboxStorage->rollBack();
                throw $t;
            }
        } else {
            $pendingTransportOperations = $this->operationsConverter->convertToPendingTransportOperations(
                $deduplicationEntry
            );
        }

        $this->dispatchPendingOperations($pendingTransportOperations, $physicalMessageContext);

        $this->outboxStorage->markAsDispatched($messageId);
    }
1231658
public function handle($request, Closure $next)
    {
        $this->authorizer->setRequest($request);

        $this->authorizer->checkAuthCodeRequest();

        return $next($request);
    }
934454
public function execute($command, callable $next)
    {
        if ($this->user->getId() === null) {
            throw new NotAuthenticatedException();
        }

        if (!$this->user->can($this->permission)) {
            throw new InsufficientPermissionsException($this->permission);
        }

        return $next($command);
    }
1086162
public function execute(Command $command)
    {
        if ($this->locked === true) {
            $this->queue[] = $command;
            return null;
        }

        $this->locked = true;

        $response = $this->executeIgnoringLock($command);

        $this->executeQueue();

        $this->locked = false;

        return $response;
    }
169805
public function handle(Request $request, callable $next)
    {
        set_error_handler(
            function ($errorNumber, $errorString) {
                throw new \Exception($errorString, $errorNumber);
            }
        );

        try {
            $response = $next($request);

            if (!$response instanceof Response) {
                return new Response(
                    $this->get500(),
                    Response::HTTP_INTERNAL_SERVER_ERROR
                );
            }

            return $response;

        } catch (\Exception $exception) {
            switch ($exception->getCode()) {
                case Response::HTTP_NOT_FOUND:
                    return new Response(
                        $this->get404(),
                        Response::HTTP_NOT_FOUND
                    );
                default:
                    return new Response(
                        $this->get500(),
                        Response::HTTP_INTERNAL_SERVER_ERROR
                    );
            }
        }
    }
101737
public function handle($request, Closure $next)
    {
        try {
            if ($this->validator->validateRequest($request)) {
                $this->app->singleton(LaravelExceptionHandler::class, function ($app) {
                    return $app[ExceptionHandler::class];
                });

                $request = $this->app->make(RequestContract::class)->createFromIlluminate($request);

                $this->events->dispatch(new RequestWasMatched($request, $this->app));

                return $this->sendRequestThroughRouter($request);
            }
        } catch (Exception $exception) {
            $this->exception->report($exception);

            return $this->exception->handle($exception);
        }

        return $next($request);
    }
550849
public function execute($command, callable $next)
    {
        // dev only
        if ($this->isDebug && $command->logs) {
            VarDumper::dump($command->logs);
        }

        return $next($command);
    }
1156799
public function handle($command)
    {
        $user = new User();
        $user
            ->setEmail($command->getEmail())
            ->setPassword($command->getPassword())
            ->setRoles($this->registeredUserRoles)
            ->setEnabled(true);

        // validate user
        $errors = $this->validator->validate($user);
        if (count($errors) > 0) {
            $exception = new InvalidCommandException("User is invalid");
            $exception->setConstraintViolationList($errors);
            throw $exception;
        }

        // persist user
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        return $user;
    }
507074
public function toCommandHandler($command)
    {
        $commandClass = get_class($command);
        $handler = substr_replace($commandClass, 'CommandHandler', strrpos($commandClass, 'Command'));

        if ( ! class_exists($handler))
        {
            $message = "Command handler [$handler] does not exist.";

            throw new HandlerNotRegisteredException($message);
        }

        return $handler;
    }
1099760
public function dispatchNow($command, $handler = null)
    {
        if ($handler || $handler = $this->getCommandHandler($command)) {
            $callback = function ($command) use ($handler) {
                return $handler->handle($command);
            };
        } else {
            $callback = function ($command) {
                return $this->container->call([$command, 'handle']);
            };
        }

        return $this->pipeline->send($command)->through($this->pipes)->then($callback);
    }
983613
public function execute($command, callable $next)
    {
        $result = $next($command);

        $events = $this->eventStorage->release();
        $this->emitEvents($events);

        return $result;
    }
1075591
public function execute(Command $command)
    {
        $handler = $this->resolver->resolve($command);

        return $handler->handle($command);
    }
1330302
public function handle(AbstractCommand $command)
    {
        $this->commandDispatcher->handle($command);
        // Now that the command is handled, let's found if there is some events to publish
        $events = $this->extractEventsFromCommand($command);
        foreach ($events as $event) {
            // we will only publish event to synchronous listeners
            $this->publish($event);
        }

        return $command;
    }