You are here

class JsonRenderer in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/system/tests/modules/common_test/src/Render/MainContent/JsonRenderer.php \Drupal\common_test\Render\MainContent\JsonRenderer

Default main content renderer for JSON requests.

Hierarchy

Expanded class hierarchy of JsonRenderer

1 string reference to 'JsonRenderer'
common_test.services.yml in core/modules/system/tests/modules/common_test/common_test.services.yml
core/modules/system/tests/modules/common_test/common_test.services.yml
1 service uses JsonRenderer
main_content_renderer.json in core/modules/system/tests/modules/common_test/common_test.services.yml
Drupal\common_test\Render\MainContent\JsonRenderer

File

core/modules/system/tests/modules/common_test/src/Render/MainContent/JsonRenderer.php, line 16

Namespace

Drupal\common_test\Render\MainContent
View source
class JsonRenderer implements MainContentRendererInterface {

  /**
   * The title resolver.
   *
   * @var \Drupal\Core\Controller\TitleResolverInterface
   */
  protected $titleResolver;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a new JsonRenderer.
   *
   * @param \Drupal\Core\Controller\TitleResolverInterface $title_resolver
   *   The title resolver.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   */
  public function __construct(TitleResolverInterface $title_resolver, RendererInterface $renderer) {
    $this->titleResolver = $title_resolver;
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $json = [];
    $json['content'] = (string) $this->renderer
      ->renderRoot($main_content);
    if (!empty($main_content['#title'])) {
      $json['title'] = (string) $main_content['#title'];
    }
    else {
      $json['title'] = (string) $this->titleResolver
        ->getTitle($request, $route_match
        ->getRouteObject());
    }
    $response = new CacheableJsonResponse($json, 200);
    $response
      ->addCacheableDependency(CacheableMetadata::createFromRenderArray($main_content));
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
JsonRenderer::$renderer protected property The renderer service.
JsonRenderer::$titleResolver protected property The title resolver.
JsonRenderer::renderResponse public function Renders the main content render array into a response. Overrides MainContentRendererInterface::renderResponse
JsonRenderer::__construct public function Constructs a new JsonRenderer.