You are here

public static function LibraryItem::createFromParagraph in Paragraphs 8

Creates a library entity from a paragraph entity.

Parameters

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

Return value

\Drupal\paragraphs_library\LibraryItemInterface 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 modules/paragraphs_library/paragraphs_library.module
Make library item submit callback.

File

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(),
  ]);

  // 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;
}