bentools/uri-factory

PSR-7 URI factory

2.3 2023-06-21 14:18 UTC

This package is auto-updated.

Last update: 2024-04-21 15:59:45 UTC


README

Latest Stable Version License Build Status Coverage Status Quality Score Total Downloads

Uri Factory

A library / framework agnostic PSR-7 UriInterface factory.

There are several PSR-7 libraries on packagist but each one has its own factory for creating an UriInterface object from a string.

bentools/uri-factory has no explicit dependency and automatically picks up your favorite library for creating UriInterface instances.

Supported libraries so far:

  • guzzlehttp/psr7
  • league/uri
  • nyholm/psr7
  • ringcentral/psr7

Usage

On any URL string:

use function BenTools\UriFactory\Helper\uri;
$uri = uri('http://www.example.net'); // Will convert to a Psr\Http\Message\UriInterface instance

On current location:

use function BenTools\UriFactory\Helper\current_location;
$uri = current_location(); // Will convert the current location to a Psr\Http\Message\UriInterface instance

You can specify which library to use, by using the corresponding adapter:

use BenTools\UriFactory\Adapter\GuzzleAdapter;
use BenTools\UriFactory\Adapter\LeagueUriAdapter;
use function BenTools\UriFactory\Helper\current_location;
use function BenTools\UriFactory\Helper\uri;

$uri = uri('http://www.example.net', GuzzleAdapter::factory());
$uri = uri('http://www.example.net', LeagueUriAdapter::factory());

$uri = current_location(GuzzleAdapter::factory());
$uri = current_location(LeagueUriAdapter::factory());

Canonicalizer

This library ships with an URL canonicalizer.

It is not a perfect one since your PSR-7 library may behave differently regarding special chars, but it should work most of the time.

The canonicalize() function accepts any PSR-7 UriInterface object and will return a canonicalized one.

require_once __DIR__ . '/vendor/autoload.php';

use function BenTools\UriFactory\Helper\canonicalize;
use function BenTools\UriFactory\Helper\uri;

$url = 'http://example.org../foo/../bar/?#baz';
echo canonicalize(uri($url)); // http://example.org/bar/

Installation

PHP 8.0+ is required.

composer require bentools/uri-factory

Tests

./vendor/bin/phpunit

Contribute

If you want bentools/uri-factory to support more PSR-7 libraries, feel free to submit a PR.

License

MIT.