Problem/Motivation

Module hooks have successfully been converted to OOP.
It would be great to convert Theme hooks to OOP.

This requires several changes and architectural changes.

  • Add theme namespaces to the container
  • Add ThemeHookCollectorPass to collect hooks
  • Update ThemeHandler to remove just in time namespace registration
  • Add updateThemes call after theme install and uninstall
  • Add invoke and invokeAllWith to support non alter calls that themes support

Architecture:
Theme hooks are different than module hooks in the following ways
1. Order is fixed
2. Only certain alters are supported
3. Very limited non alter hooks are supported

We can use Hook and throw an error if the module parameter or order parameter are set.
AI disclosure, the idea to reuse hook and throw errors on those parameters came while discussing an early draft of this with a friend while he demonstrated his method for using AI.

Additional notes:
Supported hooks in core: (contrib can support others) check for themeManager->alter and themeManager->alterForTheme

  • css_alter
  • js_alter
  • js_settings_alter
  • library_info_alter
  • form_alter
  • form_BASE_FORM_ID_alter
  • form_FORM_ID_alter
  • element_info_alter
  • page_attachments_alter
  • theme_registry_alter
  • hook_theme_suggestions_alter
  • hook_theme_suggestions_HOOK_alter
  • views_ui_display_tab_alter
  • views_ui_display_top_alter
  • plugin_filter_layout_alter
  • plugin_filter_layout__layout_alter
  • hook_views_pre_render
  • hook_views_post_render
  • hook_theme
  • hook_preprocess
  • hook_preprocess_HOOK

Steps to reproduce

N/A

Proposed resolution

  • Add theme namespaces to the container
  • Add ThemeHookCollectorPass to collect hooks in themes
  • Update ThemeHandler to remove just in time namespace registration
  • Reuse Hook Attribute
  • Use ThemeManager to execute hooks
  • Add invoke and invokeAllWith to support non alter calls that themes support

Remaining tasks

Do we need an extra CR for drupal kernel deprecations or is the main one fine
Follow up: Convert hooks

User interface changes

N/A

Introduced terminology

N/A

API changes

Theme namespaces are registered during install
Theme installer requires the kernel instead of the component plugin manager
ThemeManager now has the following new methods on the interface
- invoke
- invokeAllWith
DrupalKernel has deprecated
- getModulesParameter
- getModuleFileNames
- getModuleNamespacesPsr4

Data model changes

N/A

Release notes snippet

TBD

Issue fork drupal-3544715

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

nicxvan created an issue. See original summary.

nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Issue summary: View changes

nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Title: Convert theme hooks to OOP » Allow theme hooks to be OOP

nicxvan’s picture

nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Failures without the kernel test base changes:

Kernel Tests

  • Drupal\Tests\editor\Kernel\EditorValidationTest
  • Drupal\Tests\block\Kernel\ConfigActions
  • Drupal\Tests\block\Kernel\NewDefaultThemeBlocks
  • Drupal\KernelTests\Core\Asset\LibraryDiscoveryIntegrationTest
  • Drupal\KernelTests\Core\Theme\ThemeSettings
  • Drupal\Tests\block\Kernel\BlockStorageUnit

Functional Tests

  • Drupal\Tests\system\Functional\Theme\ThemeInfoTest
  • Drupal\Tests\system\Functional\Theme\TwigDebugMarkupTest
  • Drupal\Tests\system\Functional\Theme\ExperimentalThemeTest
  • Drupal\Tests\config_translation\Functional\ConfigTranslationUiThemeTest
  • Drupal\Tests\block\Functional\BlockDemoTest
  • Drupal\FunctionalTests\Core\Recipe\StandardRecipeTest
  • Drupal\Tests\system\Functional\Theme\TwigTransTest
  • Drupal\Tests\system\Functional\Menu\BreadcrumbTest
  • Drupal\Tests\system\Functional\System\ThemeTest

