@param Application $app
@param Request     $request
@param array       $parameters

@return Response
331529
public function defaultEditAction(Application $app, Request $request, $id)
    {
        return $this->getEditForm($app, $request, $id);
    }
237907
public function write(Request $request, Application $app)
    {
        $username = $request->request->get('username');
        $password = $request->request->get('password');

        $user = $this->userProvider->loadUserByUsername($username);
        if (!$this->passwordEncoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
            throw new BadCredentialsException;
        }

        $this->userManager->loginUser($user);
        // get latest revision of user
        $user = $this->userProvider->loadUserByIdentifier($user->getAggregateId());
        $request->attributes->set('user', $user);

        return [LoginSuccessView::class];
    }
1193795
public static function fromRequest(Application $app, Request $request)
    {
        /** @var Authenticator $authenticator */
        $authenticator = $app->getAuthenticator();
        $isAuthenticated = $authenticator->isAuthenticated();

        $options = new static();

        $options->collectionReferenceRepository = $app['repo.collection-references'];

        $options->disallowBusinessFields();
        $options->setLocale($app['locale']);

        $options->setSearchType($request->get('search_type'));
        $options->setRecordType($request->get('record_type'));
        $options->setSort($request->get('sort'), $request->get('ord', SearchEngineOptions::SORT_MODE_DESC));
        $options->setStemming((Boolean) $request->get('stemme'));

        $min_date = $max_date = null;
        if ($request->get('date_min')) {
            $min_date = \DateTime::createFromFormat('Y/m/d H:i:s', $request->get('date_min') . ' 00:00:00');
        }
        if ($request->get('date_max')) {
            $max_date = \DateTime::createFromFormat('Y/m/d H:i:s', $request->get('date_max') . ' 23:59:59');
        }
        $options->setMinDate($min_date);
        $options->setMaxDate($max_date);

        $status = is_array($request->get('status')) ? $request->get('status') : [];
        $options->setStatus($status);

        /** @var ACLProvider $aclProvider */
        $aclProvider = $app['acl'];
        $acl = $isAuthenticated ? $aclProvider->get($authenticator->getUser()) : null;
        if ($acl) {
            $searchableBaseIds = $acl->getSearchableBasesIds();
            if (is_array($request->get('bases'))) {
                $selected_bases = array_map(function($bid){return (int)$bid;}, $request->get('bases'));
                $searchableBaseIds = array_values(array_intersect($searchableBaseIds, $selected_bases));
                if (empty($searchableBaseIds)) {
                    throw new BadRequestHttpException('No collections match your criteria');
                }
            }
            $options->onBasesIds($searchableBaseIds);
            if ($acl->has_right(\ACL::CANMODIFRECORD)) {
                /** @var int[] $bf */
                $bf = array_filter($searchableBaseIds, function ($baseId) use ($acl) {
                    return $acl->has_right_on_base($baseId, \ACL::CANMODIFRECORD);
                });
                $options->allowBusinessFieldsOn($bf);
            }
        }
        else {
            $options->onBasesIds([]);
        }

        /** @var \databox[] $databoxes */
        $databoxes = [];
        foreach($options->getCollectionsReferencesByDatabox() as $sbid=>$refs) {
            $databoxes[] = $app->findDataboxById($sbid);
        }

        $queryFields = is_array($request->get('fields')) ? $request->get('fields') : [];
        if (empty($queryFields)) {
            // Select all fields (business included)
            foreach ($databoxes as $databox) {
                foreach ($databox->get_meta_structure() as $field) {
                    $queryFields[] = $field->get_name();
                }
            }
        }
        $queryFields = array_unique($queryFields);

        $queryDateFields = array_unique(explode('|', $request->get('date_field')));

        $databoxFields = [];
        $databoxDateFields = [];

        foreach ($databoxes as $databox) {
            $metaStructure = $databox->get_meta_structure();

            foreach ($queryFields as $fieldName) {
                try {
                    if( ($databoxField = $metaStructure->get_element_by_name($fieldName, databox_descriptionStructure::STRICT_COMPARE)) ) {
                        $databoxFields[] = $databoxField;
                    }
                } catch (\Exception $e) {
                    // no-op
                }
            }

            foreach ($queryDateFields as $fieldName) {
                try {
                    if( ($databoxField = $metaStructure->get_element_by_name($fieldName, databox_descriptionStructure::STRICT_COMPARE)) ) {
                        $databoxDateFields[] = $databoxField;
                    }
                } catch (\Exception $e) {
                    // no-op
                }
            }
        }

        $options->setFields($databoxFields);
        $options->setDateFields($databoxDateFields);

        return $options;
    }
