ResourceResponse example

class NoSerializationClassTestResource extends ResourceBase {

  /** * Responds to a POST request. * * @param array $data * An array with the payload. * * @return \Drupal\rest\ResourceResponse */
  public function post(array $data) {
    return new ResourceResponse($data);
  }

}

  public function get(EntityInterface $entity, Request $request) {
    $response = new ResourceResponse($entity, 200);
    // @todo Either remove the line below or remove this todo in https://www.drupal.org/project/drupal/issues/2973356     $response->addCacheableDependency($request->attributes->get(AccessAwareRouterInterface::ACCESS_RESULT));
    $response->addCacheableDependency($entity);

    if ($entity instanceof FieldableEntityInterface) {
      foreach ($entity as $field_name => $field) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $field */
        $field_access = $field->access('view', NULL, TRUE);
        $response->addCacheableDependency($field_access);

        if (!$field_access->isAllowed()) {
          
$config->getResourcePlugin()->willReturn($resource->reveal());
    $config->getCacheContexts()->willReturn([]);
    $config->getCacheTags()->willReturn([]);
    $config->getCacheMaxAge()->willReturn(12);

    // Response returns NULL this time because response from plugin is not     // a ResourceResponse so it is passed through directly.     $response = $this->requestHandler->handle($route_match$request$config->reveal());
    $this->assertEquals(NULL, $response);

    // Response will return a ResourceResponse this time.     $response = new ResourceResponse([]);
    $resource->get(NULL, $request)
      ->willReturn($response);
    $handler_response = $this->requestHandler->handle($route_match$request$config->reveal());
    $this->assertEquals($response$handler_response);

    // We will call the patch method this time.     $route_match = new RouteMatch('test', (new Route('/rest/test', ['_rest_resource_config' => 'restplugin', 'example_original' => '']['_content_type_format' => 'json']))->setMethods(['PATCH']));
    $request->setMethod('PATCH');
    $response = new ResourceResponse([]);
    $resource->patch(['this is an array']$request)
      ->shouldBeCalledTimes(1)
      
/** * Helper method to create a resource response from arbitrary JSON. * * @param string|null $json * The JSON with which to create a mock response. * * @return \Drupal\rest\ResourceResponse * The mock response object. */
  protected static function createResponse(?string $json = NULL): ResourceResponse {
    $response = new ResourceResponse();
    if ($json) {
      $response->setContent($json);
    }
    return $response;
  }

}

class ResourceResponseSubscriberTest extends UnitTestCase {

  /** * @covers ::onResponse * @dataProvider providerTestSerialization */
  public function testSerialization($data$expected_response = FALSE) {
    $request = new Request();
    $route_match = new RouteMatch('test', new Route('/rest/test', ['_rest_resource_config' => 'restplugin']['_format' => 'json']));

    $handler_response = new ResourceResponse($data);
    $resource_response_subscriber = $this->getFunctioningResourceResponseSubscriber($route_match);
    $event = new ResponseEvent(
      $this->prophesize(HttpKernelInterface::class)->reveal(),
      $request,
      HttpKernelInterface::MAIN_REQUEST,
      $handler_response
    );
    $resource_response_subscriber->onResponse($event);

    // Content is a serialized version of the data we provided.     $this->assertEquals($expected_response !== FALSE ? $expected_response : Json::encode($data)$event->getResponse()->getContent());
  }
$request = $event->getRequest();

    if ($request->getRequestFormat() !== 'api_json') {
      return;
    }
    // Retry-After will be random within a range defined in jsonapi settings.     // The goals are to keep it short and to reduce the thundering herd problem.     $header_settings = $this->config->get('jsonapi.settings')->get('maintenance_header_retry_seconds');
    $retry_after_time = rand($header_settings['min']$header_settings['max']);
    $http_exception = new HttpException(503, $this->maintenanceMode->getSiteMaintenanceMessage());
    $document = new JsonApiDocumentTopLevel(new ErrorCollection([$http_exception])new NullIncludedData()new LinkCollection([]));
    $response = new ResourceResponse($document$http_exception->getStatusCode()[
      'Content-Type' => 'application/vnd.api+json',
      'Retry-After' => $retry_after_time,
    ]);
    // Calling RequestEvent::setResponse() also stops propagation of event.     $event->setResponse($response);
  }

}

  public function get($id = NULL) {
    if ($id) {
      $record = Database::getConnection()->query("SELECT * FROM {watchdog} WHERE [wid] = :wid", [':wid' => $id])
        ->fetchAssoc();
      if (!empty($record)) {
        return new ResourceResponse($record);
      }

      throw new NotFoundHttpException("Log entry with ID '$id' was not found");
    }

    throw new BadRequestHttpException('No log entry ID was provided');
  }

}

  protected function setEventResponse(ExceptionEvent $event$status) {
    /** @var \Symfony\Component\HttpKernel\Exception\HttpException $exception */
    $exception = $event->getThrowable();
    $document = new JsonApiDocumentTopLevel(new ErrorCollection([$exception])new NullIncludedData()new LinkCollection([]));
    if ($event->getRequest()->isMethodCacheable()) {
      $response = new CacheableResourceResponse($document$exception->getStatusCode()$exception->getHeaders());
      $response->addCacheableDependency($exception);
    }
    else {
      $response = new ResourceResponse($document$exception->getStatusCode()$exception->getHeaders());
    }
    $event->setResponse($response);
  }

  /** * Check if the error should be formatted using JSON:API. * * The JSON:API format is supported if the format is explicitly set or the * request is for a known JSON:API route. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $exception_event * The exception event. * * @return bool * TRUE if it needs to be formatted using JSON:API. FALSE otherwise. */
throw new UnprocessableEntityHttpException($message);
    }

    // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $self_link = new Link(new CacheableMetadata(), Url::fromRoute('jsonapi.file--file.individual', ['entity' => $file->uuid()]), 'self');
    /* $self_link = new Link(new CacheableMetadata(), $this->entity->toUrl('jsonapi'), ['self']); */
    $links = new LinkCollection(['self' => $self_link]);

    $relatable_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($file_field_name));
    $file_resource_type = reset($relatable_resource_types);
    $resource_object = ResourceObject::createFromEntity($file_resource_type$file);
    return new ResourceResponse(new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1)new NullIncludedData()$links), 201, []);
  }

  /** * Ensures that the given account is allowed to upload a file. * * @param \Drupal\Core\Session\AccountInterface $account * The account for which access should be checked. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field for which the file is to be uploaded. * @param \Drupal\Core\Entity\FieldableEntityInterface|null $entity * The entity, if one exists, for which the file is to be uploaded. */
      // needs to be invoked manually.       $batch =& batch_get();
      // Mark this batch as non-progressive to bypass the progress bar and       // redirect.       $batch['progressive'] = FALSE;
      batch_process();
    }
    else {
      $entity->delete();
    }

    return new ResourceResponse(NULL, 204);
  }

  /** * Gets the collection of entities. * * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The JSON:API resource type for the request to be served. * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * * @return \Drupal\jsonapi\ResourceResponse * The response. * * @throws \Drupal\Core\Http\Exception\CacheableBadRequestHttpException * Thrown when filtering on a config entity which does not support it. */
Home | Imprint | This part of the site doesn't use cookies.