Functional js Tests

  • Drupal\Tests\ckeditor5\FunctionalJavascript\CKEditor5MarkupTest

Nightwatch

  • Olivero/oliveroMobileMenuTest

17 Tests in all, I may have missed one or two.

Alter test is fixed in the related issue.
I've looked deeply at library discovery, config action, and theme info.

nicxvan’s picture

Title: Allow theme hooks to be OOP » Add oop support to hooks currently supported by themes
nicxvan’s picture

berdir’s picture

> First we can use Hook and throw an error if the module parameter or order parameter are set.

As discussed before I would like to deprecate the module parameter anyway. On order, no objections to start there.

> Do we want to move hooks execution to ThemeHandler

No opinion really. ThemeHandler and ModuleHandler have similar names but I think the functionality they provide is quite different in practice, so I don't think we need to unless it makes things simpler.

did aa first pass through the MR, added some thoughts.

godotislate’s picture

As discussed before I would like to deprecate the module parameter anyway.

#3481903: Support hooks (Hook attribute) in any registered service has been postponed a while on a couple other issues, but I have a working POC there, and to make it possible for kernel test classes to register their own methods as hooks, we'd need to keep the module parameter.

Draft CR for reference: https://www.drupal.org/node/3526437

berdir’s picture

Going through some of the kernel test failures, reversed, because reasons. On the main MR this time.

* \Drupal\Tests\block\Kernel\BlockStorageUnitTest, this is just a stale $this->container problem. storing entity storages in properties and reusing them is just not a good idea. Passes with Block::loadMultiple()
* core/tests/Drupal/KernelTests/Core/Theme/ThemeSettingsTest.php: same, stale $theme_handler object, need to fetch it again from $this->container.
* Drupal\KernelTests\Core\Asset\LibraryDiscoveryIntegrationTest, same, $this->libraryDiscovery is stale. container rebuilds are tricky. Have I mentioned that I dislike $this->container and doing "DI" in tests recently?
* \Drupal\Tests\block\Kernel\NewDefaultThemeBlocksTest: Yes. stale $theme_installer again, specifically stale injected dependencies. See how \Drupal\Core\Extension\ModuleInstaller::updateKernel re-injects dependencies again into itself after the kernel rebuild. DI around container rebuilds is hard and messy.
* \Drupal\Tests\block\Kernel\ConfigActionsTest: This one looks like a new problem. Somehow the whole system seems to forget umami exists after the install. If I split the ThemeInstaller::install() call for umami out into a second call, then I get a Unknown themes: umami. The first time we call install(), $theme_data is 84 entries. The second time, it just has 79. umami is a profile theme. It's not supposed to be possible to install it when not using umami as a profile. So my guess is that doing a proper theme install in a kernel test actually resets some test overrides that allow it to find things within profiles and then that doesn't work anymore. So the test is kind of doing some illegal things. Maybe we can either update this to do a fake theme install only, since that's not what this is testing, or we switch to a different theme and don't use this umami for this.
* \Drupal\Tests\editor\Kernel\EditorValidationTest, this seems to lose the public stream wrapper. I know that things around this can be very weird. It's failing because StreamWrapperManager::$wrappers is empty. getWrappers() only works if the all key is initialized, this happens in \Drupal\Core\StreamWrapper\StreamWrapperManager::registerWrapper(), so we're reinitializing the StreamWrapperManager and don't call register on it. for kernel tests, this is initially done through DrupalKernel::preHandle() in \Drupal\KernelTests\KernelTestBase::bootKernel(). I'm not sure why there aren't more fails like this. ModuleInstaller does call the register method. It feels like that should happen elsewhere or maybe the stream wrapper should be more intelligent about registering if that hasn't been done yet?

nicxvan’s picture

Thank you so much!

I'm wondering if we should reset some of these somewhere or just let these be test only artifacts.

I ready the steam wrapper in theme install and that makes Drupal\Tests\editor\Kernel\EditorValidationTest pass.

