Creates a library entity from a paragraph entity.
\Drupal\paragraphs\ParagraphInterface $paragraph: The paragraph entity.
static The library item entity.
\Exception If a conversion is attempted for bundles that don't support it.
Overrides LibraryItemInterface::createFromParagraph
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;
}