public static function resolve(Uri $baseUri, Uri $targetUri)
    {
        if (!$baseUri->isAbsolute()) {
            throw new InvalidArgumentException('Base uri must be absolute');
        }

        // if the target uri is absolute
        if ($targetUri->isAbsolute()) {
            $path = $targetUri->getPath();

            if (!empty($path)) {
                return $targetUri->withPath($path);
            } else {
                return $targetUri;
            }
        } else {
            $authority = $targetUri->getAuthority();
            $path      = $targetUri->getPath();
            $query     = $targetUri->getQuery();

            if (!empty($authority)) {
                if (!empty($path)) {
                    $path = self::removeDotSegments($path);
                }
            } else {
                if (empty($path)) {
                    if (empty($query)) {
                        $path  = $baseUri->getPath();
                        $query = $baseUri->getQuery();
                    } else {
                        $path = self::merge($baseUri->getPath(), '');
                    }
                } else {
                    if (substr($path, 0, 1) == '/') {
                        $path = self::removeDotSegments($path);
                    } else {
                        $path = self::merge($baseUri->getPath(), $path);
                        $path = self::removeDotSegments($path);
                    }
                }

                $authority = $baseUri->getAuthority();
            }

            return new Uri(
                $baseUri->getScheme(),
                $authority,
                $path,
                $query,
                $targetUri->getFragment()
            );
        }
    }