1+ <?php
2+
3+ namespace Prokl \BitrixOrdinaryToolsBundle \DependencyInjection \CompilerPass ;
4+
5+ use Symfony \Component \Config \Resource \FileExistenceResource ;
6+ use Symfony \Component \DependencyInjection \Compiler \CompilerPassInterface ;
7+ use Symfony \Component \DependencyInjection \ContainerBuilder ;
8+
9+ /**
10+ * Class TwigBundlesViewCompilerPass
11+ * @package Prokl\BitrixOrdinaryToolsBundle\DependencyInjection\CompilerPass
12+ *
13+ * @since 12.08.2021
14+ */
15+ final class TwigBundlesViewCompilerPass implements CompilerPassInterface
16+ {
17+ /**
18+ * {@inheritdoc}
19+ */
20+ public function process (ContainerBuilder $ container )
21+ {
22+ if (!$ container ->hasDefinition ('twig.loader ' )) {
23+ return ;
24+ }
25+
26+ $ twigFilesystemLoaderDefinition = $ container ->getDefinition ('twig.loader ' );
27+
28+ $ bundleHierarchy = $ this ->getBundleTemplatePaths ($ container , [
29+ 'default_path ' => ''
30+ ]);
31+
32+ foreach ($ bundleHierarchy as $ name => $ paths ) {
33+ $ namespace = $ this ->normalizeBundleName ($ name );
34+ foreach ($ paths as $ path ) {
35+ $ twigFilesystemLoaderDefinition ->addMethodCall ('addPath ' , [$ path , $ namespace ]);
36+ }
37+ }
38+ }
39+
40+ /**
41+ * @param ContainerBuilder $container
42+ * @param array $config
43+ *
44+ * @return array
45+ */
46+ private function getBundleTemplatePaths (ContainerBuilder $ container , array $ config ): array
47+ {
48+ $ bundleHierarchy = [];
49+ foreach ($ container ->getParameter ('kernel.bundles_metadata ' ) as $ name => $ bundle ) {
50+ $ defaultOverrideBundlePath = $ container ->getParameterBag ()->resolveValue ($ config ['default_path ' ]).'/bundles/ ' .$ name ;
51+
52+ if (file_exists ($ defaultOverrideBundlePath )) {
53+ $ bundleHierarchy [$ name ][] = $ defaultOverrideBundlePath ;
54+ }
55+ $ container ->addResource (new FileExistenceResource ($ defaultOverrideBundlePath ));
56+
57+ if (file_exists ($ dir = $ bundle ['path ' ].'/Resources/views ' ) || file_exists ($ dir = $ bundle ['path ' ].'/templates ' )) {
58+ $ bundleHierarchy [$ name ][] = $ dir ;
59+ }
60+
61+ $ container ->addResource (new FileExistenceResource ($ dir ));
62+ }
63+
64+ return $ bundleHierarchy ;
65+ }
66+
67+ /**
68+ * @param string $name Класс бандла.
69+ *
70+ * @return string
71+ */
72+ private function normalizeBundleName (string $ name ): string
73+ {
74+ if (str_ends_with ($ name , 'Bundle ' )) {
75+ $ name = substr ($ name , 0 , -6 );
76+ }
77+
78+ return $ name ;
79+ }
80+ }
0 commit comments