Problem/Motivation
On a couple of sites using the module we started getting this error when going to add block.
Error: Call to a member function get() on null in Drupal\paragraph_blocks\ParagraphBlocksLabeller->getParagraphFromLibrary() (line 219 of /app/web/modules/contrib/paragraph_blocks/src/ParagraphBlocksLabeller.php).
https://git.drupalcode.org/project/paragraph_blocks/-/blob/069a18476bf00... has loaded a paragraph, it is https://git.drupalcode.org/project/paragraph_blocks/-/blob/069a18476bf00... from_library but https://git.drupalcode.org/project/paragraph_blocks/-/blob/069a18476bf00... loads null, the target_id does not exist anymore it's been deleted.
Steps to reproduce
How you get the paragraphs into this state I've not investigated.
Proposed resolution
The getParagraphFromLibrary method already is allowed to return NULL https://git.drupalcode.org/project/paragraph_blocks/-/blob/069a18476bf00... although this isn't handled yet and also would cause a fatal error https://git.drupalcode.org/project/paragraph_blocks/-/blob/069a18476bf00...
So fixing that, by keeping the $paragraph if getting it from the library returns NULL
$paragraph = $this->getParagraphFromLibrary($paragraph) ?? $paragraph;
and making the method check that there is a library item
if ($paragraph->hasField('field_reusable_paragraph') && $library_item = LibraryItem::load($paragraph->get('field_reusable_paragraph')->target_id)) {
seems a safe thing to do, from my presently limited understanding of the code.
Remaining tasks
Create a branch
diff --git a/src/ParagraphBlocksLabeller.php b/src/ParagraphBlocksLabeller.php
index 9c77715..f2e40d4 100644
--- a/src/ParagraphBlocksLabeller.php
+++ b/src/ParagraphBlocksLabeller.php
@@ -113,7 +113,7 @@ class ParagraphBlocksLabeller {
$paragraph = $this->getParagraph($plugin_id);
// Replace the paragraph if it is from the paragraphs library.
if ($this->isParagraphFromLibrary($paragraph)) {
- $paragraph = $this->getParagraphFromLibrary($paragraph);
+ $paragraph = $this->getParagraphFromLibrary($paragraph) ?? $paragraph;
$definitions[$plugin_id]['category'] .= ' ' . $this->t('from library');
}
$definitions[$plugin_id]['admin_label'] = $this->getTitle($paragraph);
@@ -214,8 +214,7 @@ class ParagraphBlocksLabeller {
* The referenced paragraph entity or NULL.
*/
public function getParagraphFromLibrary(Paragraph $paragraph): ?EntityInterface {
- if ($paragraph->hasField('field_reusable_paragraph')) {
- $library_item = LibraryItem::load($paragraph->get('field_reusable_paragraph')->target_id);
+ if ($paragraph->hasField('field_reusable_paragraph') && $library_item = LibraryItem::load($paragraph->get('field_reusable_paragraph')->target_id)) {
return $this->paragraphStorage->loadRevision($library_item->get('paragraphs')->target_revision_id);
}
return NULL;