JsonSubrequestDenormalizer.php in Subrequests 8.2
File
src/Normalizer/JsonSubrequestDenormalizer.php
View source
<?php
namespace Drupal\subrequests\Normalizer;
use Drupal\Component\Serialization\Json;
use Drupal\subrequests\Subrequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class JsonSubrequestDenormalizer implements DenormalizerInterface {
public function denormalize($data, $class, $format = NULL, array $context = []) {
$path = parse_url($data->uri, PHP_URL_PATH);
$query = parse_url($data->uri, PHP_URL_QUERY) ?: [];
if (isset($query) && !is_array($query)) {
$_query = [];
parse_str($query, $_query);
$query = $_query;
}
$master_request = $context['master_request'];
$request = Request::create($path, static::getMethodFromAction($data->action), empty($data->body) ? $query : $data->body, $master_request->cookies ? $master_request->cookies
->all() : [], $master_request->files ? $master_request->files
->all() : [], [], empty($data->body) ? '' : Json::encode($data->body));
$session = $master_request
->getSession();
$request
->setSession($session);
foreach ($data->headers as $name => $value) {
$request->headers
->set($name, $value);
}
$this::fixBasicAuth($request);
$content_id = empty($data->requestId) ? md5(serialize($data)) : $data->requestId;
$request->headers
->set('Content-ID', '<' . $content_id . '>');
return $request;
}
public function supportsDenormalization($data, $type, $format = NULL) {
return $type === Request::class && $data instanceof Subrequest;
}
public static function getMethodFromAction($action) {
switch ($action) {
case 'create':
return Request::METHOD_POST;
case 'update':
return Request::METHOD_PATCH;
case 'replace':
return Request::METHOD_PUT;
case 'delete':
return Request::METHOD_DELETE;
case 'exists':
return Request::METHOD_HEAD;
case 'discover':
return Request::METHOD_OPTIONS;
default:
return Request::METHOD_GET;
}
}
protected static function fixBasicAuth(Request $request) {
if ($request->headers
->has('Authorization')) {
$header = $request->headers
->get('Authorization');
if (strpos($header, 'Basic ') === 0) {
list($user, $pass) = explode(':', base64_decode(substr($header, 6)));
$request->headers
->set('PHP_AUTH_USER', $user);
$request->headers
->set('PHP_AUTH_PW', $pass);
}
}
}
}