Create a new instance of activeRecord and add it to Request attributes

@param EntityFactoryConfig    $config
@param ServerRequestInterface $request
@param ResponseInterface      $response
@param callable               $next

@return ResponseInterface
511878
public function create(
        EntityFactoryConfig $config,
        ServerRequestInterface $request,
        ResponseInterface $response,
        callable $next
    ): ResponseInterface {
        $entityRequest = $config->createEntityRequest($request, $this->container);

        # make a new empty record
        $obj = $entityRequest->instantiateActiveRecord();

        # Execute beforeCreate hook, which can alter record
        $entityRequest->beforeCreate($obj, $request);

        # Then, alter object with allowed properties
        if ($config->isHydrateEntityFromRequest()) {
            $requestParams = $request->getQueryParams();
            $postParams    = $request->getParsedBody();
            if ($postParams) {
                $requestParams = array_merge($requestParams, (array)$postParams);
            }

            /** @noinspection PhpUndefinedMethodInspection */
            $obj->fromArray($entityRequest->getAllowedDataFromRequest($requestParams, $request->getMethod()));
        }

        # Execute afterCreate hook, which can alter record
        $entityRequest->afterCreate($obj, $request);

        $request = $request->withAttribute($config->getParameterToInjectInto(), $obj);
        /** @var Response $response */
        return $next($request, $response);
    }
994582
public function next(Request $request)
    {
        $response = $this->middleware->process($request, $this->nextDelegate);

        // Negotiate PSR7 responses
        if ($response instanceof ResponseInterface) {
            return $this->foundationFactory->createResponse($response);
        }

        return $response;
    }
1129004
public function handleRequest(RequestInterface $request, callable $next, callable $first)
    {
        return $next($request)->then(function (ResponseInterface $response) {
            $status = $response->getStatusCode();

            if ($status >= 400 && $status < 600) {
                self::handleError($status, self::getMessage($response) ?: $response->getReasonPhrase());
            }

            return $response;
        });
    }
980146
public function handle(Request $request, \Closure $next)
    {
        if ($this->shouldLogOperation($request)) {
            $log = [
                'user_id' => Merchant::user()->id,
                'path'    => $request->path(),
                'method'  => $request->method(),
                'ip'      => $request->getClientIp(),
                'input'   => json_encode($request->input()),
            ];

            OperationLogModel::create($log);
        }

        return $next($request);
    }