Thank you for validating my umami weirdness findings, I had thought it was a red herring, but you found what I found, it initially calls the scan with no profile at so it finds everything, then when it gets to the test the profile is set to a test one so umami isn't found.

Let's just change to another theme for the test.

nicxvan changed the visibility of the branch 3544715-kernelTestBase to hidden.

nicxvan changed the visibility of the branch 11.x to hidden.

nicxvan’s picture

I fixed Drupal\Tests\block\Kernel\NewDefaultThemeBlocksTest by just getting a fresh installer like you suggested.

Then for Drupal\Tests\block\Kernel\ConfigActionsTest i used the block test theme which also had a content region.

I'm starting to work through Functional Tests, the first is that messages are not being displayed relating to install which i suspect is a similar issue, but if i recall correctly container build persists messages.

nicxvan’s picture

Looking at the Functional Javascript failures:

One is MediaLinkabilityTest.php
$assert_session->assertNoElementAfterWait('css', 'figure.drupal-media > figcaption');
Not sure why that's failing yet.

The other is CKEditor5Test.php
This is just a new order of the attributes but they are all correct. I think we can just update the order in the test.

Edit: turns out these are false positives.

nicxvan’s picture

Knocking them down!

Just a few failures left:

Config Translation Ui Theme (Drupal\Tests\config_translation\Functional\ConfigTranslationUiTheme)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/confi...

Twig Trans (Drupal\Tests\system\Functional\Theme\TwigTrans)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

Breadcrumb (Drupal\Tests\system\Functional\Menu\Breadcrumb)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

Theme (Drupal\Tests\system\Functional\System\Theme)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

Experimental Theme (Drupal\Tests\system\Functional\Theme\ExperimentalTheme)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

For the first the route provided is access denied.
For the last the install message doesn't display

Haven't dug into the others.

Edit:
Quickly went through and put a drupal_flush_all_caches right before each failure, this fixed all of the failures except the last two so I suspect we just have one other stale service related to language that needs resetting.

The last two are something else.

nicxvan’s picture

Issue summary: View changes

nicxvan changed the visibility of the branch 3544715-themeproceduralcall to hidden.

nicxvan’s picture

Adding the plugin clear and router rebuild fixed most of the remaining.

Failures:
Twig Trans (Drupal\Tests\system\Functional\Theme\TwigTrans)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for system.site with the following errors: 0 [default_langcode] The value you selected is not a valid choice.

Theme (Drupal\Tests\system\Functional\System\Theme)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

Theme settings color hex code
       ┐
       ├ Failed asserting that two strings are identical.
       ┊ ---·Expected
       ┊ +++·Actual
       ┊ @@ @@
       ┊ -'#F0F'
       ┊ +'0F0'

Experimental Theme (Drupal\Tests\system\Functional\Theme\ExperimentalTheme)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

Experimental confirm form
       ┐
       ├ Behat\Mink\Exception\ResponseTextException: The text "The Experimental test theme has been installed." was not found anywhere in the text of the current page.

I also started working on preprocess but it is very rough and I think it's not actually working since function exists is there still.

nicxvan’s picture

Ok I got the theme and translation tests.

Only remaining test is:
Experimental Theme (Drupal\Tests\system\Functional\Theme\ExperimentalTheme)
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/syste...

Experimental confirm form
       ┐
       ├ Behat\Mink\Exception\ResponseTextException: The text "The Experimental test theme has been installed." was not found anywhere in the text of the current page.

It is reproducible in the UI.
When enabling experimental_theme_test you get the confirmation to enable an experimental theme but no message once it is done.
The code does hit this line $this->messenger()->addStatus($this->t('The %theme theme has been installed.', ['%theme' => $themes[$theme]->info['name']])); in ThemeExperimentalConfirmForm.

nicxvan’s picture

Ok I added some tests for normal hooks.

Preprocess needs tests and likely some work.

The last failing test messenger trait seems to be holding onto the old messenger service hard.

