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

namespace RtmMailVendor\Dependencies\WordpressModels\DependencyInjection\CliCommandAttributes;

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

class WpCliCommandAttributesCompilerPass implements CompilerPassInterface
{

    public function process(ContainerBuilder $container)
    {
        if (!$container->has(WpCliCommandRegistry::class)) {
            return;
        }

        $definition = $container->findDefinition(WpCliCommandRegistry::class);

        $taggedServices = $container->findTaggedServiceIds('wp_cli.command');

        foreach ($taggedServices as $id => $tags) {
            $commandDefinition = $container->findDefinition($id);
            $baseName = '';

            // get the base command tag
            if ($commandDefinition->hasTag('wp_cli.command_base')) {
                $baseCommand = current($commandDefinition->getTag('wp_cli.command_base'));
                $baseName = $baseCommand['name'];
            }
            $serviceReference = new Reference($id);

            // add the command to the registry
            foreach ($tags as $attributes) {
                $method = $attributes['method'];
                $commandName = $method === '__invoke'
                    ? $baseName
                    : join(' ', array_filter([$baseName, $attributes['name']]));

                $definition->addMethodCall('addCommand', [
                    $commandName,
                    [$serviceReference, $method],
                    $attributes['args']
                ]);
            }
        }
    }
}