You are here

public function JsonSubrequestDenormalizer::denormalize in Subrequests 8

Same name and namespace in other branches
  1. 8.2 src/Normalizer/JsonSubrequestDenormalizer.php \Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer::denormalize()
  2. 3.x src/Normalizer/JsonSubrequestDenormalizer.php \Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer::denormalize()

Denormalizes data back into an object of the given class.

Parameters

mixed $data data to restore:

string $class the expected class to instantiate:

string $format format the given data was extracted from:

array $context options available to the denormalizer:

Return value

object

File

src/Normalizer/JsonSubrequestDenormalizer.php, line 25

Class

JsonSubrequestDenormalizer

Namespace

Drupal\subrequests\Normalizer

Code

public function denormalize($data, $class, $format = NULL, array $context = []) {
  if (!Parser::isValidSubrequest($data)) {
    throw new \RuntimeException('The provided blueprint contains an invalid subrequest.');
  }
  $data['path'] = parse_url($data['uri'], PHP_URL_PATH);
  $data['query'] = parse_url($data['uri'], PHP_URL_QUERY) ?: [];
  if (isset($data['query']) && !is_array($data['query'])) {
    $query = [];
    parse_str($data['query'], $query);
    $data['query'] = $query;
  }
  $data = NestedArray::mergeDeep([
    'body' => '',
    'headers' => [],
  ], $data, parse_url($data['path']));

  /** @var \Symfony\Component\HttpFoundation\Request $master_request */
  $master_request = $context['master_request'];
  $request = Request::create($data['path'], static::getMethodFromAction($data['action']), empty($data['body']) ? $data['query'] : Json::decode($data['body']), $master_request->cookies ? (array) $master_request->cookies
    ->getIterator() : [], $master_request->files ? (array) $master_request->files
    ->getIterator() : [], [], empty($data['body']) ? '' : $data['body']);

  // Maintain the same session as in the master request.
  $request
    ->setSession($master_request
    ->getSession());

  // Replace the headers by the ones in the subrequest.
  foreach ($data['headers'] as $name => $value) {
    $request->headers
      ->set($name, $value);
  }
  $this::fixBasicAuth($request);

  // Add the content ID to the sub-request.
  $content_id = empty($data['requestId']) ? md5(serialize($data)) : $data['requestId'];
  $request->headers
    ->set('Content-ID', '<' . $content_id . '>');
  $request->attributes
    ->set(RequestTree::SUBREQUEST_ID, $content_id);

  // If there is a parent, then add the ID to construct the tree.
  if (!empty($data['waitFor'])) {
    $request->attributes
      ->set(RequestTree::SUBREQUEST_PARENT_ID, $data['waitFor']);
  }
  return $request;
}