103397
public function show(string $app, string $property, array $params = [])
    {
        $path = $this->buildPropertiesPath($app, $property);

        return $this->get($path, $params);
    }
791758
public function recast(Request $request, Application $app, $operation)
    {
        if (!in_array($operation, $this->availableMethods)) {
            return new Response(sprintf(
                'Valid methods for recast are [%s] received "%s".',
                implode(', ', $this->availableMethods),
                $operation
            ), 400);
        }
        $this->log->info("Request to {$operation} resource.");

        $token = null;
        if ($request->headers->has('Authorization')) {
            $token = $request->headers->get('Authorization');
        }

        $fedora_uri = $request->headers->get("Apix-Ldp-Resource");
        $fedora_resource = $request->attributes->get('fedora_resource');
        $body = (string) $fedora_resource->getBody();
        $mimeType = $fedora_resource->getHeader('Content-type');
        if (is_array($mimeType)) {
            $mimeType = reset($mimeType);
        }
        if (preg_match("/^([^;]+);/", $mimeType, $matches)) {
            $mimeType = $matches[1];
        }
        try {
            $format = \EasyRdf_Format::getFormat($mimeType)->getName();
        } catch (\EasyRdf_Exception $e) {
            $this->log->info("Could not parse format {$mimeType}");
            return new Response("Cannot process resource in format ({$mimeType})", 400);
        }

        try {
            $graph = new \EasyRdf_Graph();
            $graph->parse(
                $body,
                $format,
                $fedora_uri
            );
        } catch (\EasyRdf_Exception $e) {
            $this->log->error("Error parsing graph in {$format}");
            return new Response("Error parsing graph", 400);
        }

        $resources = $graph->resources();
        foreach ($resources as $uri => $data) {
            if (strpos($uri, $app['crayfish.drupal_base_url']) === 0) {
                $this->log->debug("Checking resource ", [
                'uri' => $uri,
                ]);
                $reverse_uri = $this->geminiClient->findByUri($uri, $token);
                if (!is_null($reverse_uri)) {
                    if (is_array($reverse_uri)) {
                        $reverse_uri = reset($reverse_uri);
                    }
                    // Don't rewrite the current URI (in-case of sameAs)
                    if ($reverse_uri !== $fedora_uri) {
                        $predicate = $this->findPredicateForObject($graph, $uri);
                        $this->log->debug('Found a reverse URI', [
                            'original_uri' => $uri,
                            'reverse_uri' => $reverse_uri,
                        ]);
                        if (!is_null($predicate)) {
                            $graph->addResource(
                                $fedora_uri,
                                $predicate,
                                $reverse_uri
                            );
                            if (strtolower($operation) == 'replace') {
                                $graph->deleteResource(
                                    $fedora_uri,
                                    $predicate,
                                    $uri
                                );
                            }
                        }
                    }
                }
            }
        }
        if ($request->headers->has('Accept')) {
            $acceptable_content_types = $request->getAcceptableContentTypes();
            $format = null;
            foreach ($acceptable_content_types as $output_type) {
                if ($output_type == "*/*") {
                    $output_type = "text/turtle";
                }
                try {
                    $format = \EasyRdf_Format::getFormat($output_type)->getName();
                    break;
                } catch (\EasyRdf_Exception $e) {
                    // pass
                }
            }
            if (is_null($format)) {
                return new Response('Cannot graph convert to requested format', 500);
            }
        } else {
            $format = 'turtle';
            $output_type = 'text/turtle';
        }

        // Add in user configured prefixes/uris for rdf mapping.
        if (isset($app['crayfish.namespaces'])) {
            // To get the prefixes we nest the associative array inside an array
            $namespaces = $app['crayfish.namespaces'][0];
            if (is_array($namespaces) && count($namespaces) > 0) {
                foreach ($namespaces as $prefix => $uri) {
                    if (\EasyRdf_Namespace::prefixOfUri($uri) == '') {
                        $this->log->debug("Adding $prefix -> $uri");
                        \EasyRdf_Namespace::set($prefix, $uri);
                    }
                }
            }
        }

        $new_body = $graph->serialise($format);

        if ($format == 'jsonld') {
            // TODO: Not have to do this to remove the extraneous resources.
            $temp = array_filter(
                json_decode($new_body, true),
                function ($item) use ($fedora_uri) {
                    return $item['@id'] == $fedora_uri;
                }
            );
            $new_body = json_encode(array_values($temp));
        }
        $headers = [
        'Content-type' => $output_type,
        'Content-length' => strlen($new_body),
        ];

        return new Response($new_body, 200, $headers);
    }
