LibraryItem.php 10.7 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\paragraphs_library\Entity;

use Drupal\Component\Utility\Unicode;
6
use Drupal\Core\Entity\EditorialContentEntityBase;
7 8 9 10 11 12 13 14 15 16 17 18 19
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\paragraphs\ParagraphInterface;
use Drupal\paragraphs_library\LibraryItemInterface;
use Drupal\user\UserInterface;

/**
 * Defines the LibraryItem entity.
 *
 * @ContentEntityType(
 *   id = "paragraphs_library_item",
 *   label = @Translation("Paragraphs library item"),
20 21 22 23 24 25 26
 *   label_collection = @Translation("Paragraphs library items"),
 *   label_singular = @Translation("Paragraphs library item"),
 *   label_plural = @Translation("Paragraphs library items"),
 *   label_count = @PluralTranslation(
 *     singular = "@count Paragraphs library item",
 *     plural = "@count Paragraphs library items",
 *   ),
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\Core\Entity\EntityListBuilder",
 *     "access" = "Drupal\paragraphs_library\LibraryItemAccessControlHandler",
 *     "views_data" = "Drupal\paragraphs_library\LibraryItemViewsData",
 *     "form" = {
 *       "default" = "Drupal\paragraphs_library\Form\LibraryItemForm",
 *       "add" = "Drupal\paragraphs_library\Form\LibraryItemForm",
 *       "edit" = "Drupal\paragraphs_library\Form\LibraryItemForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\paragraphs_library\Routing\LibraryItemRouteProvider",
 *     },
 *   },
 *   base_table = "paragraphs_library_item",
 *   data_table = "paragraphs_library_item_field_data",
 *   revision_table = "paragraphs_library_item_revision",
 *   revision_data_table = "paragraphs_library_item_revision_field_data",
 *   show_revision_ui = TRUE,
 *   translatable = TRUE,
 *   admin_permission = "administer paragraphs library",
 *   render_cache = FALSE,
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "revision" = "revision_id",
 *     "uuid" = "uuid",
55 56
 *     "langcode" = "langcode",
 *     "published" = "status",
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
 *   },
 *   revision_metadata_keys = {
 *     "revision_created" = "revision_created",
 *     "revision_user" = "revision_uid",
 *     "revision_log_message" = "revision_log"
 *   },
 *   links = {
 *     "add-form" = "/admin/content/paragraphs/add/default",
 *     "edit-form" = "/admin/content/paragraphs/{paragraphs_library_item}/edit",
 *     "delete-form" = "/admin/content/paragraphs/{paragraphs_library_item}/delete",
 *     "collection" = "/admin/content/paragraphs",
 *     "canonical" = "/admin/content/paragraphs/{paragraphs_library_item}",
 *     "revision" = "/admin/content/paragraphs/{paragraphs_library_item}/revisions/{paragraphs_library_item_revision}/view",
 *     "revision-revert" = "/admin/content/paragraphs/{paragraphs_library_item}/revisions/{paragraphs_library_item_revision}/revert",
 *     "revision-delete" = "/admin/content/paragraphs/{paragraphs_library_item}/revisions/{paragraphs_library_item_revision}/delete"
 *   },
 *   field_ui_base_route = "paragraphs_library_item.settings",
 * )
 */
