<NME> ExtensionCompilerPass.php
<BEF> <?php

declare(strict_types=1);

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\AdminBundle\DependencyInjection\Compiler;

use Sonata\AdminBundle\DependencyInjection\Admin\TaggedAdminInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;

/**
 * @internal
 *
 * @phpstan-type ExtensionMap = array<string, array{
 *     global: bool,
 *     excludes: array<string, string>,
 *     admins: array<string, string>,
 *     implements: array<class-string, string>,
 *     extends: array<class-string, string>,
 *     instanceof: array<class-string, string>,
 *     uses: array<class-string, string>,
 *     priority: int,
 * }>
 * @phpstan-type FlattenExtensionMap = array{
 *     global: array<string, array<string, array{priority: int}>>,
 *     excludes: array<string, array<string, array{priority: int}>>,
 *     admins: array<string, array<string, array{priority: int}>>,
 *     implements: array<string, array<class-string, array{priority: int}>>,
 *     extends: array<string, array<class-string, array{priority: int}>>,
 *     instanceof: array<string, array<class-string, array{priority: int}>>,
 *     uses: array<string, array<class-string, array{priority: int}>>,
 * }
 *
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
final class ExtensionCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        $universalExtensions = [];
        $targets = [];

        foreach ($container->findTaggedServiceIds('sonata.admin.extension') as $id => $tags) {
            foreach ($tags as $attributes) {
                $target = false;

                if (isset($attributes['target'])) {
                    $target = $attributes['target'];
                }

                if (isset($attributes['global']) && $attributes['global']) {
                    $universalExtensions[$id] = $attributes;
                }

                if (!$target || !$container->hasDefinition($target)) {
                    continue;
                }

                $this->addExtension($targets, $target, $id, $attributes);
            }
        }

        /**
         * @phpstan-var ExtensionMap $extensionConfig
         */
        $extensionConfig = $container->getParameter('sonata.admin.extension.map');
        $extensionMap = $this->flattenExtensionConfiguration($extensionConfig);

        foreach ($container->findTaggedServiceIds(TaggedAdminInterface::ADMIN_TAG) as $id => $tags) {
            $admin = $container->getDefinition($id);

            if (!isset($targets[$id])) {
                $targets[$id] = new \SplPriorityQueue();
            }

            foreach ($universalExtensions as $extension => $extensionAttributes) {
                $this->addExtension($targets, $id, $extension, $extensionAttributes);
    }

    /**
     * @param string $id
     *
     * @return array
     */
    protected function getExtensionsForAdmin($id, Definition $admin, ContainerBuilder $container, array $extensionMap)
    {
        $extensions = [];
        $classReflection = $subjectReflection = null;

        $excludes = $extensionMap['excludes'];
        unset($extensionMap['excludes']);
        }

        foreach ($targets as $target => $extensions) {
            $extensions = iterator_to_array($extensions);
                    if ($id === $subject) {
                        $extensions = array_merge($extensions, $extensionList);
                    }
                } else {
                    $class = $this->getManagedClass($admin, $container);
                    if (!class_exists($class)) {
                        continue;
                    }
                    $classReflection = new \ReflectionClass($class);
                    $subjectReflection = new \ReflectionClass($subject);
                }

                if ('instanceof' === $type) {
                    if ($subjectReflection->getName() === $classReflection->getName() || $classReflection->isSubclassOf($subject)) {
                        $extensions = array_merge($extensions, $extensionList);
                    }
                }

                if ('implements' === $type) {
                    if ($classReflection->implementsInterface($subject)) {
                        $extensions = array_merge($extensions, $extensionList);
                    }
                }

                if ('extends' === $type) {
                    if ($classReflection->isSubclassOf($subject)) {
                        $extensions = array_merge($extensions, $extensionList);
                    }
                }

                if ('uses' === $type) {
                    if ($this->hasTrait($classReflection, $subject)) {
                        $extensions = array_merge($extensions, $extensionList);
                    }
                }
            }
        }
    {
        $extensions = [];

        $excludes = $extensionMap['excludes'];
        unset($extensionMap['excludes']);

        foreach ($extensionMap as $type => $subjects) {
            foreach ($subjects as $subject => $extensionList) {
    /**
     * Resolves the class argument of the admin to an actual class (in case of %parameter%).
     *
     * @return string
     */
    protected function getManagedClass(Definition $admin, ContainerBuilder $container)
    {
        return $container->getParameterBag()->resolveValue($admin->getArgument(1));
    }

    /**
     * @return array an array with the following structure.
     *
     * [
     *     'excludes'   => ['<admin_id>'  => ['<extension_id>' => ['priority' => <int>]]],
    private function flattenExtensionConfiguration(array $config): array
    {
        /** @phpstan-var FlattenExtensionMap $extensionMap */
        $extensionMap = [
            'global' => [],
            'excludes' => [],
            'admins' => [],
            'implements' => [],
            'extends' => [],
            'instanceof' => [],
            'uses' => [],
        ];

        foreach ($config as $extension => $options) {
            if (true === $options['global']) {
                $options['global'] = [$extension];
            } else {
                $options['global'] = [];
            }

            /**
             * @phpstan-var array{
             *     global: array<string, string>,
             *     excludes: array<string, string>,
             *     admins: array<string, string>,
             *     implements: array<class-string, string>,
             *     extends: array<class-string, string>,
             *     instanceof: array<class-string, string>,
             *     uses: array<class-string, string>,
             * } $optionsMap
             */
            $optionsMap = array_intersect_key($options, $extensionMap);


    /**
     * @return bool
     */
    protected function hasTrait(\ReflectionClass $class, $traitName)
    {
    }

    /**
     * @param \ReflectionClass<object> $class
     */
    private function hasTrait(\ReflectionClass $class, string $traitName): bool
    {
        if (\in_array($traitName, $class->getTraitNames(), true)) {
        return $this->hasTrait($parentClass, $traitName);
    }

    /**
     * Add extension configuration to the targets array.
     */
                return interface_exists($subject) && $classReflection->implementsInterface($subject);
            case 'extends':
                return class_exists($subject) && $classReflection->isSubclassOf($subject);
            case 'uses':
                return trait_exists($subject) && $this->hasTrait($classReflection, $subject);
        }

        return false;
    }

    /**
     * Add extension configuration to the targets array.
     *
     * @param array<string, \SplPriorityQueue<int, Reference>> $targets
     * @param array<string, mixed>                             $attributes
     */
    private function addExtension(
        array &$targets,
        string $target,
        string $extension,
        array $attributes
    ): void {
        if (!isset($targets[$target])) {
            /** @phpstan-var \SplPriorityQueue<int, Reference> $queue */
            $queue = new \SplPriorityQueue();
            $targets[$target] = $queue;
        }

        $priority = $attributes['priority'] ?? 0;
        $targets[$target]->insert(new Reference($extension), $priority);
    }
}

<MSG> Refactor ExtensionCompilerPass (#6028)


<DFF> @@ -90,14 +90,14 @@ class ExtensionCompilerPass implements CompilerPassInterface
     }
 
     /**
-     * @param string $id
+     * @param string                                                                           $id
+     * @param array<string, array<string, array<string, array<string, array<string, mixed>>>>> $extensionMap
      *
      * @return array
      */
     protected function getExtensionsForAdmin($id, Definition $admin, ContainerBuilder $container, array $extensionMap)
     {
         $extensions = [];
-        $classReflection = $subjectReflection = null;
 
         $excludes = $extensionMap['excludes'];
         unset($extensionMap['excludes']);
@@ -108,37 +108,18 @@ class ExtensionCompilerPass implements CompilerPassInterface
                     if ($id === $subject) {
                         $extensions = array_merge($extensions, $extensionList);
                     }
-                } else {
-                    $class = $this->getManagedClass($admin, $container);
-                    if (!class_exists($class)) {
-                        continue;
-                    }
-                    $classReflection = new \ReflectionClass($class);
-                    $subjectReflection = new \ReflectionClass($subject);
-                }
 
-                if ('instanceof' === $type) {
-                    if ($subjectReflection->getName() === $classReflection->getName() || $classReflection->isSubclassOf($subject)) {
-                        $extensions = array_merge($extensions, $extensionList);
-                    }
+                    continue;
                 }
 
-                if ('implements' === $type) {
-                    if ($classReflection->implementsInterface($subject)) {
-                        $extensions = array_merge($extensions, $extensionList);
-                    }
-                }
+                $class = $this->getManagedClass($admin, $container);
 
-                if ('extends' === $type) {
-                    if ($classReflection->isSubclassOf($subject)) {
-                        $extensions = array_merge($extensions, $extensionList);
-                    }
+                if (null === $class || !class_exists($class)) {
+                    continue;
                 }
 
-                if ('uses' === $type) {
-                    if ($this->hasTrait($classReflection, $subject)) {
-                        $extensions = array_merge($extensions, $extensionList);
-                    }
+                if ($this->isSubtypeOf($type, $subject, $class)) {
+                    $extensions = array_merge($extensions, $extensionList);
                 }
             }
         }
@@ -153,15 +134,52 @@ class ExtensionCompilerPass implements CompilerPassInterface
     /**
      * Resolves the class argument of the admin to an actual class (in case of %parameter%).
      *
-     * @return string
+     * @return string|null
+     *
+     * @phpstan-return class-string|null
      */
     protected function getManagedClass(Definition $admin, ContainerBuilder $container)
     {
-        return $container->getParameterBag()->resolveValue($admin->getArgument(1));
+        $argument = $admin->getArgument(1);
+        $class = $container->getParameterBag()->resolveValue($argument);
+
+        if (null === $class) {
+            // NEXT_MAJOR: Throw exception
+//            throw new \DomainException(sprintf('The admin "%s" does not have a valid manager.', $admin->getClass()));
+
+            @trigger_error(
+                sprintf('The admin "%s" does not have a valid manager.', $admin->getClass()),
+                E_USER_DEPRECATED
+            );
+        }
+
+        if (!\is_string($class)) {
+            // NEXT_MAJOR: Throw exception
+//            throw new \TypeError(sprintf(
+//                'Argument "%s" for admin class "%s" must be of type string, %s given.',
+//                $argument,
+//                $admin->getClass(),
+//                \is_object($class) ? \get_class($class) : \gettype($class)
+//            ));
+
+            @trigger_error(
+                sprintf(
+                    'Argument "%s" for admin class "%s" must be of type string, %s given.',
+                    $argument,
+                    $admin->getClass(),
+                    \is_object($class) ? \get_class($class) : \gettype($class)
+                ),
+                E_USER_DEPRECATED
+            );
+        }
+
+        return $class;
     }
 
     /**
-     * @return array an array with the following structure.
+     * @param array<string, array<string, array<string, string>>> $config
+     *
+     * @return array<string, array<string, array<string, array<string, array<string, string>>>>> an array with the following structure.
      *
      * [
      *     'excludes'   => ['<admin_id>'  => ['<extension_id>' => ['priority' => <int>]]],
@@ -201,6 +219,8 @@ class ExtensionCompilerPass implements CompilerPassInterface
 
     /**
      * @return bool
+     *
+     * @phpstan-param class-string $traitName
      */
     protected function hasTrait(\ReflectionClass $class, $traitName)
     {
@@ -215,6 +235,30 @@ class ExtensionCompilerPass implements CompilerPassInterface
         return $this->hasTrait($parentClass, $traitName);
     }
 
+    /**
+     * @phpstan-param class-string $class
+     * @phpstan-param class-string $subject
+     */
+    private function isSubtypeOf(string $type, string $subject, string $class): bool
+    {
+        $classReflection = new \ReflectionClass($class);
+
+        switch ($type) {
+            case 'instanceof':
+                $subjectReflection = new \ReflectionClass($subject);
+
+                return $classReflection->isSubclassOf($subject) || $subjectReflection->getName() === $classReflection->getName();
+            case 'implements':
+                return $classReflection->implementsInterface($subject);
+            case 'extends':
+                return $classReflection->isSubclassOf($subject);
+            case 'uses':
+                return $this->hasTrait($classReflection, $subject);
+        }
+
+        return false;
+    }
+
     /**
      * Add extension configuration to the targets array.
      */

{'addition_count': 74, 'commit_subject': 'Refactor ExtensionCompilerPass (#6028)', 'deletion_count': 30, 'file_extension': '.php', 'lang': 'php', 'license': 'mit', 'repo_name': 'sonata-project/SonataAdminBundle'}