I even called setmessenger from the theme installer and the confirm experimental form still has the old service.

When in the form calling drupal service messenger has the correct messenger instance and the test passes.

But that's obviously not a real solution.
Any ideas would be great!

nicxvan’s picture

Issue summary: View changes

Spent some more time looking at this.

@catch said it's fine for now to just use the service call directly and then create a follow up which I did.

We should be green.

This is mostly ready for review, I still need to write tests for preprocess, I think I'll pull those changes into the main MR now though.
I need to review the one or two remaining @todo

nicxvan changed the visibility of the branch 3544715-preprocess to hidden.

nicxvan’s picture

Issue summary: View changes
Status: Active » Needs review

I think this is ready for review, let's move the preprocess work to a follow up, I'll continue in the hidden branch here, but this already is doing a lot so we can review it as is.

I know @berdir wants to review options for how we're storing and collecting them, but I think the rest of this is ready for review and discussion!

nicxvan’s picture

Title: Add oop support to hooks currently supported by themes » Add oop support to hooks currently supported by themes except preprocess
nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Status: Needs review » Needs work

I broke something while consolidating.

There is more consolidation to do so back to needs work.

nicxvan changed the visibility of the branch 3544715-convert-theme-hooks-consolidated to hidden.

nicxvan’s picture

Status: Needs work » Needs review

I reverted some of the consolidation so the tests should be passing while people review the high level concepts, I'll create a separate consolidation branch to work on consolidating some of the kernel duplication in the meantime.

nicxvan changed the visibility of the branch 3544715-convert-theme-hooks-consolidated2 to hidden.

needs-review-queue-bot’s picture

Status: Needs review » Needs work
StatusFileSize
new17.14 KB

The Needs Review Queue Bot tested this issue. It fails the Drupal core commit checks. Therefore, this issue status is now "Needs work".

This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

nicxvan’s picture

Issue summary: View changes
Status: Needs work » Needs review
Issue tags: +no-needs-review-bot

I've got too many MRs the bot is confused.

I consolidated some of the duplicate methods on the kernel to reduce duplication.

I left updateThemes/updateModules and themeData/moduleData since they would require some pass by reference stuff that will likely make it far more complex.

I did do a pass where I tried to fully consolidate the data property, but it gets reset on a theme and everything breaks and will make it far harder for BC.

I will continue to tinker on the preprocess branch while this gather's reviews, but I think this is ready.

jurgenhaas’s picture

Went through the "Problem/Motivation" and compared it with what we're working on while merging Gin into core by also incorporating all from Claro.

I found 2 missing hooks that are currently used by Claro and that are not in the hook list above:

  • hook_theme_suggestions_HOOK_alter
  • hook_views_pre_render

Then, I also found 2 special cases of library_info_alter and theme_registry_alter:

  • gin_system_module_invoked_library_info_alter
  • gin_system_module_invoked_theme_registry_alter

Are they supported as well? I mean, they're special as the hook is not just gin but gin_system_module_invoked. The comment in the current 5.x code reads like this:

/**
 * Called by system.module via its hook_library_info_alter().
 *
 * If the active theme is not Gin, but Gin is the admin theme, this alters
 * the toolbar library config so Gin's toolbar stylesheets are used.
 *
 * @see system_library_info_alter()
 */

Other than that we also have 51 preprocessors in Gin and Claro collectively. I guess that follow-up doesn't exist yet?

nicxvan’s picture

hook_theme_suggestions_HOOK_alter should be covered:

    // Invoke hook_theme_suggestions_alter() and
    // hook_theme_suggestions_HOOK_alter().
    $hooks = [
      'theme_suggestions',
      'theme_suggestions_' . $base_theme_hook,
    ];
    $this->moduleHandler->alter($hooks, $suggestions, $variables, $base_theme_hook);
    $this->alter($hooks, $suggestions, $variables, $base_theme_hook);