76
class LibraryItem extends EditorialContentEntityBase implements LibraryItemInterface {
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Label'))
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE)
      ->setSettings([
        'max_length' => 255,
      ])
      ->setDisplayOptions('view', [
        'type' => 'string',
        'weight' => 0,
        'label' => 'hidden',
      ])
      ->setDisplayOptions('form', [
96
        'type' => 'string_textfield',
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        'weight' => -5,
      ])
      ->setRequired(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['paragraphs'] = BaseFieldDefinition::create('entity_reference_revisions')
      ->setLabel(t('Paragraphs'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'paragraph')
      ->setSetting('handler', 'default')
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'entity_reference_revisions_entity_view',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'paragraphs',
        'weight' => 0,
      ])
      ->setRequired(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setDescription(t('The time that the library item was created.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'region' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the library item was last edited.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of the library item author.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setDefaultValueCallback('Drupal\paragraphs_library\Entity\LibraryItem::getCurrentUserId')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'region' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);

152 153 154 155 156 157 158 159 160 161
    $fields['status']
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 3,
      ])
      ->setDisplayConfigurable('form', TRUE);

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    return $fields;
  }

  /**
   * Default value callback for 'uid' base field definition.
   *
   * @see ::baseFieldDefinitions()
   *
   * @return array
   *   An array of default values.
   */
  public static function getCurrentUserId() {
    return array(\Drupal::currentUser()->id());
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    // If no revision author has been set explicitly, make the entity owner the
    // revision author.
    if (!$this->getRevisionUser()) {
      $this->setRevisionUserId($this->getOwnerId());
    }
    parent::preSave($storage);
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('uid')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('uid')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('uid', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('uid', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage, $record);

    if (!$this->isNewRevision() && isset($this->original) && (!isset($record->revision_log) || $record->revision_log === '')) {
      $record->revision_log = $this->original->revision_log->value;
    }

    // @todo Remove when https://www.drupal.org/project/drupal/issues/2869056 is
    // fixed.
    $new_revision = $this->isNewRevision();
    if (!$new_revision && isset($this->original) && (!isset($record->revision_log) || $record->revision_log === '')) {
      // If we are updating an existing library item without adding a new
      // revision, we need to make sure $entity->revision_log is reset whenever
      // it is empty. Therefore, this code allows us to avoid clobbering an
      // existing log entry with an empty one.
      $record->revision_log = $this->original->getRevisionLogMessage();
    }

    if ($new_revision && (!isset($record->revision_created) || empty($record->revision_created))) {
      $record->revision_created = \Drupal::time()->getRequestTime();
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function createFromParagraph(ParagraphInterface $paragraph) {
    if (!$paragraph->getParagraphType()->getThirdPartySetting('paragraphs_library', 'allow_library_conversion', FALSE)) {
      throw new \Exception(sprintf('%s cannot be converted to library item per configuration', $paragraph->bundle()));
    }

    // Ensure that we work with the default language as the active one.
    $paragraph = $paragraph->getUntranslated();

    // Make a copy of the paragraph. Use the Replicate module, if it is enabled.
    if (\Drupal::hasService('replicate.replicator')) {
      $duplicate_paragraph = \Drupal::getContainer()->get('replicate.replicator')->replicateEntity($paragraph);
    }
    else {
      $duplicate_paragraph = $paragraph->createDuplicate();
    }
    $duplicate_paragraph->save();

    $library_item = static::create([
      'paragraphs' => $duplicate_paragraph,
267
      'langcode' => $paragraph->language()->getId(),
268 269
    ]);

270 271 272 273 274 275 276
    // Build the label in each available translation and ensure the translations
    // exist.
    foreach ($duplicate_paragraph->getTranslationLanguages() as $langcode => $language) {
      if (!$library_item->hasTranslation($langcode)) {
        $library_item->addTranslation($langcode, $library_item->toArray());
      }
      $library_item->getTranslation($langcode)->set('label', static::buildLabel($duplicate_paragraph->getTranslation($langcode)));
277 278 279 280 281 282 283 284 285 286 287 288 289 290
    }

    return $library_item;
  }

  /**
   * Builds a label for the library item.
   *
   * @param \Drupal\paragraphs\ParagraphInterface $paragraph
   *   The paragraph for which the label should be generated.
   *
   * @return string
   */
  protected static function buildLabel(ParagraphInterface $paragraph) {
291 292
    $summary = $paragraph->getSummaryItems(['show_behavior_summary' => FALSE]);
    $summary = Unicode::truncate(implode(', ', $summary['content']), 50);
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    return $paragraph->getParagraphType()->label() . ': ' . $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  protected function urlRouteParameters($rel) {
    $uri_route_parameters = parent::urlRouteParameters($rel);
    if ($rel === 'revision-revert' || $rel === 'revision-delete') {
      $uri_route_parameters['paragraphs_library_item_revision'] = $this->getRevisionId();
    }
    return $uri_route_parameters;
  }
}