<?php

declare(strict_types=1);

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

namespace TYPO3\CMS\Frontend\Typolink;

use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Core\Resource\Folder;

/**
 * Builds a TypoLink to a folder or file
 */
class FileOrFolderLinkBuilder extends AbstractTypolinkBuilder implements TypolinkBuilderInterface
{
    public function buildLink(
        array $linkDetails,
        array $configuration,
        ServerRequestInterface $request,
        string $linkText = '',
    ): LinkResultInterface {
        $target = $linkDetails['target'] ?? '';
        $fileOrFolderObject = ($linkDetails['file'] ?? false) ?: ($linkDetails['folder'] ?? null);
        // check if the file exists or if a / is contained (same check as in detectLinkType)
        if (!($fileOrFolderObject instanceof FileInterface) && !($fileOrFolderObject instanceof Folder)) {
            throw new UnableToLinkException(
                'File "' . $linkDetails['typoLinkParameter'] . '" did not exist, so "' . $linkText . '" was not linked.',
                1490989449,
                null,
                $linkText
            );
        }
        $linkLocation = $fileOrFolderObject->getPublicUrl();
        if ($linkLocation === null) {
            // set the linkLocation to an empty string if null,
            // so it does not collide with the various string functions
            $linkLocation = '';
        }
        // Setting title if blank value to link
        $linkText = $this->encodeFallbackLinkTextIfLinkTextIsEmpty($linkText, rawurldecode($linkLocation));
        $url = $linkLocation;
        if (!empty($linkDetails['fragment'])) {
            $url .= '#' . $linkDetails['fragment'];
        }
        return (new LinkResult($linkDetails['type'], $this->forceAbsoluteUrl($url, $configuration, $request)))
            ->withLinkConfiguration($configuration)
            ->withTarget($target ?: $this->resolveTargetAttribute($configuration, 'fileTarget', $request->getAttribute('currentContentObject')))
            ->withLinkText($linkText);
    }
}
