Problem/Motivation

The logic in ConfigManager::getEntityTypeIdByName() is needlessly complicated:

  public function getEntityTypeIdByName($name) {
    $entities = array_filter($this->entityTypeManager->getDefinitions(), function (EntityTypeInterface $entity_type) use ($name) {
      return ($entity_type instanceof ConfigEntityTypeInterface && $config_prefix = $entity_type->getConfigPrefix()) && strpos($name, $config_prefix . '.') === 0;
    });
    return key($entities);
  }

It's using array_filter with a custom filter callback to find those entity types whose config prefix matches the given config $name.
But it then returns only the first one found, using key() -- since there should only be one.

I think it would be much easier to read and debug if it did this:

foreach (($this->entityTypeManager->getDefinitions() as $entity_type) {
 if (condition ... ) {
  return entity type ID
 }
}

Steps to reproduce

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

Release notes snippet

Issue fork drupal-3328066

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

joachim created an issue. See original summary.

rpayanm made their first commit to this issue’s fork.

rpayanm’s picture

Status: Active » Needs review
joachim’s picture

Status: Needs review » Needs work
rpayanm’s picture

Status: Needs work » Needs review

@joachim Thank you for reviewing it, I created a new commit.

joachim’s picture

Status: Needs review » Reviewed & tested by the community

Looks good. Thanks!

  • xjm committed 75035a0f on 10.1.x
    Issue #3328066 by rpayanm, joachim: simplify logic in ConfigManager::...

  • xjm committed db906a7b on 10.0.x
    Issue #3328066 by rpayanm, joachim: simplify logic in ConfigManager::...
xjm’s picture

Nice code cleanup! Thanks @joachim for finding it and @rpayanm for implementing a nice clean fix.

Committed to 10.1.x and cherry-picked to 10.0.x. Since it uses str_starts_with(), we can't backport it to 9.5.x, but I think that's fine. There would be a merge conflict on the line either way if we used strpos(). (See also #3328456: Replace substr($a, 0, $i) with str_starts_with() and #3328443: Replace most strpos() === 0 or !== 0 with str_starts_with().)

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.