<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Sut\Domain\Compatibility;

class GetCodeGenerationBase
{
    private const SUFFIXES = [
        'ExtensionInterfaceFactory' => 'Extension',
        'Factory' => '',
        'Mapper' => '',
        'Persistor' => '',
        'Converter' => '',
        'ExtensionInterface' => 'Interface',
        'Extension' => 'Interface',
        'Remote' => '',
        '\Proxy' => '',
        '\Interceptor' => '',
        '\Logger' => '',
        '\Repository' => '',
        '\SearchResults' => '',
        '\ProxyDeferred' => '',
    ];

    /**
     * Return the original class for autogenerated class / interface
     *
     * @param string $fqn
     * @return string
     */
    public function execute(string $fqn): string
    {
        foreach (self::SUFFIXES as $suffix => $replacement) {
            if ($this->endsWith($fqn, $suffix)) {
                return $this->execute($this->stringWithReplacedSuffix($fqn, $suffix, $replacement));
            }
        }

        return $fqn;
    }

    /**
     * @param string $string
     * @param string $endString
     * @return bool
     */
    private function endsWith(string $string, string $endString): bool
    {
        $len = strlen($endString);
        if ($len === 0) {
            return true;
        }
        return (substr($string, -$len) === $endString);
    }

    /**
     * @param string $string
     * @param string $suffix
     * @param string $replacement
     * @return string
     */
    private function stringWithReplacedSuffix(string $string, string $suffix, string $replacement): string
    {
        return substr($string, 0, -strlen($suffix)) . $replacement;
    }
}
