haukurh/uri

PHP 库,用于将 URI 解析为其组件,基于 RFC 3986

v1.0.0 2020-02-12 18:30 UTC

This package is auto-updated.

Last update: 2024-09-14 20:50:56 UTC


README

PHP 库,用于将 URI 解析为其组件,基于 RFC 3986

描述

此库的主要思想是将 URI 解析为其组件。它不会以任何形式验证 URI,只会根据 RFC 3986 的一些基本规则解析 URI。

目前它非常类似于 parse_url(),但不会更改 URL 中的无效字符,例如可能成为路径和/或查询一部分的某些 UTF8 字符。

将来可能会实现一些验证和更多功能。

基本用法

提供了一些基本获取器,可以检索所需的组件。这些组件也作为公共属性提供,可以用于读取或写入,但建议使用获取器,因为可能对选定的 URI 组件应用某些业务逻辑,例如将方案转换为小写。

<?php

require_once 'vendor/autoload.php';

use Haukurh\Uri\Uri;

$uri = new Uri('HTTPS://john.doe@www.example.com:8000/some/path?q=term#result1');

echo $uri->getScheme() . PHP_EOL; // https
echo $uri->getAuthority() . PHP_EOL; // john.doe@www.example.com:8000
echo $uri->getPath() . PHP_EOL; // /some/path
echo $uri->getQuery() . PHP_EOL; // q=term
echo $uri->getFragment() . PHP_EOL; // result1

echo $uri . PHP_EOL; // https://john.doe@www.example.com:8000/some/path?q=term#result1

var_dump($uri->toArray());
// array(5) {
//   ["scheme"]=>
//   string(5) "https"
//   ["authority"]=>
//   string(29) "john.doe@www.example.com:8000"
//   ["path"]=>
//   string(10) "/some/path"
//   ["query"]=>
//   string(6) "q=term"
//   ["fragment"]=>
//   string(7) "result1"
// }

如前所述,URI 组件是公共属性,可以用于操作 URI。例如,当处理在网站中找到的相对 URL 时,即 http 和 https 方案或“允许”对 URI 的某些宽松解释的其他方案。

<?php

use Haukurh\Uri\Uri;

$relativeAnchorLink = '/public/css/main.css?v=1.3';

$uri = new Uri($relativeAnchorLink);

echo $uri; // /public/css/main.css?v=1.3

$uri->scheme = 'https';
$uri->authority = 'www.example.com';

echo $uri; // https://www.example.com/public/css/main.css?v=1.3

运行测试

创建了一些测试以确保正确解析组件。

使用 phpunit 运行测试

./vendor/bin/phpunit --bootstrap vendor/autoload.php tests/

待办事项

  • 将权限分解为其子组件。
  • 根据基于 URL 的方案(如 http、https)添加一些功能。
  • 实现针对一些边缘情况的更好的测试。
  • 重构测试