533175
public function getResponse(\BearFramework\App\Request $request)
    {
        $requestPath = (string) $request->path;
        $requestMethod = $request->method;
        foreach ($this->data as $route) {
            foreach ($route[0] as $pattern) {
                $matches = null;
                preg_match('/^(?:(?:((?:[A-Z]+\|){0,}[A-Z]+) )?)(.*+)/', $pattern, $matches);
                $patternMethods = '|' . ($matches[1] === '' ? 'GET' : $matches[1]) . '|';
                if (strpos($patternMethods, '|' . $requestMethod . '|') === false) {
                    continue;
                }
                $patternPath = $matches[2];
                if (preg_match('/^' . str_replace(['/', '?', '*'], ['\/', '[^\/]+?', '.+?'], $patternPath) . '$/u', $requestPath) === 1) {
                    foreach ($route[1] as $callable) {
                        ob_start();
                        try {
                            $response = call_user_func($callable, $request);
                            ob_end_clean();
                        } catch (\Exception $e) {
                            ob_end_clean();
                            throw $e;
                        }
                        if ($response instanceof App\Response) {
                            return $response;
                        }
                    }
                    // continue searching
                }
            }
        }
        if ($request->method === 'HEAD') {
            $getRequest = clone($request);
            $getRequest->method = 'GET';
            $response = $this->getResponse($getRequest);
            if ($response instanceof App\Response) {
                $response->content = '';
                return $response;
            }
        }
        return null;
    }
576316
public function initializeRequest(Application $app, Request $request = null)
    {
        if ($request === null) {
            $request = $app['request_stack']->getCurrentRequest() ?: Request::createFromGlobals();
        }

        // This is where we set the canonical. Note: The protocol (scheme) defaults to 'http',
        // and the path is discarded, as it makes no sense in this context: Bolt always
        // determines the path for a page / record. This is not the canonical's job.
        $canonical = $app['config']->get('general/canonical', $request->server->get('HTTP_HOST'));
        if (strpos($canonical, 'http') !== 0) {
            $canonical = 'http://' . $canonical;
        }

        $canonical = parse_url($canonical);

        if (empty($canonical['host'])) {
            $canonical['host'] = $request->server->get('HTTP_HOST');
        }

        if (empty($canonical['scheme'])) {
            $canonical['scheme'] = 'http';
        }

        if (($request->server->get('HTTPS') == 'on') ||
            ($request->server->get('SERVER_PROTOCOL') == 'https') ||
            ($request->server->get('HTTP_X_FORWARDED_PROTO') == 'https') ||
            ($request->server->get('HTTP_X_FORWARDED_SSL') == 'on')) {
            $canonical['scheme'] = 'https';
        }

        $this->request['canonical'] = sprintf('%s://%s', $canonical['scheme'], $canonical['host']);

        $rootUrl = rtrim($this->urls['root'], '/');
        if ($rootUrl !== $request->getBasePath()) {
            $this->urlPrefix = $request->getBasePath();
        }

        $this->request['protocol'] = $canonical['scheme'];
        $hostname = $request->server->get('HTTP_HOST', 'localhost');
        $this->request['hostname'] = $hostname;
        $current = $request->getBasePath() . $request->getPathInfo();
        $this->setUrl('current', $current);
        $this->setUrl('currenturl', sprintf('%s://%s%s', $canonical['scheme'], $hostname, $current));
        $this->setUrl('hosturl', sprintf('%s://%s', $canonical['scheme'], $hostname));
        $this->setUrl('rooturl', sprintf('%s%s/', $this->request['canonical'], $rootUrl));

        $url = sprintf('%s%s', $this->request['canonical'], $current);
        if (PagerManager::isPagingRequest($request)) {
            $url .= '?' . http_build_query($request->query->all());
        }
        $this->setUrl('canonicalurl', $url);

        $this->requestInitialized = true;
    }
