EntityBase::toLink() should ensure $text is a string

Created on 17 August 2025, 6 days ago

Problem/Motivation

The EntityBase::toLink() method creates a new Link object. The Link object constructor requires the first parameter to be a string.

EntityBase does not ensure that $text is a string.

If the $text is passed as NULL, it does fall back to $this->getLabel().

But, EntityBase::getLabel() may also return NULL.

If this occurs, Link will eventually invoke LinkGenerator::doGenerate(), which will call Html::escape() with a NULL value, which will cause a WSOD.

Steps to reproduce

  1. Create an entity
  2. Ensure it will return NULL for getLabel() (e.g. hard code the entity class to return NULL)
  3. Call $entity->toLink()->toString();

Proposed resolution

We should ensure we do not pass a non-string value to the Link constructor.

πŸ› Bug report
Status

Active

Version

11.0 πŸ”₯

Component

entity system

Created by

πŸ‡ΊπŸ‡ΈUnited States TomTech

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @TomTech
  • Pipeline finished with Success
    6 days ago
    Total: 659s
    #574929
  • πŸ‡ΊπŸ‡ΈUnited States TomTech

    I've created an MR that simply falls back to the entity id if the label returns NULL, as it is likely that it would at least have an id.

    id(), though, can also return NULL, so the MR then falls back to empty string.

    The URL would obviously not be visible on a page with no text, but this seems better than the current WSOD. We could also fall back to some placeholder text, if we could agree on the appropriate text.

  • πŸ‡ΊπŸ‡ΈUnited States smustgrave

    Can you elaborate on why you would do

    hard code the entity class to return NULL

    . May help drive the tests.

  • πŸ‡ΊπŸ‡ΈUnited States TomTech

    Well, that's just a brute force way. :)

    The definition for label() is:

      /**
       * Gets the label of the entity.
       *
       * @return string|\Drupal\Core\StringTranslation\TranslatableMarkup|null
       *   The label of the entity, or NULL if there is no label defined.
       */
      public function label();
    
    

    so it is documented to return NULL.

    But, toLink() calls:

        return new Link($text, $url);
    
    

    which expects a string, not ?string.

    Another approach:

    Implement an EventSubscriber that subscribes to ProfileEvents::PROFILE_LABEL, and in the invoked method, call $event->setLabel(NULL).

    Or, implement a custom entity, but do NOT set a label entity key.

Production build 0.71.5 2024