hook_views_pre_render is a weird one, maybe we can update that to use alter for theme:

      $function = $theme_name . '_views_pre_render';
      if (function_exists($function)) {
        $function($this);
      }

Also for:

  • gin_system_module_invoked_library_info_alter
  • gin_system_module_invoked_theme_registry_alter

Those are not hooks, they are helpers called from another hook.
Basically system implements: library_info_alter then calls the claro version.
I think it's a case of a poorly named function in core that looks like a hook that is really a helper then that pattern was copied and pasted.
Does gin_toolbar implement library_info_alter and theme_registry_alter then call those two functions?

jurgenhaas’s picture

hook_theme_suggestions_HOOK_alter should be covered:

Oh, I'll give that a try. Maybe worth an update of the IP then?

nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Status: Needs review » Needs work

Moving back to needs work since the event dispatcher removal took a different direction, I pushed up a very rough and untested version following that pattern.

I still may need to extract the include bit and work on the preprocess for suggestions bit.

I'm going to open an MR to see what we're missing, but I expect it to fail.

nicxvan’s picture

Got it back to green, gotta handle BC properly and preprocess suggestions for themes, but that might be better done when the other issue lands.

I'm going to leave this in needs work for that, but it can be reviewed by interested parties for the approach.

nicxvan changed the visibility of the branch 3544715-convert-theme-hooks to hidden.

nicxvan changed the visibility of the branch 3544715-convert-theme-hooks-keyvalue to hidden.

nicxvan changed the visibility of the branch 3544715-convert-theme-hooks-keyvalue to active.

jurgenhaas’s picture

Issue summary: View changes

I have rebased MR!13412 so that it can be applied to 11.x again

nicxvan’s picture

I'll take a look at the failing tests.

nicxvan’s picture

I created a branch from the tag before the rebase so we can see if tests pass.

I will take a look later at rebasing myself since there are likely a lot of gnarly conflicts.

nicxvan’s picture

Issue summary: View changes

Issue summary was out of date so I updated it.

nicxvan’s picture

I rebased.

I still have to finish consolidating the hook collector changes, registry and performance tests.

I will continue working on this.

nicxvan’s picture

Status: Needs work » Needs review

This is green again, performance tests being chained took some churn since I cannot run them locally for some reason.

I'd love to get preprocess in here too, but got snagged up there.
We may need to address hook_theme in themes too as a gap.

I split out HookCollector to make it easier to integrate HookCollectorPass and ThemeHookCollectorPass with common methods.

I intentionally did not update HookCollectorPass though to reduce the number of changes.

I created a follow up for that.

BC for ThemeInstaller and ThemeManager is still an open question, but I think like ModuleHandler we can skip that with a CR.

I'll work on CRs in the next few days since this still needs a full review.

nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Issue summary: View changes

nicxvan changed the visibility of the branch 3544715-keyvalue-theme-with-invoke to hidden.

nicxvan changed the visibility of the branch 3544715-keyvalue-theme-with-invoke to hidden.

berdir’s picture

Status: Needs review » Needs work

Posted a detailed review of the non-test changes.

nicxvan’s picture

Assigned: Unassigned » nicxvan

Thank you for the detailed review, I'm going to assign this to myself for now since I want to take care of the feedback.

nicxvan’s picture

Title: Add oop support to hooks currently supported by themes except preprocess » Add oop support to most hooks currently supported by themes
nicxvan’s picture

Issue summary: View changes
Status: Needs work » Needs review

Ok I think this is ready for review again. I've refactored most things based on your feedback and I think it's been a huge improvement.

There are a couple of open threads still.
One I think we should leave as is, one I think can be a follow up.

The other two are just comments that need confirmation from you it is satisfactory.

Since last round I have replaced the DrupalKernel methods I removed and deprecated them, added remaining task question about CR
I have added invoke and invokeWith so we can convert:

  • hook_views_pre_render
  • hook_views_post_render
  • hook_theme