283876
protected function buildDataJoinsMany(ConfigInterface $config, array $joinKeys)
    {
        //~ Search for keys
        $keys = '';
        $joinKeys = array_flip($joinKeys);
        foreach ($this->columns as $column) {
            if (!isset($joinKeys[$column->getName()])) {
                continue;
            }

            $keys .= '
            $mapper->addWhere(\'' . $column->getName() . '\', $this->' . $column->getMethodNameGet() .'());';
        }

        if (empty($keys)) {
            throw new \LogicException('Empty keys list for join all method !');
        }

        $propertyCacheName = 'joinManyCache' . $config->getClassname();
        $this->vars['properties'] .= '

    /**
     * @var ' . $config->getClassname() . '[] $' . $propertyCacheName . '
     */
     protected $' . $propertyCacheName . ' = null;';

        //~ Generate method
        return '
    /**
     * Get list of ' . $config->getClassname() . ' data objects.
     *
     * @param  bool $isForceReload
     * @return ' . $config->getClassname() . '[]
     */
    public function getAll' . $config->getClassname() . '($isForceReload = false)
    {
        if ($isForceReload || null === $this->' . $propertyCacheName . ') {
            $mapper = new ' . $config->getClassname() . 'Mapper($this->dependencyContainer->getDatabase(\'' . $config->getDbConfig() . '\'));' .
            $keys . '

            $this->' . $propertyCacheName . ' = $mapper->select();
        }
        
        return $this->' . $propertyCacheName . ';
    }
';
    }
199898
public function getPaginator(PaginatorConfig $paginatorConfig, Request $request)
    {
        $queryBuilder = $paginatorConfig->getQueryBuilder();
        // insert default values in paginator config
        $paginatorConfig = clone($paginatorConfig);
        if (is_null($paginatorConfig->getItemCountInPage())) {
            $paginatorConfig->setItemCountInPage($this->paginatorParameterList["item_count_in_page"]);
        }
        if (is_null($paginatorConfig->getVisiblePageCountInPaginator())) {
            $paginatorConfig->setVisiblePageCountInPaginator($this->paginatorParameterList["visible_page_count_in_paginator"]);
        }

        // create paginator object
        $paginator = new Paginator();
        $paginator->setPaginatorConfig($paginatorConfig);
        $paginator->setUrlTool(new UrlTool());
        $paginator->setRequestUri($request->getRequestUri());

        // get currentPage
        $paginator->setCurrentPage($request->query->get($paginatorConfig->getRequestQueryName("currentPage"), 1));

        // calculate total object count
        $countQueryBuilder = clone($queryBuilder);
        $countQueryBuilder->select("count(DISTINCT ".$paginatorConfig->getCountFieldName().")");
        $countQueryBuilder->setMaxResults(null);
        $countQueryBuilder->setFirstResult(null);
        $countQueryBuilder->resetDQLPart('groupBy');
        $countQueryBuilder->resetDQLPart('orderBy');

        // event to change paginator query builder
        $event = new DataGridEvent();
        $event->set("paginator", $paginator);
        $event->set("paginatorQueryBuilder", $countQueryBuilder);
        $event->set("request", $request);
        $this->dispatcher->dispatch(KitpagesDataGridEvents::ON_GET_PAGINATOR_QUERY, $event);

        if (!$event->isDefaultPrevented()) {
            $query = $countQueryBuilder->getQuery();
            $event->set("query", $query);
        }
        $this->dispatcher->dispatch(KitpagesDataGridEvents::AFTER_GET_PAGINATOR_QUERY, $event);

        // hack : recover query from the event so the developper can build a new query
        // from the paginatorQueryBuilder in the listener and reinject it in the event.
        $query = $event->get("query");

        try {
            $totalCount = $query->getSingleScalarResult();
            $paginator->setTotalItemCount($totalCount);
        } catch (\Doctrine\ORM\NoResultException $e) {
            $paginator->setTotalItemCount(0);
        }

        // calculate total page count
        if ($paginator->getTotalItemCount() == 0) {
            $paginator->setTotalPageCount(0);
        } else {
            $paginator->setTotalPageCount(
                (int) ((($paginator->getTotalItemCount() - 1) / $paginatorConfig->getItemCountInPage()) + 1)
            );
        }

        // change current page if needed
        if ($paginator->getCurrentPage() > $paginator->getTotalPageCount()) {
            $paginator->setCurrentPage(1);
        }

        // calculate nbPageLeft and nbPageRight
        $nbPageLeft = (int) ($paginatorConfig->getVisiblePageCountInPaginator() / 2);
        $nbPageRight = $paginatorConfig->getVisiblePageCountInPaginator() - 1 - $nbPageLeft ;

        // calculate lastPage to display
        $maxPage = min($paginator->getTotalPageCount(), $paginator->getCurrentPage() + $nbPageRight);
        // adapt minPage and maxPage
        $minPage = max(1, $maxPage-($paginatorConfig->getVisiblePageCountInPaginator() - 1));
        $maxPage = min($paginator->getTotalPageCount(), $minPage + ($paginatorConfig->getVisiblePageCountInPaginator() - 1));

        $paginator->setMinPage($minPage);
        $paginator->setMaxPage($maxPage);

        // calculate previousButton
        if ($paginator->getCurrentPage() == 1) {
            $paginator->setPreviousButtonPage(null);
        } else {
            $paginator->setPreviousButtonPage( $paginator->getCurrentPage() - 1 );
        }
        // calculate nextButton
        if ($paginator->getCurrentPage() == $paginator->getTotalPageCount()) {
            $paginator->setNextButtonPage(null);
        } else {
            $paginator->setNextButtonPage( $paginator->getCurrentPage() + 1);
        }

        return $paginator;
    }
489361
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->nextHandler = (isset($this->nextHandler)) ? next($this->handlers) : current($this->handlers);

        // nextHandler is a stack
        if ($this->nextHandler instanceof \Peak\Blueprint\Http\Stack) {
            return $this->returnResponse($this->handleStack($this->nextHandler, $request));
        }

        // no more handlers, look for parent
        if ($this->nextHandler === false && isset($this->parentStack)) {
            return $this->returnResponse($this->parentStack->process($request, $this->parentStack));
        } elseif ($this->nextHandler === false) {
            throw new StackEndedWithoutResponseException($this);
        }

        // resolve nextHandler if not already a object
        $handlerInstance = $this->nextHandler;
        if (is_callable($handlerInstance) || !is_object($handlerInstance)) {
            $handlerInstance = $this->handlerResolver->resolve($this->nextHandler);
        }

        // how to call the handler (MiddlewareInterface or RequestHandlerInterface)
        if ($handlerInstance instanceof MiddlewareInterface) {
            return $this->returnResponse($handlerInstance->process($request, $this));
        } elseif($handlerInstance instanceof RequestHandlerInterface) {
            return $this->returnResponse($handlerInstance->handle($request));
        }

        // at this point, the handler is not good
        throw new InvalidHandlerException($handlerInstance);
    }
341479
public function handle( $request, Closure $next )
	{
		$response = $next( $request );

		foreach ( $this->cookies->getQueuedCookies() as $cookie )
			$response->headers->setCookie( $cookie );

		return $response;
	}
142728
public static function handle(
        ServerRequestInterface $request,
        Closure $next,
        ContainerInterface $container
    ): ResponseInterface {
        $header = $request->getHeader('Authorization');
        // if value has Bearer token and it is a valid json with 2 required fields and they are strings
        if (empty($header) === false &&
            substr($value = $header[0], 0, 7) === 'Bearer ' &&
            is_string($tokenValue = substr($value, 7)) === true &&
            empty($tokenValue) === false
        ) {
            assert($container->has(PassportAccountManagerInterface::class));

            /** @var PassportAccountManagerInterface $accountManager */
            $accountManager = $container->get(PassportAccountManagerInterface::class);
            try {
                $accountManager->setAccountWithTokenValue($tokenValue);
            } catch (AuthenticationException $exception) {
                if (($logger = static::getLoggerIfEnabled($container)) !== null) {
                    $logger->info(
                        'Passport authentication failed for a given Bearer token value.',
                        ['token' => $tokenValue]
                    );
                }

                return static::createAuthenticationFailedResponse($container);
            }
        } else {
            if (($logger = static::getLoggerIfEnabled($container)) !== null) {
                $logger->debug(
                    'No Bearer token for Passport authentication. The request is not authenticated.'
                );
            }
        }

        // call next middleware handler
        return $next($request);
    }
31371
public function handle($request, Closure $next) {

        if ($request->isMethod('OPTIONS')) {
            $response = new Response("", 200);
        }
        else {
            $response = $next($request);
        }

        $this->setCorsHeaders($request, $response);

        return $response;
    }
1296736
public function handle($request, Closure $next)
    {
        try {
            $response = $next($request);

            // Was an exception thrown? If so and available catch in our middleware
            if (isset($response->exception) && $response->exception) {
                throw $response->exception;
            }

            return $response;
        } catch (OAuthException $e) {
            $message = env('API_DEBUG') ? $e->getMessage() : null;
            throw new HttpException($e->httpStatusCode, $message, $e, $e->getHttpHeaders());
        } catch (HttpResponseException $e) {
            $message = env('API_DEBUG') ? $e->getMessage() : null;
            throw new HttpException($e->getResponse()->getStatusCode(), $message, $e);
        } catch (AuthenticationException $e) {
            throw new UnauthorizedHttpException(null, $e->getMessage(), $e);
        } catch (ValidatorException $e) {
            $messageBag = $e->getMessageBag();
            throw new ResourceException($messageBag->first(), $messageBag->all());
        } catch (ModelNotFoundException $e) {
            throw new NotFoundHttpException('No results found.');
        }
    }
1050465
public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        $headers = (new SecureHeaders(config('secure-headers', [])))->headers();

        foreach ($headers as $key => $value) {
            $response->headers->set($key, $value, true);
        }

        return $response;
    }
461759
public function handle(Request $request, callable $next)
    {
        $response = $next($request);
        if ( is_string($response) ) {
            return new Response($response);
        }

        return $response;
    }
265469
public function checkFieldKey(ServerRequest $request, Response $response): Response
    {
        $queryParams = $request->getQueryParams();
        $fieldKey = $queryParams['key'];
        $table = 'tt_content';
        if (isset($queryParams['table'])) {
            $table = $queryParams['table'];
        }

        $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
        $storageRepository = $objectManager->get(StorageRepository::class);

        // check if fieldKey is available for this table
        $isAvailable = true;
        if ($storageRepository->loadField($table, $fieldKey)) {
            $isAvailable = false;
        }

        return new JsonResponse(['isAvailable' => $isAvailable]);
    }
611914
public function handle($request, Closure $next)
    {
        $paginationKey = config('pagination.key');

        $request->offsetSet($paginationKey, $request->paginationCount());

        return $next($request);
    }
1196300
protected function doIndexAction(AbstractAdminListConfigurator $configurator, Request $request)
    {
        $em = $this->getEntityManager();
        /* @var AdminList $adminList */
        $adminList = $this->container->get('kunstmaan_adminlist.factory')->createList($configurator, $em);
        $adminList->bindRequest($request);

        $this->buildSortableFieldActions($configurator);

        return new Response(
            $this->renderView(
                $configurator->getListTemplate(),
                array('adminlist' => $adminList, 'adminlistconfigurator' => $configurator, 'addparams' => array())
            )
        );
    }
267794
function(next) {
            if (options.noDb || core.noDb) return next();
            db.initConfig(options, next);
        }