<?php

namespace App\Helpers;

use League\Uri\Http as UriHttp;
use League\Uri\UriResolver;

/**
 * Helper to work with urls.
 */
class Url
{
    /**
     * Convert specified relative URL to an absolute URL using specified base
     * URL.
     *
     * @param mixed $baseUrl
     * @param mixed $relativeUrl
     *
     * @return string
     */
    public static function makeUrlAbsolute($baseUrl, $relativeUrl)
    {
        if (\is_string($baseUrl)) {
            try {
                $baseUrl = UriHttp::createFromString($baseUrl);
            } catch(Exception $e) {
                return $baseUrl;
            }
        }

        if (\is_string($relativeUrl)) {
            try {
                $relativeUrl = UriHttp::createFromString($relativeUrl);
            } catch(Exception $e) {
                $relativeUrl = '/';
            }
        }

        try {
            $newUri = UriResolver::resolve($relativeUrl, $baseUrl);
        } catch(Exception $e) {
            return $baseUrl;
        }

        return (string) $newUri;
    }
}