This leaves only preprocess and preprocess__HOOK which is nice considering we can follow the same pattern as modules and just do it in a follow up.

nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Issue summary: View changes

I handled the last todo so I removed it from the IS.

I also updated invokeAllWith and added invokeAllWithForTheme to match the alter and alterForTheme pattern to simplify calls.

nicxvan’s picture

Assigned: nicxvan » Unassigned
nicxvan’s picture

Assigned: Unassigned » nicxvan
Issue summary: View changes
Status: Needs review » Needs work
nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Assigned: nicxvan » Unassigned
Status: Needs work » Needs review

Didn't mean to change status, I updated the IS to be accurate and rebased.

nicxvan’s picture

Issue summary: View changes

Simplified ThemeCollectorPass a bit more and updated the IS

jurgenhaas’s picture

I've tested the latest version of the MR again with the Gin 6.x branch, and all still works as expected. Leaving it at NR as I haven't reviewed the code.

jfurnas’s picture

I'm a little confused on the documentation of this.

It states that 'modules cannot implement hooks on behalf of a theme.'

Does this mean that you can no longer use for example 'hook_theme' (but the OOP equivalent of it) in a dedicated module file now? If so, that seems pretty limiting as it's easier to create a basic module and enable it than it is to create a subtheme of a contrib theme (if the contrib theme even supports it), just for sticking in a theme hook.

Additionally, it lists form_alter as a theme hook. Does this mean that you can no longer use form_alters in modules? Because I am using them currently in the OOP version of a custom module and they work, so am now curious if it's going to break backwards compatability.

NOTE: I am reading the changelog notes for this issue: https://www.drupal.org/node/3551652

nicxvan’s picture

Thank you for checking that!

No, that is not what this means, nothing here changes how hooks work in modules.

This issue is only about extending OOP support to hooks that exist IN themes.

So for example in gin you have a gin_form_alter, that can now be in src/Hook/GinFormHooks.php with a #[Hook('form_alter')]

modules cannot implement hooks on behalf of a theme.

Refers to the fact that currently if you create gin_form_alter in a custom module when the theme executes it's hooks that would run.
This behavior is unintentional and incompatible with OOP hooks.

It is confusing so maybe we should cut it out of the CR. But someone somewhere might be relying on that.

berdir’s picture

I think that information probably belongs somewhere but not in this CR. Because it's not targeted towards themes, but modules. If anything, we'd need to document the opposite here, that we do not support defining hooks for modules in themes, which technically was also possible now, it was just very unpredictable and only worked if the theme was already loaded and would always be loaded when the hook is invoked.

Also, maybe we can clarify that we don't support *discovery* of such hooks anymore. But it's actually very easy now (but not explicitly supported and covered by BC, IMHO) to put stuff in the theme data parameters, just like #3502432: Make hook testing with kernel tests very simple is doing. You could easily add an arbitrary callback to a specific theme in a service provider. And I think there are interesting use cases or that, we've struggled a few times hardcoded form alters such as claro_form_node_form_alter() that we wanted to undo and currently the only option would be to define a subtheme if claro.

nicxvan’s picture

I'm on the fence, I moved it to the bottom and marked it as an edge case.

Because it's not targeted towards themes, but modules.

Yes, but it's this change that makes it not work now.

godotislate’s picture

Status: Needs review » Needs work

Some comments on the MR.

nicxvan’s picture

Assigned: Unassigned » nicxvan

I will take care of these! Thank you.

Assigning myself again.

nicxvan’s picture

Status: Needs work » Needs review

CR needs some work, but I addressed almost all of the latest round of feedback.

Two comments I replied to and the array shapes I sent a question in slack.

Should be ready for review again.

I also did some additional manual testing installing from drush and through the browser both standard and umami and set the maintenance theme. All looked great!

nicxvan’s picture

Assigned: nicxvan » Unassigned
godotislate’s picture

Didn't have time to look at this again this weekend, but should be able to look tomorrow.

