<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\DependencyInjection\Compiler;

use Ferienpass\CoreBundle\Filesystem\PublicUri\StoragePublicUriProvider;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class ConfigureFilesystemPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        $publicUriProvider = $container->getDefinition(StoragePublicUriProvider::class);

        $this->introduceAdapters($container, $publicUriProvider);
    }

    private function introduceAdapters(ContainerBuilder $container, Definition $fileProvider): void
    {
        foreach (['contao.filesystem.adapter.media', 'contao.filesystem.adapter.attachments', 'contao.filesystem.adapter.logos', 'contao.filesystem.adapter.export'] as $adapterId) {
            // has(), not hasDefinition(): since Contao 6 these ids are ALIASES onto the
            // adapter definitions the Flysystem extension builds, and hasDefinition()
            // does not see an alias. Checking for a definition silently registered
            // nothing, which left every storage without a public URI.
            if (!$container->has($adapterId)) {
                continue;
            }

            $fileProvider->addMethodCall('registerAdapter', [new Reference($adapterId), str_replace('contao.filesystem.adapter.', '', $adapterId)]);
        }
    }
}
