thinktomorrow / url
一个简单的PHP URL实用类。
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: ^9.5
README
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安装
$ composer require thinktomorrow/url
用法
创建Url实例
通过调用静态fromString
方法并传入您的URL字符串来创建新的URL实例。
\Thinktomorrow\Url\Url::fromString('https://example.com');
如果URL字符串格式不正确,将抛出InvalidUrl
异常。此验证基于原生parse_url
认为的格式不正确的URL字符串。
URL的各个部分
通过Url实例,您可以访问URL字符串的所有不同部分。您可以检索以下部分
// 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(); // foobar
修改URL字符串
确保URL的安全性
您可以使用secure()
方法确保URL的安全性。
Url::fromString('example.com')->secure()->get(); // 'https://example.com'
您可以使用nonSecure
方法强制使用非安全方案。
Url::fromString('example.com')->nonSecure()->get(); // 'http://example.com' Url::fromString('https://example.com')->nonSecure()->get(); // 'http://example.com'
更改URL根目录
如果您需要更改URL根目录,可以使用setCustomRoot
方法。该方法期望一个\Thinktomorrow\Url\Root
对象作为参数。
Url::fromString('http://example.com/foobar') ->setCustomRoot(Root::fromString('https://newroot.be')) ->get(); // 'https://newroot.be/foobar'
本地化URL
如果您使用URL路径段进行本地化,可以使用localize
方法注入区域段
Url::fromString('http://example.com/foobar') ->localize('en') ->get(); // 'http://example.com/en/foobar'
localize
方法还接受第二个参数以列出所有可用区域。如果传递的URL包含这些区域之一,则现有区域将被新区域替换。
Url::fromString('http://example.com/en/foobar') ->localize('fr', ['en','fr']) ->get(); // 'http://example.com/fr/foobar'
如果您将null
作为区域参数传递,则任何区域段都将被删除。
Url::fromString('http://example.com/en/foobar') ->localize(null, ['en','fr']) ->get(); // 'http://example.com/foobar'
测试
$ vendor/bin/phpunit
安全性
如果您发现任何与安全相关的问题,请通过电子邮件ben@thinktomorrow.be联系,而不是使用问题跟踪器。
致谢
- Ben Cavens ben@thinktomorrow.be
- Philippe Damen philippe@thinktomorrow.be
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。