berdir changed the visibility of the branch 3544715-preprocess-ignore to hidden.

nicxvan’s picture

Issue summary: View changes
nicxvan’s picture

Issue summary: View changes

Pulled in the preprocess suggestion from berdir after a careful review locally and testing. It matches the precedent for modules and let's us provide support out of the gate so I think it makes sense to include.

nicxvan’s picture

Title: Add oop support to most hooks currently supported by themes » Add oop support to hooks currently supported by themes
jurgenhaas’s picture

Issue summary: View changes

FYI, I've tested the current MR again with Gin 6.x and everything is still working as before. I also noticed that this is now supporting preprocess hooks, and I migrated them in Gin too. So, Gin is now free of procedural PHP Code !!!

godotislate’s picture

I think implementing an invokeAll() method in the them manager would be a nice to have, but probably would work for a follow up if needed.

A couple small suggestions to add return typedefs to a couple new protected methods, not sure how I missed those before. I would not say they're a blocker though, so feel free to apply suggestions (or not) and self RTBC.

godotislate’s picture

Almost forgot: is there explicit testing that the base theme(s) hook implementations are invoked as expected?

nicxvan’s picture

Status: Needs review » Reviewed & tested by the community

No objection to these return types.

If a committer thinks we need invokeAll we can add it, but we don't need it for any core hooks right now in themes and both berdir and godotidlate indicated it's not a blocker.

Rtbc per 99!

berdir’s picture

Status: Reviewed & tested by the community » Needs work

I added a few more comments of things we should update.

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

nicxvan’s picture

Status: Needs work » Needs review

Addressed current feedback!

berdir’s picture

Status: Needs review » Reviewed & tested by the community

This was already RTBC and my comments were addressed. It's big and it does a lot in one single issue, has some drawbacks like more container rebuilds but it brings themes up to speed on what we've been working on around module hooks since 1y+.

We need follow-ups to convert the .theme files, I think one issue per theme would make sense and one or multiple for all the test themes (minus a few for BC testing I guess). Only a handful of hooks are already converted here, but there's quite a bit of testing, including updated unit tests around preprocess. Also, Gin has already been fully updated on top of this, so we have a good amount of real world testing.

nicxvan’s picture

nicxvan’s picture

Rebased for perf tests

nicxvan’s picture

The failing test is random, I've rerun it about 10 times and each time it's different, a fix here #3554055: Stablize performance tests

Edit: Fix is in rebased.

berdir’s picture

Did a rebase after theme_get_setting() got in, added DI, relevant change:

$ git diff drupal-3544715/3544715-keyvalue-theme-previous core/themes/olivero/src/Hook/OliveroPagePreprocessHooks.php
diff --git a/core/themes/olivero/src/Hook/OliveroPagePreprocessHooks.php b/core/themes/olivero/src/Hook/OliveroPagePreprocessHooks.php
index dc1899b572f..bcd4c66a351 100644
--- a/core/themes/olivero/src/Hook/OliveroPagePreprocessHooks.php
+++ b/core/themes/olivero/src/Hook/OliveroPagePreprocessHooks.php
@@ -4,6 +4,7 @@

use Drupal\Core\Asset\AssetQueryStringInterface;
use Drupal\Core\Extension\ThemeExtensionList;
+use Drupal\Core\Extension\ThemeSettingsProvider;
use Drupal\Core\Hook\Attribute\Hook;
use Symfony\Component\HttpFoundation\RequestStack;

@@ -16,6 +17,7 @@ public function __construct(
      protected RequestStack $requestStack,
      protected ThemeExtensionList $themeExtensionList,
      protected AssetQueryStringInterface $assetQueryString,
+    protected ThemeSettingsProvider $themeSettingsProvider,
) {
}

