33namespace Drupal \uebertool_twig_loader \Template \Loader ;
44
55use Drupal \Core \Asset \LibraryDiscoveryInterface ;
6+ use Drupal \Core \Extension \ThemeHandlerInterface ;
67use Drupal \Core \Theme \ComponentPluginManager ;
78use Drupal \Core \Render \Component \Exception \ComponentNotFoundException ;
89use Drupal \Core \Template \Loader \ComponentLoader ;
10+ use Drupal \Core \Theme \ExtensionType ;
911use Twig \Source ;
1012use Twig \Loader \LoaderInterface ;
1113
@@ -18,38 +20,36 @@ public function __construct(
1820 protected ComponentLoader $ prototype ,
1921 protected ComponentPluginManager $ pluginManager ,
2022 protected LibraryDiscoveryInterface $ libraryDiscovery ,
23+ protected ThemeHandlerInterface $ themeHandler ,
2124 ) {}
2225
2326 /**
2427 * {@inheritdoc}
2528 */
2629 public function getSourceContext ($ name ): Source {
27- try {
28- $ component = $ this ->pluginManager ->find ($ name );
29- $ path = $ component ->getTemplatePath ();
30- $ themeName = explode ($ component ::DERIVATIVE_SEPARATOR , $ component ->getPluginId ())[0 ];
31- $ distThemeName = "{$ themeName }_dist " ;
32- }
33- catch (ComponentNotFoundException $ e ) {
34- return new Source ('' , $ name , '' );
35- }
36- $ original_code = file_get_contents ($ path );
30+ $ source = $ this ->prototype ->getSourceContext ($ name );
3731
38- $ prefix = '' ;
32+ // Skip empty/non-existing components.
33+ if ($ source ->getCode () === '' && $ source ->getPath () === '' ) {
34+ return $ source ;
35+ }
3936
40- $ componentName = $ component ->getDerivativeId ();
41- $ libraryName = "sdc-- {$ componentName }" ;
37+ $ component = $ this ->pluginManager ->find ($ name );
38+ $ pluginDefinition = $ component ->getPluginDefinition ();
39+ $ distThemeName = "{$ pluginDefinition ['provider ' ]}_dist " ;
4240
43- $ prefix = '' ;
44- if (!str_starts_with ($ path , 'core/ ' )) {
45- $ prefix = $ this ->libraryDiscovery ->getLibraryByName ($ distThemeName , $ libraryName )
46- ? "{{ attach_library(' {$ distThemeName }/ {$ libraryName }') }} "
47- : '' ;
41+ // Only components from themes with a '_dist' theme get special treatment.
42+ if ($ pluginDefinition ['extension_type ' ] === ExtensionType::Theme && $ this ->themeHandler ->themeExists ($ distThemeName )) {
43+ $ componentName = $ component ->getDerivativeId ();
44+ $ libraryName = "sdc-- {$ componentName }" ;
45+ $ hasLibrary = $ this ->libraryDiscovery ->getLibraryByName ($ distThemeName , $ libraryName );
46+ if ($ hasLibrary ) {
47+ $ prefix = "{{ attach_library(' {$ distThemeName }/ {$ libraryName }') }} " ;
48+ $ source = new Source ($ prefix . $ source ->getCode (), $ source ->getName (), $ source ->getPath ());
49+ }
4850 }
4951
50- $ code = $ prefix . $ original_code ;
51-
52- return new Source ($ code , $ name , $ path );
52+ return $ source ;
5353 }
5454
5555 /**
0 commit comments