public static function LibraryItem::createFromParagraph

Creates a library entity from a paragraph entity.

Parameters

\Drupal\paragraphs\ParagraphInterface $paragraph: The paragraph entity.

Return value

static The library item entity.

Throws

\Exception If a conversion is attempted for bundles that don't support it.

Overrides LibraryItemInterface::createFromParagraph

1 call to LibraryItem::createFromParagraph()
paragraphs_library_make_library_item_submit in paragraphs/modules/paragraphs_library/paragraphs_library.module
Make library item submit callback.

File

paragraphs/modules/paragraphs_library/src/Entity/LibraryItem.php, line 248

Class

LibraryItem
Defines the LibraryItem entity.

Namespace

Drupal\paragraphs_library\Entity

Code

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,
    'langcode' => $paragraph
      ->language()
      ->getId(),
  ]);

  // If the item has a moderation field, set it to published.
  if ($library_item
    ->hasField('moderation_state')) {
    $library_item
      ->set('moderation_state', 'published');
  }

  // 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)));
  }
  return $library_item;
}