1316840
protected function doRequest($request)
    {
        $path = getcwd();
        if (defined('APP_PATH')) {
            $path = APP_PATH;
        }
        $loader = new ClassLoader();

        $loader->add(null, $path);
        $loader->register();

        // Create application
        Configuration::addPath($path . '/Configuration');
        Template::addPath($path . '/Views');

        $uri = str_replace('http://localhost/', '', $request->getUri());
        preg_match('/^([a-zA-Z0-9\/\-_]+).?([a-zA-Z0-9\-_]*)\??([a-zA-Z0-9\-_\=]*)/i', $uri, $matches);

        if (isset($matches[3]) && $matches[3] != '') {
            $params = parse_url($request->getUri());
            parse_str($params['query'], $_GET);
        }

        if (isset($matches[1]) && $matches[1] != '') {
            $_GET['url'] = $matches[1];
        }

        if (isset($matches[2]) && $matches[2] != '') {
            $_GET['extension'] = $matches[2];
        }

        $app = new Application();

        $zendRequest = $app->getRequest();
        $zendResponse = $app->getResponse();

        $uri = new HttpUri($request->getUri());
        $queryString = $uri->getQuery();
        $method = strtoupper($request->getMethod());

        if ($queryString) {
            parse_str($queryString, $query);
        }

        if ($method == HttpRequest::METHOD_POST) {
            $zendRequest->setPost(new Parameters($request->getParameters()));
        }
        /* elseif ($method == HttpRequest::METHOD_PUT) {
            $zendRequest->setContent($request->getContent());
        }*/

        $zendRequest->setMethod($method);
        $zendRequest->setUri($uri);

        // Application bootstrap
        $app->bootstrap();

        $app->run();


        return new Response(
            $zendResponse->getContent(),
            $zendResponse->getStatusCode(),
            $zendResponse->getHeaders()->toArray()
        );

    }
681160
public function boot(Application $app)
    {
        $app->flush();

        /* @var $routes \Symfony\Component\Routing\RouteCollection */
        $routes = $app['routes'];

        /* @var $route \Silex\Route */
        foreach ($routes->getIterator() as $id => $route) {
            $path = $route->getPath();

            $headers = implode(',', [
                'Authorization',
                'Accept',
                'X-Request-With',
                'Content-Type',
                'X-Session-Token',
                'X-Hmac-Hash',
                'X-Time',
                'X-Url'
            ]);

            /* @var $controller \Silex\Controller */
            $controller = $app->match(
                $path,
                function () use ($headers) {
                    return new Response(
                        null,
                        204,
                        [
                            "Allow" => "GET,POST,PUT,DELETE",
                            "Access-Control-Max-Age" => 84600,
                            "Access-Control-Allow-Origin" => "*",
                            "Access-Control-Allow-Credentials" => "false",
                            "Access-Control-Allow-Methods" => "GET,POST,PUT,DELETE",
                            "Access-Control-Allow-Headers" => $headers
                        ]
                    );
                }
            );

            $controller->method('OPTIONS');

            /* @var $controllerRoute \Silex\Route */
            $controllerRoute = $controller->getRoute();
            $controllerRoute->setCondition($route->getCondition());
            $controllerRoute->setSchemes($route->getSchemes());
            $controllerRoute->setMethods('OPTIONS');
        }
    }
802221
public function register(Application $app)
    {
        /** @var Translator $translator  */
        $translator = $app['translator'];
        $translator->addTranslationFolder(__DIR__ . DIRECTORY_SEPARATOR . 'Messages');

        /** @var ApplicationConfiguration $config */
        $config = $app['config'];

        $partialsCollection = new PartialsCollection($app['markdown']);
        $app['partials'] = $partialsCollection;

        /** @var Partial[] $partials */
        $partials = $config->getPartials();
        if ($partials) {
            foreach ($partials as $partial) {
                if (! $partial->getName()) {
                    throw new Exception\MissingNameForPartialException('The name of the partial to load is missing');
                }

                $content = '';
                if ($partial->getContent()) {
                    $content = $partial->getContent();
                } elseif ($partial->getLink()) {
                    if (! is_readable($partial->getLink())) {
                        $app['monolog']->error(
                            sprintf($translator->translate('PPCPP:EXC-NOPARTIAL'), $partial->getLink())
                        );
                        continue;
                    }

                    $content = file_get_contents($partial->getLink());
                }
                $partialsCollection->set($partial->getName(), $content);
            }
        }
    }
