A URL helper class to easily extract certain parts of the url. It is basically a wrapper around the native parse_url function.
Currently, parse_url has no solid support for parsing uri strings. This package aims to
provide that support.
This small package is framework agnostic and has no dependencies.
$ composer require thinktomorrow/urlCreate a new url instance by calling the static fromString method with your url string.
\Thinktomorrow\Url\Url::fromString('https://example.com');In case of a malformed url string, an InvalidUrl exception will be thrown. This
validation is based on what the native parse_url considers a malformed url string.
Via the Url instance, you have access to all the different parts of the url string. You can retrieve the following parts:
// scheme
\Thinktomorrow\Url\Url::fromString('https://example.com')->getScheme(); // https
// host
\Thinktomorrow\Url\Url::fromString('https://example.com')->getHost(); // example.com
// port
\Thinktomorrow\Url\Url::fromString('https://example.com:9000')->getPort(); // 9000
// path
\Thinktomorrow\Url\Url::fromString('https://example.com/foo/bar')->getPath(); // foo/bar
// query
\Thinktomorrow\Url\Url::fromString('https://example.com?foo=bar')->getQuery(); // foo=bar
// hash
\Thinktomorrow\Url\Url::fromString('https://example.com#foobar')->getHash(); // foobarYou can secure an url with the secure() method.
Url::fromString('example.com')->secure()->get(); // 'https://example.com'You can force a non-secure scheme with the nonSecure method.
Url::fromString('example.com')->nonSecure()->get(); // 'http://example.com'
Url::fromString('https://example.com')->nonSecure()->get(); // 'http://example.com'In the case you need to change the url root, you can use the setCustomRoot method.
This expects a \Thinktomorrow\Url\Root object as argument.
Url::fromString('http://example.com/foobar')
->setCustomRoot(Root::fromString('https://newroot.be'))
->get(); // 'https://newroot.be/foobar'In case you use the url path segment for localization purposes, you can inject the locale segment with the localize method
Url::fromString('http://example.com/foobar')
->localize('en')
->get(); // 'http://example.com/en/foobar'The localize method also accepts a second parameter to enlist all available locales. In the case that passed url
contains any of these locales, the existing locale will be replaced by the new locale.
Url::fromString('http://example.com/en/foobar')
->localize('fr', ['en','fr'])
->get(); // 'http://example.com/fr/foobar'If you pass null as the locale parameter, any locale segment will be removed.
Url::fromString('http://example.com/en/foobar')
->localize(null, ['en','fr'])
->get(); // 'http://example.com/foobar'$ vendor/bin/phpunitIf you discover any security related issues, please email ben@thinktomorrow.be instead of using the issue tracker.
- Ben Cavens ben@thinktomorrow.be
- Philippe Damen philippe@thinktomorrow.be
The MIT License (MIT). Please see License File for more information.