<?php
/**
 * @license proprietary
 *
 * Modified by RTM Business on 16-December-2024 using {@see https://github.com/BrianHenryIE/strauss}.
 */

namespace RtmMailVendor\Dependencies\WordpressModels\DependencyInjection\RestRouteAttributes;

use RtmMailVendor\Dependencies\Symfony\Component\DependencyInjection\ContainerBuilder;
use RtmMailVendor\Dependencies\Symfony\Component\DependencyInjection\Reference;

class RestRouteCompilerPass implements \RtmMailVendor\Dependencies\Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->has(RestRouteRegistry::class)) {
            return;
        }
        $registry = $container->getDefinition(RestRouteRegistry::class);

        $controllerScopes = $container->findTaggedServiceIds('wp_rest_controller_scope');

        foreach ($controllerScopes as $id => $tags) {
            foreach ($tags as $tag) {
                $registry->addMethodCall('addScope', [...$tag]);
            }
        }

        $services = $container->findTaggedServiceIds('wp_rest_controller');

        foreach ($services as $id => $tags) {
            foreach ($tags as $tag) {
                // unset the method
                $method = $tag['$method'];
                unset($tag['$method']);

                // ensure the scope is to the current service class
                if ($tag['$scope'] !== $id && class_exists($id)) {
                    $tag['$scope'] = $id;
                }

                $registry->addMethodCall('addRoute', [
                    '$callable' => [new Reference($id), $method],
                    ...$tag
                ]);
            }
        }
    }
}