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
| Comment | File | Size | Author |
|---|
Issue fork drupal-3544715
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:
- 3544715-keyvalue-theme-previous
changes, plain diff MR !13465
- 3544715-preprocess-ignore
changes, plain diff MR !13545
- 3544715-keyvalue-theme-with-invoke
changes, plain diff MR !13467
- 3544715-convert-theme-hooks
changes, plain diff MR !13148
- 3544715-preprocess
changes, plain diff MR !13242
- 3544715-convert-theme-hooks-keyvalue
changes, plain diff MR !13412
- 3544715-convert-theme-hooks-consolidated2
compare
- 3544715-kernelTestBase
changes, plain diff MR !13155
- 3544715-convert-theme-hooks-consolidated
compare
- 3544715-themeproceduralcall
changes, plain diff MR !13233
- 11.x
compare
Comments
Comment #2
nicxvan commentedComment #3
nicxvan commentedComment #5
nicxvan commentedComment #6
nicxvan commentedComment #7
nicxvan commentedComment #9
nicxvan commentedComment #10
nicxvan commentedComment #11
nicxvan commentedComment #12
nicxvan commentedFailures without the kernel test base changes:
Kernel Tests
Functional Tests
Functional js Tests
Nightwatch
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.
Comment #13
nicxvan commentedComment #14
nicxvan commentedComment #15
berdir> 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.
Comment #16
godotislate#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
moduleparameter.Draft CR for reference: https://www.drupal.org/node/3526437
Comment #17
berdirGoing 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?
Comment #18
nicxvan commentedThank 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.
Comment #21
nicxvan commentedI 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.
Comment #22
nicxvan commentedLooking 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.phpThis 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.
Comment #23
nicxvan commentedKnocking 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.
Comment #24
nicxvan commentedComment #29
nicxvan commentedAdding 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...
Theme (Drupal\Tests\system\Functional\System\Theme)
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...
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.
Comment #30
nicxvan commentedOk 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...
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.Comment #31
nicxvan commentedOk 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!
Comment #32
nicxvan commentedSpent 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
Comment #34
nicxvan commentedI 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!
Comment #35
nicxvan commentedComment #36
nicxvan commentedComment #37
nicxvan commentedI broke something while consolidating.
There is more consolidation to do so back to needs work.
Comment #39
nicxvan commentedI 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.
Comment #42
needs-review-queue-bot commentedThe 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.
Comment #43
nicxvan commentedI'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.
Comment #44
jurgenhaasWent 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:
Then, I also found 2 special cases of
library_info_alterandtheme_registry_alter:Are they supported as well? I mean, they're special as the hook is not just
ginbutgin_system_module_invoked. The comment in the current 5.x code reads like this:Other than that we also have 51 preprocessors in Gin and Claro collectively. I guess that follow-up doesn't exist yet?
Comment #45
nicxvan commentedhook_theme_suggestions_HOOK_alter should be covered:
hook_views_pre_render is a weird one, maybe we can update that to use alter for theme:
Also for:
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_alterandtheme_registry_alterthen call those two functions?Comment #46
jurgenhaasOh, I'll give that a try. Maybe worth an update of the IP then?
Comment #47
nicxvan commentedComment #48
nicxvan commentedMoving 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.
Comment #50
nicxvan commentedGot 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.
Comment #54
jurgenhaasI have rebased MR!13412 so that it can be applied to 11.x again
Comment #55
nicxvan commentedI'll take a look at the failing tests.
Comment #57
nicxvan commentedI 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.
Comment #58
nicxvan commentedIssue summary was out of date so I updated it.
Comment #59
nicxvan commentedI rebased.
I still have to finish consolidating the hook collector changes, registry and performance tests.
I will continue working on this.
Comment #63
nicxvan commentedThis 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.
Comment #64
nicxvan commentedComment #65
nicxvan commentedComment #66
nicxvan commentedComment #70
berdirPosted a detailed review of the non-test changes.
Comment #71
nicxvan commentedThank you for the detailed review, I'm going to assign this to myself for now since I want to take care of the feedback.
Comment #72
nicxvan commentedComment #73
nicxvan commentedOk 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:
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.
Comment #74
nicxvan commentedComment #75
nicxvan commentedI 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.
Comment #76
nicxvan commentedComment #77
nicxvan commentedComment #78
nicxvan commentedComment #79
nicxvan commentedDidn't mean to change status, I updated the IS to be accurate and rebased.
Comment #80
nicxvan commentedSimplified ThemeCollectorPass a bit more and updated the IS
Comment #81
jurgenhaasI'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.
Comment #83
jfurnas commentedI'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
Comment #84
nicxvan commentedThank 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.phpwith a#[Hook('form_alter')]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.
Comment #85
berdirI 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.
Comment #86
nicxvan commentedI'm on the fence, I moved it to the bottom and marked it as an edge case.
Yes, but it's this change that makes it not work now.
Comment #87
godotislateSome comments on the MR.
Comment #88
nicxvan commentedI will take care of these! Thank you.
Assigning myself again.
Comment #89
nicxvan commentedCR 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!
Comment #90
nicxvan commentedComment #91
godotislateDidn't have time to look at this again this weekend, but should be able to look tomorrow.
Comment #94
nicxvan commentedComment #95
nicxvan commentedPulled 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.
Comment #96
nicxvan commentedComment #97
jurgenhaasFYI, 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 !!!
Comment #98
godotislateI 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.
Comment #99
godotislateAlmost forgot: is there explicit testing that the base theme(s) hook implementations are invoked as expected?
Comment #100
nicxvan commentedNo 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!
Comment #102
berdirI added a few more comments of things we should update.
Comment #104
nicxvan commentedAddressed current feedback!
Comment #105
berdirThis 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.
Comment #106
nicxvan commentedComment #107
nicxvan commentedRebased for perf tests
Comment #108
nicxvan commentedThe 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.
Comment #109
berdirDid a rebase after theme_get_setting() got in, added DI, relevant change:
(indention is off, something weird with terminal copying)
Comment #110
alexpottWe 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.
Comment #111
nicxvan commentedChanges in 109 look good and were expected!
I'm working on 110 right now.
Comment #112
nicxvan commentedThank 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.
Comment #113
alexpottThe 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).
Comment #114
jurgenhaasLot'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_settingmethod successfully.Looks like this should be NR according to the last 2 comments. My tests most likely don't qualify for RTBC yet.
Comment #115
alexpottMy comment in #113 is explaining why I changed
themeEnabledListtothemeListand 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.
Comment #116
nicxvan commentedI think we're good again!
Fair enough on the naming, I think that makes sense.
Comment #117
alexpottPreprocess ended up being included here so fixing the issue summary.
Comment #118
nicxvan commentedSomeone had a stale issue summary and overwrote the changes unintentionally I think, I'll confirm the rest later.
Comment #119
catchGave 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!
Comment #124
catchTagging for highlights.
Comment #125
demeritcowboy commentedHi,
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.
Comment #127
geek-merlinCrosslinking a regression.