You are here

public function ReusableBlocksController::load in Gutenberg 8

Same name and namespace in other branches
  1. 8.2 src/Controller/ReusableBlocksController.php \Drupal\gutenberg\Controller\ReusableBlocksController::load()

Returns JSON representing the loaded blocks.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request.

string $block_id: The reusable block id.

Return value

\Symfony\Component\HttpFoundation\JsonResponse The JSON response.

1 string reference to 'ReusableBlocksController::load'
gutenberg.routing.yml in ./gutenberg.routing.yml
gutenberg.routing.yml

File

src/Controller/ReusableBlocksController.php, line 28

Class

ReusableBlocksController
Returns responses for our blocks routes.

Namespace

Drupal\gutenberg\Controller

Code

public function load(Request $request, $block_id = NULL) {
  $headers = [
    'Allow' => 'GET, POST, PUT, PATCH, DELETE',
    'Access-Control-Allow-Methods' => 'OPTIONS, GET, POST, PUT, PATCH, DELETE',
    'Access-Control-Allow-Credentials' => 'true',
    'Access-Control-Allow-Headers' => 'Authorization, Content-Type',
  ];
  if ($block_id && $block_id > 0) {
    $block = BlockContent::load($block_id);
    return new JsonResponse([
      'id' => (int) $block
        ->id(),
      'title' => [
        'raw' => $block->info->value,
      ],
      'content' => [
        'protected' => FALSE,
        'raw' => $block->body->value,
      ],
      'type' => 'wp_block',
      'status' => 'publish',
      'slug' => 'reusable_block_' . $block
        ->id(),
      // Kind of a hack but accepted by Gutenberg ;)
      'headers' => $headers,
    ], 200, $headers);
  }
  $ids = \Drupal::entityQuery('block_content')
    ->condition('type', 'reusable_block')
    ->execute();
  $blocks = BlockContent::loadMultiple($ids);
  $result = [];
  foreach ($blocks as $key => $block) {
    $result[] = [
      'id' => (int) $block
        ->id(),
      'title' => [
        'raw' => $block->info->value,
      ],
      'content' => [
        'protected' => FALSE,
        'raw' => $block->body->value,
      ],
      'type' => 'wp_block',
      'status' => 'publish',
      'slug' => 'reusable_block_' . $block
        ->id(),
    ];
  }
  return new JsonResponse($result, 200, $headers);
}