50516
public function deleteApp(Request $request, ApiApplication $application)
    {
        $this->assertJsonRequestFormat($request);

        $this->getApiApplicationManipulator()->delete($application);

        return $this->app->json(['success' => true]);
    }
556307
public function register(Application $app)
    {
        $app['rest_normalizer.version'] = '0.1.0';
        $app['rest_normalizer.builder'] = $app->protect(
            function ($object = null) use ($app) {
                $version = $app['rest_normalizer.version'];
                $request = $app['request'];
                /** @var $request \Symfony\Component\HttpFoundation\Request */

                $builder = ResponseBuilder::create(
                    $version,
                    HttpMethod::valueOf($request->getMethod()),
                    $object
                );

                foreach ($request->request->all() as $key => $value) {
                    $parameter = Parameter::create($key, $value);
                    $builder->addParameter($parameter);
                }

                return $builder;
            }
        );
    }
552962
public GetAppResponse queryApp(GetAppRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getApp(), "The parameter app should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_APP,
                request.getApp());
        return invokeHttpClient(internalRequest, GetAppResponse.class);
    }
559258
public function execute(Request $request, Route $route, $parameters)
    {
        $request->attributes->set('_controller', $this->getControllerCallback());
        $app = Facade::getFacadeApplication();
        $controllerResolver = $app->make(ApplicationAwareControllerResolver::class);
        $callback = $controllerResolver->getController($request);
        $argumentsResolver = $app->make(ArgumentResolver::class);

        $arguments = $argumentsResolver->getArguments($request, $callback);
        $controller = $callback[0];
        $method = $callback[1];

        if (method_exists($controller, 'on_start')) {
            $controller->on_start();
        }

        if (method_exists($controller, 'runAction')) {
            $response = $controller->runAction($method, $arguments);
        } else {
            $response = call_user_func_array([$controller, $method], $arguments);
        }

        if ($response instanceof Response) {
            // note, our RedirectResponse doesn't extend Response, it extends symfony2 response
            return $response;
        }

        if ($response instanceof AbstractView) {
            $content = $response->render();
        } else if (method_exists($controller, 'getViewObject')) {
            $content = null;
            $view = $controller->getViewObject();
            if (is_object($view)) {
                $view->setController($controller);
                if (isset($view) && $view instanceof AbstractView) {
                    $content = $view->render();
                }
            }
        } else {
            $content = $response;
        }

        if (is_object($content)) {
            return $content;
        }

        $response = new Response();
        $response->setContent($content);
        return $response;
    }
231565
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
    {
        $this->currentUri = $this->prepareUrlForRequest($uri);

        $symfonyRequest = SymfonyRequest::create(
            $this->currentUri, $method, $parameters,
            $cookies, $files, $server, $content
        );

        $response = $this->app->prepareResponse(
            $this->app->handle(Request::createFromBase($symfonyRequest))
        );
        $this->response = $this->createTestResponse($response);

        return $this->response;
    }
379364
public static function executeWeb(Request $request, $config = [], $appClass = 'Windwalker\Web\Application')
    {
        $profile = Ioc::getProfile();

        Ioc::setProfile('web');

        if (!class_exists($appClass)) {
            throw new \LogicException($appClass . ' not found, you have to provide an exists Application class name.');
        }

        if (!is_subclass_of($appClass, WebApplication::class)) {
            throw new \LogicException('Application class should be sub class of ' . WebApplication::class);
        }

        /** @var WebApplication $app */
        $app = new $appClass($request);

        $app->getConfig()->load($config);

        $app->set('output.return_body', true);

        $app->server->setOutput(new NoHeaderOutput());

        $response = $app->execute();

        Ioc::setProfile($profile);

        return $response;
    }
932112
protected function render($view, array $parameters = array(), Response $response = null)
    {
        return $this->app->render($view, $parameters, $response);
    }