<?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\ContainerBuilder;
use RtmMailVendor\Dependencies\Symfony\Component\DependencyInjection\Definition;
use RtmMailVendor\Dependencies\Symfony\Component\DependencyInjection\Extension\Extension;
use RtmMailVendor\Dependencies\WordpressModels\DependencyInjection\CliCommandAttributes\Attributes\CommandArgument;
use RtmMailVendor\Dependencies\WordpressModels\DependencyInjection\CliCommandAttributes\Attributes\WpCliCommand;

class WpCliCommandAttributesExtension extends Extension
{

    public function load(array $configs, ContainerBuilder $container)
    {
        $container->registerAttributeForAutoconfiguration(WpCliCommand::class, self::tagServices(...));
    }

    public static function tagServices(Definition $definition, WpCliCommand $command, \ReflectionMethod|\ReflectionClass $reflection): void
    {
        if ($reflection instanceof \ReflectionClass) {
            // add the base command tag
            $definition->addTag('wp_cli.command_base', [
                'name' => $command->name,
            ]);

            if (!$reflection->hasMethod('__invoke')) {
                return;
            }

            $reflection = $reflection->getMethod('__invoke');
        }


        $synopsis = [];

        // get the argument attributes
        foreach ($reflection->getParameters() as $parameter) {
            $attributes = $parameter->getAttributes(CommandArgument::class);
            foreach ($attributes as $attribute) {
                /** @var CommandArgument $argument */
                $argument = $attribute->newInstance();

                // add the argument to the definition
                $synopsis[] = [
                    'type' => $argument->type,
                    'name' => $argument->name,
                    'description' => $argument->description,
                    'default' => $argument->default,
                    'optional' => $argument->optional,
                    'repeating' => $argument->repeating,
                    'options' => $argument->options,
                ];
            }
        }


        $definition->addTag('wp_cli.command', [
            'method' => $reflection->getName(),
            'name' => $command->name,
            'args' => [
                'longdesc' => $command->description,
                'shortdesc' => $command->shortDescription,
                'when' => $command->when,
                'synopsis' => $synopsis,
            ]
        ]);
    }

}