Problem/Motivation
I keep finding myself writing code like this:
if (!$editor->hasAssociatedFilterFormat()) {
return;
}
$format = $editor->getFilterFormat();
if (empty($format)) {
return;
}
I'd like to be able to just do this:
$format = $editor->getFilterFormat();
if (empty($format)) {
return;
}
If you do this before an editor object is saved, you get a frustrating fatal error about trying to load an entity with a NULL id.
This usually happens calling code in a subroutine at '/admin/config/content/formats/add'.
I believe you should not get a fatal error when calling $editor->getFilterFormat()
before the entity is saved. It should return NULL.
The interface even says it can return NULL, but the ::getFilterFormat() in Editor doesn't really allow for this:
/**
* Returns the filter format this text editor is associated with.
*
* This could be NULL if the associated filter format is still being created.
* @see hasAssociatedFilterFormat()
*
* @return \Drupal\filter\FilterFormatInterface|null
*/
public function getFilterFormat();
Proposed resolution
Change this code:
/**
* {@inheritdoc}
*/
public function hasAssociatedFilterFormat() {
return $this->format !== NULL;
}
/**
* {@inheritdoc}
*/
public function getFilterFormat() {
if (!$this->filterFormat) {
$this->filterFormat = \Drupal::entityTypeManager()->getStorage('filter_format')->load($this->format);
}
return $this->filterFormat;
}
To this:
/**
* {@inheritdoc}
*/
public function hasAssociatedFilterFormat() {
return $this->format !== NULL;
}
/**
* {@inheritdoc}
*/
public function getFilterFormat() {
if (!$this->hasAssociatedFilterFormat()) {
return NULL;
}
if (!$this->filterFormat) {
// Should we add a try catch here?
return \Drupal::entityTypeManager()->getStorage('filter_format')->load($this->format);
}
return NULL;
}
If this change is made, there are places where calling ::hasAssociatedFilterFormat() will be unnecessary.