Services.php in Services 9.0.x
File
src/Controller/Services.php
View source
<?php
namespace Drupal\services\Controller;
use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
class Services extends ControllerBase {
protected $serializer;
public function __construct(SerializerInterface $serializer) {
$this->serializer = $serializer;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('serializer'));
}
public function processRequest(Request $request, RouteMatchInterface $route_match, $service_endpoint_id, $service_definition_id) {
$service_endpoint = $this
->entityTypeManager()
->getStorage('service_endpoint')
->load($service_endpoint_id);
$service_resource = $service_endpoint
->loadResourceProvider($service_definition_id);
$service_def = $service_resource
->createServicePluginInstance([]);
foreach ($service_def
->getContextDefinitions() as $context_id => $context_definition) {
if ($request->attributes
->has($context_id)) {
$context = new Context($context_definition, $request->attributes
->get($context_id));
$service_def
->setContext($context_id, $context);
}
}
$data = $service_def
->processRequest($request, $route_match, $this->serializer);
$code = $service_def
->getPluginDefinition()['response_code'];
$headers = [];
$messages = $this
->messenger()
->all();
if ($messages) {
foreach ($messages as $type => $type_message) {
$headers["X-Drupal-Services-Messages-{$type}"] = implode('; ', $type_message);
}
}
$format = $request
->getRequestFormat();
$data = $this->serializer
->serialize($data, $format);
$response = new CacheableResponse($data, $code, $headers);
$response->headers
->add([
'Content-Type' => $request
->getMimeType($format),
]);
$response
->addCacheableDependency($service_def);
$response
->setVary('Accept');
$service_def
->processResponse($response);
return $response;
}
public function csrfToken() {
return new Response(\Drupal::csrfToken()
->get('services'), 200, [
'Content-Type' => 'text/plain',
]);
}
}