thephpleague / uri-schemes

Collection of URI Immutable Value Objects
https://uri.thephpleague.com/schemes/
MIT License
216 stars 7 forks source link

`Uri::withPath()` method does not support relative paths #15

Closed cedx closed 5 years ago

cedx commented 5 years ago

Issue summary

PSR-7 and the documentation of the AbstractUri class say about the $path parameter provided to the withPath() method:

The path can either be empty or absolute (starting with a slash) or rootless (not starting with a slash). Implementations MUST support all three syntaxes.

If the path is intended to be domain-relative rather than path relative then it must begin with a slash ("/"). Paths not starting with a slash ("/") are assumed to be relative to some base path known to the application or consumer.

But that's not the case currently: using a relative path triggers an exception.

System informations

Information Description
League\Uri\Schemes version 1.2.1
PHP version 7.2.15 + 7.3.1
OS Platform Ubuntu 19.04 + Windows 10

Standalone code, or other way to reproduce the problem

Http::createFromString('https://belin.io/api/')->withPath('v1');

Expected result

No exception, just a valid URI: https://belin.io/api/v1

Actual result

League\Uri\UriException : Invalid URI: if an authority is present the path must be empty or start with a `/`
nyamsprod commented 5 years ago

@cedx the behaviour you are experiencing is expected. What you are looking for is URL resolution which is not define in PSR-7 but in RFC3986 instead for instance you can accompish this using the Resolve modifier as explain in the documentation website see https://uri.thephpleague.com/manipulations/1.0/middlewares/#middlewares-which-manipulate-several-uri-components.

<?php

use League\Uri\Schemes\Http;
use League\Uri\Modifiers\Resolve;

$baseUri     = Http::createFromString('https://belin.io/api/')
$relativeUri = Http::createFromString("v1");
$modifier    = new Resolve($baseUri);
$newUri = $modifier->process($relativeUri);
echo $newUri; //displays "https://belin.io/api/v1"
cedx commented 5 years ago

Thanks for the clarification and the solution to my problem 😃 The documentation of the withPath method should probably be modified: the observed behavior is different from the description (i.e. we can't use "rootless" paths).