|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Softspring\CmsBundle\DependencyInjection\Compiler; |
| 4 | + |
| 5 | +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
| 6 | +use Symfony\Component\DependencyInjection\ContainerBuilder; |
| 7 | + |
| 8 | +/** |
| 9 | + * Sorts twig namespaces to manage priority: |
| 10 | + * - higher priority for project templates |
| 11 | + * - then bundles&plugins overrides |
| 12 | + * - less priority main bundles templates |
| 13 | + */ |
| 14 | +class SortTwigNamespaceTemplatesPass implements CompilerPassInterface |
| 15 | +{ |
| 16 | + public function process(ContainerBuilder $container): void |
| 17 | + { |
| 18 | + $this->processNamespace($container, 'SfsCms', 'cms-bundle'); |
| 19 | + $this->processNamespace($container, 'SfsMedia', 'media-bundle'); |
| 20 | + } |
| 21 | + |
| 22 | + private function processNamespace(ContainerBuilder $container, string $namespace, string $bundleDir): void |
| 23 | + { |
| 24 | + $projectDir = $container->getParameter('kernel.project_dir'); |
| 25 | + |
| 26 | + $twigFilesystemLoaderDefinition = $container->getDefinition('twig.loader.native_filesystem'); |
| 27 | + |
| 28 | + // get namespace paths and remove addPath |
| 29 | + $methodCalls = $twigFilesystemLoaderDefinition->getMethodCalls(); |
| 30 | + $sfsNamespaceCalls = $this->getNamespacePaths($namespace, $methodCalls); |
| 31 | + $twigFilesystemLoaderDefinition->setMethodCalls(array_values($methodCalls)); |
| 32 | + |
| 33 | + // sort paths |
| 34 | + uasort($sfsNamespaceCalls, function (string $a, string $b) use ($namespace, $projectDir, $bundleDir): int { |
| 35 | + return $this->pathPriority($a, $namespace, $projectDir, $bundleDir) <=> $this->pathPriority($b, $namespace, $projectDir, $bundleDir); |
| 36 | + }); |
| 37 | + |
| 38 | + // add paths |
| 39 | + foreach ($sfsNamespaceCalls as $path) { |
| 40 | + $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$path, $namespace]); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + private function pathPriority(string $path, string $namespace, string $projectDir, string $bundleDir): int |
| 45 | + { |
| 46 | + if ($path === "$projectDir/templates/bundles/{$namespace}Bundle") { |
| 47 | + return 0; |
| 48 | + } |
| 49 | + |
| 50 | + $bundlePath = realpath("$projectDir/vendor/softspring/$bundleDir"); |
| 51 | + if ($bundlePath && str_starts_with($path, $bundlePath)) { |
| 52 | + return 2; |
| 53 | + } |
| 54 | + |
| 55 | + return 1; // resto de bundles |
| 56 | + } |
| 57 | + |
| 58 | + private function getNamespacePaths(string $namespace, array &$methodCalls): array |
| 59 | + { |
| 60 | + $paths = []; |
| 61 | + |
| 62 | + foreach ($methodCalls as $i => $call) { |
| 63 | + if ('addPath' === $call[0] && (isset($call[1][1]) && $call[1][1] === $namespace)) { |
| 64 | + unset($methodCalls[$i]); |
| 65 | + $paths[] = $call[1][0]; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return $paths; |
| 70 | + } |
| 71 | +} |
0 commit comments