jfu-1.0.x-dev/src/Plugin/rest/resource/BlockContentIdResource.php
src/Plugin/rest/resource/BlockContentIdResource.php
<?php
namespace Drupal\jfu\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Cache\CacheableMetadata;
/**
* Provides a Block Get Block Content Id resource
*
* @RestResource (
* id = "block_content_id_resource",
* label = @Translation("Block Content ID Resource"),
* uri_paths = {
* "canonical" = "/jfu_rest_api/block_content_id/{string}"
* }
* )
**/
class BlockContentIdResource extends ResourceBase {
/**
* Responds to entity GET requests.
* @return \Drupal\rest\ResourceResponse
*/
public function get($string) {
$data = [];
if (!empty($string)) {
$plugin_id = base64_decode($string);
if (!empty($plugin_id)) {
$cv_array = explode(':', $plugin_id);
if (isset($cv_array[1]) && !empty($cv_array[1])) {
$entity_type_manager = \Drupal::service('entity_type.manager');
$block_content = $entity_type_manager->getStorage('block_content')->loadByProperties([
'uuid' => $cv_array[1],
]);
if (!empty($block_content)) {
$block_content = reset($block_content);
$data['bcid'] = $block_content->id();
$data['bc_link'] = $block_content->toUrl()->toString(TRUE)->getGeneratedUrl();
}
}
}
}
//Add cache tags.
$cache_metadata = new CacheableMetadata();
$cache_metadata->addCacheTags(['block_content_list']);
//Attach the cache metadata to the response.
$response = new ResourceResponse($data);
$response->addCacheableDependency($cache_metadata);
return $response;
}
}
