You are here

public function FrontController::handle in Subrequests 8

Same name and namespace in other branches
  1. 8.2 src/Controller/FrontController.php \Drupal\subrequests\Controller\FrontController::handle()
  2. 3.x src/Controller/FrontController.php \Drupal\subrequests\Controller\FrontController::handle()

Controller handler.

1 string reference to 'FrontController::handle'
subrequests.routing.yml in ./subrequests.routing.yml
subrequests.routing.yml

File

src/Controller/FrontController.php, line 48

Class

FrontController

Namespace

Drupal\subrequests\Controller

Code

public function handle(Request $request) {
  $this->parser
    ->parseRequest($request);
  $responses = [];

  /** @var \Drupal\subrequests\Blueprint\RequestTree $tree */
  $root_tree = $request->attributes
    ->get(RequestTree::SUBREQUEST_TREE);
  $trees = [
    $root_tree,
  ];

  // Handle all the sub-requests.
  while (!$root_tree
    ->isDone()) {

    // Requests in the current level may have references to older responses.
    // This step resolves those.
    array_walk($trees, function (RequestTree $tree) use ($responses) {
      $tree
        ->dereference($responses);
    });

    // Get all the requests in the trees for the previous pass.
    $requests = array_reduce($trees, function (array $carry, RequestTree $tree) {
      return array_merge($carry, $tree
        ->getRequests());
    }, []);

    // Get the next batch of trees for the next level.
    $trees = array_reduce($trees, function (array $carry, RequestTree $tree) {
      return array_merge($carry, $tree
        ->getSubTrees());
    }, []);

    // Handle the requests for the trees at this level and gather the
    // responses.
    $level_responses = array_map(function (Request $request) {
      $response = $this->httpKernel
        ->handle($request, HttpKernelInterface::MASTER_REQUEST);

      // Manually mark the request as done. We cannot use a response
      // subscriber, since it may not fire if the subrequest is cached by
      // PageCache.
      $request->attributes
        ->set(RequestTree::SUBREQUEST_DONE, TRUE);
      $id = $request->headers
        ->get('Content-ID');
      $response->headers
        ->set('Content-ID', $id);
      return $response;
    }, $requests);
    $responses = array_merge($responses, $level_responses);
  }
  return $this->parser
    ->combineResponses($responses);
}