public function JsonBlueprintDenormalizer::denormalize in Subrequests 8
Same name and namespace in other branches
- 8.2 src/Normalizer/JsonBlueprintDenormalizer.php \Drupal\subrequests\Normalizer\JsonBlueprintDenormalizer::denormalize()
- 3.x src/Normalizer/JsonBlueprintDenormalizer.php \Drupal\subrequests\Normalizer\JsonBlueprintDenormalizer::denormalize()
File
- src/
Normalizer/ JsonBlueprintDenormalizer.php, line 33
Class
Namespace
Drupal\subrequests\NormalizerCode
public function denormalize($data, $class, $format = NULL, array $context = []) {
// The top level is an array of normalized requests.
$requests = array_map(function ($item) use ($format, $context) {
return $this->serializer
->denormalize($item, Request::class, $format, $context);
}, $data);
// We want to create one tree per parent, but for that we need to identify
// the parents first.
$requests_per_parent = array_reduce($requests, function (array $carry, Request $request) {
$parent_id = $request->attributes
->get(RequestTree::SUBREQUEST_PARENT_ID, RequestTree::ROOT_TREE_ID);
if (empty($carry[$parent_id])) {
$carry[$parent_id] = [];
}
$carry[$parent_id][] = $request;
return $carry;
}, []);
// Now get all the requests for the root parent to create the root tree.
$root_tree = new RequestTree($requests_per_parent[RequestTree::ROOT_TREE_ID]);
unset($requests_per_parent[RequestTree::ROOT_TREE_ID]);
// Iterate through all the parents to find them in the tree. The attach the
// sub-tree to the root.
// TODO: If a tree hangs from a parent that is not attached to the root, then this process may fail.
foreach ($requests_per_parent as $parent_id => $children_requests) {
$parent_requests = array_filter($requests, function (Request $request) use ($parent_id) {
return $request->attributes
->get(RequestTree::SUBREQUEST_ID) == $parent_id;
});
$parent_request = reset($parent_requests);
$parent_request->attributes
->set(RequestTree::SUBREQUEST_TREE, new RequestTree($children_requests, $parent_id));
}
return $root_tree;
}