@@ -26,12 +28,12 @@ public function __construct(
*/
#[Hook('preprocess_html')]
public function preprocessHtml(array &$variables): void {
-    if (theme_get_setting('mobile_menu_all_widths') === 1) {
+    if ($this->themeSettingsProvider->getSetting('mobile_menu_all_widths') === 1) {
$variables['attributes']['class'][] = 'is-always-mobile-nav';
}

// Convert custom hex to hsl so we can use the hue value.
-    $brand_color_hex = theme_get_setting('base_primary_color') ?? '#1b9ae4';
+    $brand_color_hex = $this->themeSettingsProvider->getSetting('base_primary_color') ?? '#1b9ae4';
[$h, $s, $l] = _olivero_hex_to_hsl($brand_color_hex);

$variables['html_attributes']->setAttribute('style', "--color--primary-hue:$h;--color--primary-saturation:$s%;--color--primary-lightness:$l");

(indention is off, something weird with terminal copying)

alexpott’s picture

Status: Reviewed & tested by the community » Needs work

We need to fix resetSystem() to re-inject all the container services that we have as properties. And this is really awkward because we've made all the service properties read only - we're going to have to undo this.

nicxvan’s picture

Changes in 109 look good and were expected!

I'm working on 110 right now.

nicxvan’s picture

Thank you for helping out, that ended up being a bit trickier that I thought.

I think the bit I missed was nesting the module list check.

My only change since last rtbc was https://git.drupalcode.org/project/drupal/-/merge_requests/13465/diffs?c... which was reviewed in slack.

I carefully reviewed alexpotts changes individually and in aggregate. Looks good and reduces the amount of scanning. I liked the name themeEnabledList to help differentiate, but it's not worth holding this up.

It's also nice that these two fixes let us roll back one of the test changes!

I also reviewed berdir's change and it is in line with what we expected.

I don't think the new related issue is really quite a blocker, but it came out of this.

All feedback addressed, it might be a bit ambitious but I think it's ok to RTBC.

alexpott’s picture

The problem with themeEnabledList is that it makes the programmer wonder about moduleList. And we don't need to change that here. Because of how we review we often miss the context of the rest of the class (this was even more true in the days of patches and dreditor).

jurgenhaas’s picture

Status: Needs work » Needs review

Lot's of changes again, time to test this with the Gin 6.x again. Good news, this is still working with any issues. And we've also replaced the call to the deprecated theme_get_setting method successfully.

Looks like this should be NR according to the last 2 comments. My tests most likely don't qualify for RTBC yet.

alexpott’s picture

My comment in #113 is explaining why I changed themeEnabledList to themeList and in no way should block an rtbc.

The changes made yesterday are very very low level and don't affect the nature of the API or even functionality - they were all about the performance implications of this change and minimising them and will have no impact on themes or modules.

nicxvan’s picture

Status: Needs review » Reviewed & tested by the community

I think we're good again!

Fair enough on the naming, I think that makes sense.

alexpott’s picture

Issue summary: View changes

Preprocess ended up being included here so fixing the issue summary.

nicxvan’s picture

Issue summary: View changes

Someone had a stale issue summary and overwrote the changes unintentionally I think, I'll confirm the rest later.

catch’s picture

Status: Reviewed & tested by the community » Fixed

Gave this another look over. I can't see anything left to complain about, the new follow-up created at the last minute is fine to do in a follow-up. Committed/pushed to 11.x, thanks!

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

  • catch committed 7c9aacf5 on 11.x
    Issue #3544715 by nicxvan, berdir, godotislate, jurgenhaas, catch,...

  • catch committed 11b6150f on 11.3.x
    Issue #3544715 by nicxvan, berdir, godotislate, jurgenhaas, catch,...
catch’s picture

Tagging for highlights.

demeritcowboy’s picture

Hi,
I've filed https://www.drupal.org/project/drupal/issues/3555844 since something about this commit seems to have changed how drupalLogin and currentUser work in unit tests.

Status: Fixed » Closed (fixed)

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

geek-merlin’s picture

Crosslinking a regression.