3 namespace Drupal\layout_builder\Entity;
5 use Drupal\Core\Entity\ContentEntityStorageInterface;
6 use Drupal\Core\Entity\EntityTypeManagerInterface;
7 use Drupal\Core\TempStore\SharedTempStoreFactory;
10 * Generates a sample entity for use by the Layout Builder.
13 * Layout Builder is currently experimental and should only be leveraged by
14 * experimental modules and development releases of contributed modules.
15 * See https://www.drupal.org/core/experimental for more information.
17 class LayoutBuilderSampleEntityGenerator {
20 * The shared tempstore factory.
22 * @var \Drupal\Core\TempStore\SharedTempStoreFactory
24 protected $tempStoreFactory;
27 * The entity type manager.
29 * @var \Drupal\Core\Entity\EntityTypeManagerInterface
31 protected $entityTypeManager;
34 * LayoutBuilderSampleEntityGenerator constructor.
36 * @param \Drupal\Core\TempStore\SharedTempStoreFactory $temp_store_factory
37 * The tempstore factory.
38 * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
39 * The entity type manager.
41 public function __construct(SharedTempStoreFactory $temp_store_factory, EntityTypeManagerInterface $entity_type_manager) {
42 $this->tempStoreFactory = $temp_store_factory;
43 $this->entityTypeManager = $entity_type_manager;
47 * Gets a sample entity for a given entity type and bundle.
49 * @param string $entity_type_id
51 * @param string $bundle_id
54 * @return \Drupal\Core\Entity\EntityInterface
57 public function get($entity_type_id, $bundle_id) {
58 $tempstore = $this->tempStoreFactory->get('layout_builder.sample_entity');
59 if ($entity = $tempstore->get("$entity_type_id.$bundle_id")) {
63 $entity_storage = $this->entityTypeManager->getStorage($entity_type_id);
64 if (!$entity_storage instanceof ContentEntityStorageInterface) {
65 throw new \InvalidArgumentException(sprintf('The "%s" entity storage is not supported', $entity_type_id));
68 $entity = $entity_storage->createWithSampleValues($bundle_id);
69 // Mark the sample entity as being a preview.
70 $entity->in_preview = TRUE;
71 $tempstore->set("$entity_type_id.$bundle_id", $entity);
76 * Deletes a sample entity for a given entity type and bundle.
78 * @param string $entity_type_id
80 * @param string $bundle_id
85 public function delete($entity_type_id, $bundle_id) {
86 $tempstore = $this->tempStoreFactory->get('layout_builder.sample_entity');
87 $tempstore->delete("$entity_type_id.$bundle_id");