3 namespace Drupal\layout_builder;
5 use Drupal\Core\Database\Connection;
6 use Drupal\Core\Entity\EntityInterface;
9 * Service class to track inline block usage.
13 class InlineBlockUsage {
16 * The database connection.
18 * @var \Drupal\Core\Database\Connection
23 * Creates an InlineBlockUsage object.
25 * @param \Drupal\Core\Database\Connection $database
26 * The database connection.
28 public function __construct(Connection $database) {
29 $this->database = $database;
33 * Adds a usage record.
35 * @param int $block_content_id
36 * The block content id.
37 * @param \Drupal\Core\Entity\EntityInterface $entity
40 public function addUsage($block_content_id, EntityInterface $entity) {
41 $this->database->merge('inline_block_usage')
43 'block_content_id' => $block_content_id,
44 'layout_entity_id' => $entity->id(),
45 'layout_entity_type' => $entity->getEntityTypeId(),
50 * Gets unused inline block IDs.
53 * The maximum number of block content entity IDs to return.
58 public function getUnused($limit = 100) {
59 $query = $this->database->select('inline_block_usage', 't');
60 $query->fields('t', ['block_content_id']);
61 $query->isNull('layout_entity_id');
62 $query->isNull('layout_entity_type');
63 return $query->range(0, $limit)->execute()->fetchCol();
67 * Remove usage record by layout entity.
69 * @param \Drupal\Core\Entity\EntityInterface $entity
72 public function removeByLayoutEntity(EntityInterface $entity) {
73 $query = $this->database->update('inline_block_usage')
75 'layout_entity_type' => NULL,
76 'layout_entity_id' => NULL,
78 $query->condition('layout_entity_type', $entity->getEntityTypeId());
79 $query->condition('layout_entity_id', $entity->id());
84 * Delete the inline blocks' the usage records.
86 * @param int[] $block_content_ids
87 * The block content entity IDs.
89 public function deleteUsage(array $block_content_ids) {
90 if (!empty($block_content_ids)) {
91 $query = $this->database->delete('inline_block_usage')->condition('block_content_id', $block_content_ids, 'IN');
97 * Gets usage record for inline block by ID.
99 * @param int $block_content_id
100 * The block content entity ID.
103 * The usage record with properties layout_entity_id and layout_entity_type.
105 public function getUsage($block_content_id) {
106 $query = $this->database->select('inline_block_usage');
107 $query->condition('block_content_id', $block_content_id);
108 $query->fields('inline_block_usage', ['layout_entity_id', 'layout_entity_type']);
110 return $query->execute()->fetchObject();