Container not initialized in module_implements_alter()

Created on 10 November 2024, 5 months ago

Problem/Motivation

I'm testing out the OOP hooks introduced in πŸ“Œ OOP hooks using event dispatcher Needs review and I ran into some trouble with the Field Encrypt module.

Field Encrypt is currently failing on next minor tests (pipeline and issue that created the pipeline πŸ“Œ Update GitLab CI config now that Drupal 11 is the default Active ).

The problem relates to hook_module_implements_alter().

Field Encrypt makes a call to \Drupal::state() in the hook (see the implementation). This has been working since 8.x, including 11.0, but is now broken on 11.1.x:

    Drupal\Tests\field_encrypt\Kernel\DynamicEntityHooksTest::testUnexpectedEntityTypeId
    Drupal\Core\DependencyInjection\ContainerNotInitializedException:
    \Drupal::$container is not initialized yet. \Drupal::setContainer() must be
    called with a real container.

I didn't see any mention of code updates related to hook_module_implements_alter() in the change record β†’ .

Steps to reproduce

See the pipeline described above.

πŸ› Bug report
Status

Active

Version

11.1 πŸ”₯

Component

base system

Created by

πŸ‡―πŸ‡΅Japan ptmkenny

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

Comments & Activities

  • Issue created by @ptmkenny
  • πŸ‡ΊπŸ‡ΈUnited States nicxvan

    Can you try applying this patch?

    https://www.drupal.org/project/drupal/issues/3484754 πŸ› Ordering of alter "extra hooks" is a gigantic mess Active

    This fixes a regression with hmia. I'm not sure it's related. But it's worth a try.

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

    The issue I mentioned in my previous comment will not help here.

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

    Unfortunately you'll need to refactor this portion, it falls under:
    Breaking changes
    Conditionally defined hook implementations are not supported.

    You'll likely want to actually implement
    field_encrypt_entity_insert()
    field_encrypt_entity_update()

    And check the entities in there:

    function field_encrypt_entity_insert() {
      if (in_array($entitty_type, \Drupal::state()->get('field_encrypt.entity_types', []) \Drupal::service('field_encrypt.process_entities')->decryptEntity(\$entity);
    }
    

    That will allow you to remove eval from this bit of code too which is a nice bonus.

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

    You can still use hmia then to order your hook where you want at that point.

    I'm going to close this as works as designed and I'm gonna move the relevant bit to: πŸ“Œ Support OOP hooks Active

  • πŸ‡ΊπŸ‡ΈUnited States nicxvan
  • πŸ‡―πŸ‡΅Japan ptmkenny

    Thank you very much for the quick response and clarifications!

Production build 0.71.5 2024