Compare commits
2
Commits
laysite1.3
...
backup
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0e860f330 | ||
|
|
2aa9e5097f |
@@ -0,0 +1,14 @@
|
|||||||
|
# 站点对外地址。上线时改为实际域名。
|
||||||
|
LAYSITE_SITE_URL=https://laysense.cn
|
||||||
|
# HTTPS 部署时取消注释。
|
||||||
|
# LAYSITE_SECURE_COOKIES=1
|
||||||
|
|
||||||
|
# 有需要时覆盖默认值。相对路径以项目根目录为基准。
|
||||||
|
LAYSITE_LISTEN=http://127.0.0.1:8990
|
||||||
|
# LAYSITE_WORKERS=2
|
||||||
|
# LAYSITE_DB=storage/laysite.sqlite
|
||||||
|
# LAYSITE_MEDIA_DIR=storage/media
|
||||||
|
# LAYSITE_TRUSTED_PROXIES=127.0.0.1,::1
|
||||||
|
|
||||||
|
# 启用 MCP 时填写至少 32 字符的令牌。
|
||||||
|
# LAYSITE_MCP_TOKEN=
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
/vendor/
|
|
||||||
/runtime/
|
|
||||||
/storage/*
|
|
||||||
!/storage/.gitignore
|
|
||||||
/.env
|
|
||||||
/.taste-skill/
|
|
||||||
/shots/
|
|
||||||
BIN
Binary file not shown.
+67
@@ -0,0 +1,67 @@
|
|||||||
|
<?php
|
||||||
|
return array (
|
||||||
|
'/www/laysense.cn/app/Controller/MediaController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\MediaController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
'/www/laysense.cn/app/Controller/StudioController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\StudioController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
'/www/laysense.cn/app/Controller/AdminController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\AdminController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
'/www/laysense.cn/app/Controller/DesignController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\DesignController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
'/www/laysense.cn/app/Controller/SiteController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\SiteController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
'/www/laysense.cn/app/Controller/BackupController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\BackupController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
'/www/laysense.cn/app/Controller/McpController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\McpController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
'/www/laysense.cn/app/Controller/AccountController.php' =>
|
||||||
|
array (
|
||||||
|
'mtime' => 1795624085,
|
||||||
|
'hasAttributes' => false,
|
||||||
|
'class' => 'App\\Controller\\AccountController',
|
||||||
|
'type' => 'class',
|
||||||
|
'psr4' => true,
|
||||||
|
),
|
||||||
|
);
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[2026-11-26T00:30:57.577992+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(931): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(167): Webman\App::findRoute() #7 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #8 [internal function]: Workerman\Connection\TcpConnection->baseRead() #9 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #13 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #14 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #15 /www/laysense.cn/start.php(15): support\App::run() #16 {main} [] []
|
||||||
|
[2026-11-26T00:30:58.458939+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] []
|
||||||
|
[2026-11-26T00:31:00.354322+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] []
|
||||||
|
[2026-11-26T00:32:05.591458+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(735): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] []
|
||||||
|
[2026-11-26T00:33:08.485804+08:00] default.ERROR: 90.96.186.30 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] []
|
||||||
|
[2026-11-26T00:35:58.780386+08:00] default.ERROR: 90.96.186.33 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] []
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
2026-11-26 00:36:21 pid:4048938 Workerman[start.php] received signal SIGINT
|
||||||
|
2026-11-26 00:36:21 pid:4048938 Workerman[start.php] stopping
|
||||||
|
2026-11-26 00:36:21 pid:4048938 Workerman[start.php] has been stopped
|
||||||
|
2026-11-26 00:36:21 pid:4055911 Workerman[start.php] start in DAEMON mode
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
a:4:{s:8:"admin_id";i:1;s:12:"auth_version";s:64:"3e9123d0802768a210b9b7abb63b0fa3ec25073d7dcc13ba3fde95eaf0dbdc2e";s:11:"admin_since";i:1795626237;s:4:"csrf";s:64:"f1fbaee11f2744c721526d053a32609a6a0ea87ecef7f4c775dc0696b58e38c4";}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
a:1:{s:4:"csrf";s:64:"637ad0173f728beb95e405ee6c319895caa3e2710bebe052faba8c007ff9d84b";}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
a:1:{s:4:"csrf";s:64:"b6fec2c3e8890229d727f5d13be3cd3203af1bb7bd4cd85e2ec36b4a98e164ba";}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
a:1:{s:4:"csrf";s:64:"1193d7e41d462adc94a1f107c1ef17575624fce84d8163eb2518469826596725";}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
a:4:{s:8:"admin_id";i:1;s:12:"auth_version";s:64:"3e9123d0802768a210b9b7abb63b0fa3ec25073d7dcc13ba3fde95eaf0dbdc2e";s:11:"admin_since";i:1795624593;s:4:"csrf";s:64:"f62286ba57ef213e9288b43e3e2869d5eb8268e0486b95d99296653089f9b1b2";}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
4055919
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 82 KiB |
+575
@@ -0,0 +1,575 @@
|
|||||||
|
#!/usr/bin/env php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
final class LaySiteUpdater
|
||||||
|
{
|
||||||
|
private const UPDATESCRIPT_VERSION = '1.0.0';
|
||||||
|
private const HOST = 'https://git.laysense.com';
|
||||||
|
private const PROJECT = '/laysense/laysite';
|
||||||
|
private const MAP_PATH = self::PROJECT . '/raw/branch/main/updatescript_map.json';
|
||||||
|
private const RELEASES_PATH = '/api/v1/repos' . self::PROJECT . '/releases';
|
||||||
|
private const TAG = '/^v(\d+\.\d+\.\d+)$/D';
|
||||||
|
|
||||||
|
// These two releases shipped with 1.4.0 in VERSION. Identify their original files when updating old installations.
|
||||||
|
private const LEGACY_VERSIONS = [
|
||||||
|
'1.4.2' => [
|
||||||
|
'bin/update.sh' => 'a1cc96a5ecc3db3074563877dec07f0ebf8689e90e0e9aece838071df4793e26',
|
||||||
|
'bin/update.php' => 'b13d3e925b59589f4d599d6deebb1fb27fa81ad0b98e5d0c67199279c3de9635',
|
||||||
|
],
|
||||||
|
'1.4.1' => [
|
||||||
|
'public/assets/vendor/codemirror/xml.min.js' => 'c0c38a5cf20549c4e20d90428edd830cbbf6a631245a1ac2fb8e88676d4c0b7a',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
private const LEGACY_BASES = ['1.3.0' => 'd5bedabaa1d0187e29060c41fb030e9587a8692f'];
|
||||||
|
private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|updatescript_map\.json|composer\.(?:json|lock)|start\.php)$/D';
|
||||||
|
private const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
|
||||||
|
private const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
|
||||||
|
|
||||||
|
public function __construct(private readonly string $root)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute(?string $target, ?string $backup): void
|
||||||
|
{
|
||||||
|
$current = $this->version();
|
||||||
|
$map = self::remoteJson(self::MAP_PATH, 65536, 10000);
|
||||||
|
$rule = is_object($map) ? ($map->{self::UPDATESCRIPT_VERSION} ?? null) : null;
|
||||||
|
if (!is_object($rule)) {
|
||||||
|
throw new RuntimeException('当前更新器未列入兼容表,请下载新版 update.php。');
|
||||||
|
}
|
||||||
|
$from = self::parseRange($rule->from ?? null);
|
||||||
|
$to = self::parseRange($rule->to ?? null);
|
||||||
|
$releases = self::releases();
|
||||||
|
$latest = array_key_first($releases);
|
||||||
|
$latestVersion = $latest === null ? null : substr($latest, 1);
|
||||||
|
if (!self::inRange($current, $from, $latestVersion)) {
|
||||||
|
throw new RuntimeException("当前站点 v$current 超出此更新器的起始版本范围 {$rule->from}。");
|
||||||
|
}
|
||||||
|
$eligible = array_filter($releases, static function (string $tag) use ($current, $to, $latestVersion): bool {
|
||||||
|
$version = substr($tag, 1);
|
||||||
|
|
||||||
|
return version_compare($version, $current, '>') && self::inRange($version, $to, $latestVersion);
|
||||||
|
}, ARRAY_FILTER_USE_KEY);
|
||||||
|
printf("更新器 v%s,当前站点 v%s\n兼容起始版本 %s,目标范围 %s\n",
|
||||||
|
self::UPDATESCRIPT_VERSION, $current, $rule->from, $rule->to);
|
||||||
|
|
||||||
|
if ($target === 'check') {
|
||||||
|
if ($latest !== null) {
|
||||||
|
printf("上游最新正式发布 %s\n", $latest);
|
||||||
|
}
|
||||||
|
echo $eligible === [] ? "暂无可升级的正式发布版本。\n"
|
||||||
|
: '可升级至 ' . implode('、', array_keys($eligible)) . PHP_EOL;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ($target === null) {
|
||||||
|
$target = self::chooseRelease($eligible);
|
||||||
|
if ($target === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} elseif ($target === 'v' . $current) {
|
||||||
|
printf("当前已安装 %s。\n", $target);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($eligible[$target])) {
|
||||||
|
throw new RuntimeException("无法从 v$current 升级到 {$target}。可选版本为 "
|
||||||
|
. ($eligible === [] ? '无。' : implode('、', array_keys($eligible)) . '。'));
|
||||||
|
}
|
||||||
|
$this->update($current, $target, $backup);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function parseRange(mixed $value): array
|
||||||
|
{
|
||||||
|
if (!is_string($value) || !preg_match('/^v(\d+\.\d+\.\d+)-(?:v(\d+\.\d+\.\d+)|latest)$/D', $value, $parts)
|
||||||
|
|| (isset($parts[2]) && version_compare($parts[1], $parts[2], '>'))) {
|
||||||
|
throw new RuntimeException('更新器兼容表中的版本范围无效。');
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$parts[1], $parts[2] ?? null];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function inRange(string $version, array $range, ?string $latest): bool
|
||||||
|
{
|
||||||
|
[$minimum, $maximum] = $range;
|
||||||
|
$maximum ??= $latest;
|
||||||
|
|
||||||
|
return version_compare($version, $minimum, '>=') && ($maximum === null || version_compare($version, $maximum, '<='));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function releases(): array
|
||||||
|
{
|
||||||
|
$result = [];
|
||||||
|
$deadline = hrtime(true) + 10_000_000_000;
|
||||||
|
for ($page = 1; ; $page++) {
|
||||||
|
$timeout = (int) (($deadline - hrtime(true)) / 1_000_000);
|
||||||
|
if ($timeout <= 0) {
|
||||||
|
throw new RuntimeException('查询 LaySite 发布列表超时。');
|
||||||
|
}
|
||||||
|
$entries = self::remoteJson(self::RELEASES_PATH . "?limit=50&page=$page", 1024 * 1024, $timeout);
|
||||||
|
if (!is_array($entries)) {
|
||||||
|
throw new RuntimeException('LaySite 发布列表格式无效。');
|
||||||
|
}
|
||||||
|
foreach ($entries as $entry) {
|
||||||
|
if (!is_string($entry->tag_name ?? null) || !is_bool($entry->draft ?? null) || !is_bool($entry->prerelease ?? null)) {
|
||||||
|
throw new RuntimeException('LaySite 发布列表格式无效。');
|
||||||
|
}
|
||||||
|
if (!$entry->draft && !$entry->prerelease && preg_match(self::TAG, $entry->tag_name)) {
|
||||||
|
$result[$entry->tag_name] = $entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (count($entries) < 50) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uksort($result, static fn (string $a, string $b): int => version_compare(substr($b, 1), substr($a, 1)));
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function remoteJson(string $path, int $limit, int $timeout): mixed
|
||||||
|
{
|
||||||
|
$stream = fopen('php://temp', 'w+b');
|
||||||
|
if ($stream === false) {
|
||||||
|
throw new RuntimeException('无法创建更新查询缓冲区。');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
self::download($path, $stream, $limit, $timeout);
|
||||||
|
rewind($stream);
|
||||||
|
|
||||||
|
return json_decode((string) stream_get_contents($stream), flags: JSON_THROW_ON_ERROR);
|
||||||
|
} finally {
|
||||||
|
fclose($stream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function chooseRelease(array $releases): ?string
|
||||||
|
{
|
||||||
|
if ($releases === []) {
|
||||||
|
echo "暂无可升级的正式发布版本。\n";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$tags = array_keys($releases);
|
||||||
|
foreach ($tags as $index => $tag) {
|
||||||
|
$release = $releases[$tag];
|
||||||
|
$title = self::terminalText($release->name ?? '');
|
||||||
|
$details = self::terminalText($release->body ?? '');
|
||||||
|
printf("\n%d. %s%s\n", $index + 1, $tag, $title === '' || $title === $tag ? '' : ' · ' . str_replace("\n", ' ', $title));
|
||||||
|
echo ' ' . str_replace("\n", "\n ", $details === '' ? '暂无发布说明。' : $details) . PHP_EOL;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
echo "\n请选择版本编号或输入标签,回车取消\n> ";
|
||||||
|
$selection = trim((string) fgets(STDIN));
|
||||||
|
if ($selection === '' || strtolower($selection) === 'q') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (isset($releases[$selection])) {
|
||||||
|
return $selection;
|
||||||
|
}
|
||||||
|
if (ctype_digit($selection) && isset($tags[(int) $selection - 1])) {
|
||||||
|
return $tags[(int) $selection - 1];
|
||||||
|
}
|
||||||
|
echo "请输入列表中的编号或版本。\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function terminalText(mixed $value): string
|
||||||
|
{
|
||||||
|
if (!is_string($value)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return trim(preg_replace('/[^\P{C}\n\t]/u', '', str_replace(["\r\n", "\r"], "\n", $value)) ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function update(string $current, string $target, ?string $backup): void
|
||||||
|
{
|
||||||
|
$runtime = $this->root . '/runtime';
|
||||||
|
self::makeDirectory($runtime);
|
||||||
|
$lock = fopen($runtime . '/release-update.lock', 'c');
|
||||||
|
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) {
|
||||||
|
throw new RuntimeException('无法取得 LaySite 更新锁。');
|
||||||
|
}
|
||||||
|
$pending = $runtime . '/release-update-pending';
|
||||||
|
$work = $this->root . '/.laysite-update-' . bin2hex(random_bytes(8));
|
||||||
|
try {
|
||||||
|
if (file_exists($pending) || is_link($pending)) {
|
||||||
|
throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending)));
|
||||||
|
}
|
||||||
|
if ($this->version() !== $current) {
|
||||||
|
throw new RuntimeException('站点版本已经变更,请重新选择更新目标。');
|
||||||
|
}
|
||||||
|
$backup = $this->backupPath($backup, $current, $target);
|
||||||
|
|
||||||
|
if (!mkdir($work, 0700)) {
|
||||||
|
throw new RuntimeException('无法建立更新暂存目录。');
|
||||||
|
}
|
||||||
|
$base = $this->archive(self::LEGACY_BASES[$current] ?? ('v' . $current), $current, $work . '/base.zip');
|
||||||
|
// Accept the VERSION file already identified above, including the old release numbering.
|
||||||
|
$base['VERSION']['hash'] = hash_file('sha256', $this->root . '/VERSION');
|
||||||
|
$release = $this->archive($target, substr($target, 1), $work . '/release.zip');
|
||||||
|
$plan = $this->plan($base, $release, $backup);
|
||||||
|
$php = getenv('LAYSITE_PHP') ?: PHP_BINARY;
|
||||||
|
self::run([$php, 'bin/backup.php', 'export', $backup], $this->root);
|
||||||
|
$vendor = $this->stageDependencies($work, $plan, $release);
|
||||||
|
if ($plan !== $this->plan($base, $release, $backup)) {
|
||||||
|
throw new RuntimeException('准备更新期间,站点文件发生了变化。');
|
||||||
|
}
|
||||||
|
$this->apply($work, $pending, $plan, $release, $vendor, $php);
|
||||||
|
printf("已更新至 %s,可使用原站点配置启动 Webman。\n", $target);
|
||||||
|
} finally {
|
||||||
|
if (is_dir($work) && !is_file($pending)) {
|
||||||
|
self::removeDirectory($work);
|
||||||
|
}
|
||||||
|
fclose($lock);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function backupPath(?string $path, string $current, string $target): string
|
||||||
|
{
|
||||||
|
if ($path === null) {
|
||||||
|
$directory = $this->root . '/storage/backups';
|
||||||
|
self::makeDirectory($directory);
|
||||||
|
$path = sprintf('%s/laysite-v%s-%s-%s-%s.tar', $directory, $current, $target, gmdate('Ymd-His'), bin2hex(random_bytes(4)));
|
||||||
|
} elseif (!str_starts_with($path, '/')) {
|
||||||
|
$path = $this->root . '/' . $path;
|
||||||
|
}
|
||||||
|
$directory = realpath(dirname($path));
|
||||||
|
if ($directory === false || !str_ends_with($path, '.tar') || file_exists($path) || is_link($path)) {
|
||||||
|
throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。');
|
||||||
|
}
|
||||||
|
$path = $directory . '/' . basename($path);
|
||||||
|
printf("站点备份将写入 %s\n", $path);
|
||||||
|
|
||||||
|
return $path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function version(): string
|
||||||
|
{
|
||||||
|
$version = trim((string) @file_get_contents($this->root . '/VERSION'));
|
||||||
|
if (!preg_match('/^\d+\.\d+\.\d+$/D', $version)) {
|
||||||
|
throw new RuntimeException('请从已安装 LaySite 的目录运行更新器。');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($version === '1.4.0') {
|
||||||
|
foreach (self::LEGACY_VERSIONS as $tag => $files) {
|
||||||
|
foreach ($files as $path => $hash) {
|
||||||
|
if (@hash_file('sha256', $this->root . '/' . $path) === $hash) {
|
||||||
|
return $tag;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $version;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function download(string $path, $stream, int $limit, int $timeout): void
|
||||||
|
{
|
||||||
|
$curl = curl_init(self::HOST . $path);
|
||||||
|
$bytes = 0;
|
||||||
|
curl_setopt_array($curl, [
|
||||||
|
CURLOPT_USERAGENT => 'LaySite release updater',
|
||||||
|
CURLOPT_CONNECTTIMEOUT_MS => min(3500, $timeout),
|
||||||
|
CURLOPT_TIMEOUT_MS => $timeout,
|
||||||
|
CURLOPT_FOLLOWLOCATION => false,
|
||||||
|
CURLOPT_WRITEFUNCTION => static function (CurlHandle $curl, string $chunk) use ($stream, $limit, &$bytes): int {
|
||||||
|
$bytes += strlen($chunk);
|
||||||
|
|
||||||
|
return $bytes > $limit ? 0 : (int) fwrite($stream, $chunk);
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
if (curl_exec($curl) === false) {
|
||||||
|
throw new RuntimeException('下载 LaySite 发布文件失败。' . ($bytes > $limit ? '文件超过大小限制。' : curl_error($curl)));
|
||||||
|
}
|
||||||
|
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||||
|
if ($status !== 200) {
|
||||||
|
throw new RuntimeException("无法读取 LaySite 发布文件 {$path}(HTTP $status)。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function archive(string $ref, string $version, string $path): array
|
||||||
|
{
|
||||||
|
$stream = fopen($path, 'xb');
|
||||||
|
if ($stream === false) {
|
||||||
|
throw new RuntimeException('无法写入发布 ZIP。');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
self::download(self::PROJECT . "/archive/$ref.zip", $stream, self::MAX_ARCHIVE_BYTES, 60_000);
|
||||||
|
} finally {
|
||||||
|
fclose($stream);
|
||||||
|
}
|
||||||
|
$archive = new PharData($path);
|
||||||
|
$files = [];
|
||||||
|
$size = 0;
|
||||||
|
$prefix = 'phar://' . $path . '/laysite/';
|
||||||
|
foreach (new RecursiveIteratorIterator($archive) as $entry) {
|
||||||
|
$uri = $entry->getPathname();
|
||||||
|
if (!str_starts_with($uri, $prefix)) {
|
||||||
|
throw new RuntimeException('发布 ZIP 的目录结构无效。');
|
||||||
|
}
|
||||||
|
$name = substr($uri, strlen($prefix));
|
||||||
|
if ($entry->isLink() || !$entry->isFile() || str_contains($name, '\\')
|
||||||
|
|| preg_match('~(?:^|/)\.{0,2}(?:/|$)|[\x00-\x1f\x7f]~', $name)) {
|
||||||
|
throw new RuntimeException('发布 ZIP 包含无效的文件路径。');
|
||||||
|
}
|
||||||
|
$size += $entry->getSize();
|
||||||
|
if ($size > self::MAX_EXPANDED_BYTES) {
|
||||||
|
throw new RuntimeException('发布 ZIP 解压后的大小超过限制。');
|
||||||
|
}
|
||||||
|
if (!preg_match(self::MANAGED, $name)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$hash = hash_file('sha256', $uri);
|
||||||
|
if ($hash === false || isset($files[$name])) {
|
||||||
|
throw new RuntimeException('发布 ZIP 文件损坏。');
|
||||||
|
}
|
||||||
|
$files[$name] = ['uri' => $uri, 'hash' => $hash, 'mode' => $entry->getPerms() & 0777];
|
||||||
|
}
|
||||||
|
foreach (['VERSION', 'start.php', 'bin/install.php', 'composer.json', 'composer.lock', 'resources/schema.sql'] as $required) {
|
||||||
|
if (!isset($files[$required])) {
|
||||||
|
throw new RuntimeException('发布 ZIP 缺少 ' . $required);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$embedded = trim((string) file_get_contents($files['VERSION']['uri']));
|
||||||
|
if ($embedded !== $version) {
|
||||||
|
if ($embedded !== '1.4.0' || !isset(self::LEGACY_VERSIONS[$version])) {
|
||||||
|
throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。');
|
||||||
|
}
|
||||||
|
$canonical = $path . '.version';
|
||||||
|
$contents = $version . "\n";
|
||||||
|
if (file_put_contents($canonical, $contents) !== strlen($contents)) {
|
||||||
|
throw new RuntimeException('无法暂存发布版本号。');
|
||||||
|
}
|
||||||
|
$files['VERSION'] = ['uri' => $canonical, 'hash' => hash('sha256', $contents), 'mode' => 0644];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $files;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function plan(array $base, array $release, string $backup): array
|
||||||
|
{
|
||||||
|
clearstatcache();
|
||||||
|
require_once $this->root . '/vendor/autoload.php';
|
||||||
|
$database = App\Content\Database::path();
|
||||||
|
$media = App\Content\Media::directory();
|
||||||
|
$protected = array_unique([
|
||||||
|
$database, realpath($database) ?: $database, $media, realpath($media) ?: $media, $backup,
|
||||||
|
]);
|
||||||
|
$plan = [];
|
||||||
|
$conflicts = [];
|
||||||
|
foreach (array_keys($base + $release) as $name) {
|
||||||
|
$old = $base[$name]['hash'] ?? null;
|
||||||
|
$next = $release[$name]['hash'] ?? null;
|
||||||
|
if ($old === $next) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$path = $this->managedPath($name);
|
||||||
|
foreach ($protected as $reserved) {
|
||||||
|
if ($path === $reserved || str_starts_with($path, rtrim($reserved, '/') . '/')
|
||||||
|
|| str_starts_with($reserved, $path . '/') || in_array($path, [$database . '.key', $database . '-wal', $database . '-shm'], true)) {
|
||||||
|
throw new RuntimeException('更新路径与站点数据重叠。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$local = is_file($path) ? hash_file('sha256', $path) : null;
|
||||||
|
if ($local === $next) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($local !== $old) {
|
||||||
|
$conflicts[] = $name;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$plan[] = $name;
|
||||||
|
} catch (RuntimeException) {
|
||||||
|
$conflicts[] = $name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($conflicts !== []) {
|
||||||
|
sort($conflicts);
|
||||||
|
throw new RuntimeException("以下路径与站点定制或数据冲突,尚未替换任何文件:\n" . implode("\n", $conflicts));
|
||||||
|
}
|
||||||
|
if (array_intersect(['composer.json', 'composer.lock'], $plan)) {
|
||||||
|
$vendor = $this->root . '/vendor';
|
||||||
|
foreach ($protected as $reserved) {
|
||||||
|
if ($reserved === $vendor || str_starts_with($reserved, $vendor . '/')) {
|
||||||
|
throw new RuntimeException('站点数据或备份路径位于 vendor 目录,请先调整该路径。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function managedPath(string $name): string
|
||||||
|
{
|
||||||
|
$path = $this->root;
|
||||||
|
$parts = explode('/', $name);
|
||||||
|
$leaf = array_pop($parts);
|
||||||
|
foreach ($parts as $part) {
|
||||||
|
$path .= '/' . $part;
|
||||||
|
if (is_link($path) || (file_exists($path) && !is_dir($path))) {
|
||||||
|
throw new RuntimeException('更新路径不可写:' . $name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$path .= '/' . $leaf;
|
||||||
|
if (is_link($path) || (file_exists($path) && !is_file($path))) {
|
||||||
|
throw new RuntimeException('更新路径不可写:' . $name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function stageDependencies(string $work, array $plan, array $release): ?string
|
||||||
|
{
|
||||||
|
if (!array_intersect(['composer.json', 'composer.lock'], $plan)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$dependencies = $work . '/dependencies';
|
||||||
|
self::makeDirectory($dependencies);
|
||||||
|
foreach (['composer.json', 'composer.lock'] as $name) {
|
||||||
|
$source = in_array($name, $plan, true) ? $release[$name]['uri'] : $this->root . '/' . $name;
|
||||||
|
if (!copy($source, $dependencies . '/' . $name)) {
|
||||||
|
throw new RuntimeException('无法准备 Composer 依赖。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$vendor = $dependencies . '/vendor';
|
||||||
|
self::run([
|
||||||
|
getenv('LAYSITE_COMPOSER') ?: 'composer', 'install', '--no-dev', '--prefer-dist',
|
||||||
|
'--no-interaction', '--no-scripts', '--no-plugins',
|
||||||
|
], $dependencies, array_replace(getenv(), ['COMPOSER' => 'composer.json', 'COMPOSER_VENDOR_DIR' => $vendor]));
|
||||||
|
if (!is_file($vendor . '/autoload.php')) {
|
||||||
|
throw new RuntimeException('Composer 没有在暂存目录生成依赖。');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $vendor;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function apply(string $work, string $pending, array $plan, array $release, ?string $vendor, string $php): void
|
||||||
|
{
|
||||||
|
$staged = [];
|
||||||
|
foreach ($plan as $name) {
|
||||||
|
$staged[$name] = null;
|
||||||
|
if (isset($release[$name])) {
|
||||||
|
$file = $work . '/files/' . $name;
|
||||||
|
self::makeDirectory(dirname($file));
|
||||||
|
$mode = $release[$name]['mode'] & 0755;
|
||||||
|
if ($name === 'bin/update.sh') {
|
||||||
|
$mode |= 0100;
|
||||||
|
}
|
||||||
|
if (!copy($release[$name]['uri'], $file) || !chmod($file, $mode ?: 0644)) {
|
||||||
|
throw new RuntimeException('无法暂存文件 ' . $name);
|
||||||
|
}
|
||||||
|
$staged[$name] = $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($vendor !== null) {
|
||||||
|
if (is_link($this->root . '/vendor') || !is_dir($this->root . '/vendor')) {
|
||||||
|
throw new RuntimeException('站点的 vendor 目录需要手动更新。');
|
||||||
|
}
|
||||||
|
$staged['vendor'] = $vendor;
|
||||||
|
}
|
||||||
|
$marker = fopen($pending, 'x');
|
||||||
|
if ($marker === false) {
|
||||||
|
throw new RuntimeException('无法写入更新记录。');
|
||||||
|
}
|
||||||
|
$record = $work . PHP_EOL;
|
||||||
|
$written = fwrite($marker, $record);
|
||||||
|
fclose($marker);
|
||||||
|
if ($written !== strlen($record)) {
|
||||||
|
unlink($pending);
|
||||||
|
throw new RuntimeException('无法写入完整的更新记录。');
|
||||||
|
}
|
||||||
|
$applied = [];
|
||||||
|
try {
|
||||||
|
foreach ($staged as $name => $source) {
|
||||||
|
$destination = $this->root . '/' . $name;
|
||||||
|
$previous = $work . '/previous/' . $name;
|
||||||
|
if (file_exists($destination)) {
|
||||||
|
self::makeDirectory(dirname($previous));
|
||||||
|
self::move($destination, $previous);
|
||||||
|
}
|
||||||
|
$applied[] = $name;
|
||||||
|
if ($source !== null) {
|
||||||
|
self::makeDirectory(dirname($destination));
|
||||||
|
self::move($source, $destination);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self::run([$php, 'bin/install.php'], $this->root);
|
||||||
|
} catch (Throwable $error) {
|
||||||
|
try {
|
||||||
|
foreach (array_reverse($applied) as $name) {
|
||||||
|
$path = $this->root . '/' . $name;
|
||||||
|
if (file_exists($path)) {
|
||||||
|
$discard = $work . '/discard/' . $name;
|
||||||
|
self::makeDirectory(dirname($discard));
|
||||||
|
self::move($path, $discard);
|
||||||
|
}
|
||||||
|
$previous = $work . '/previous/' . $name;
|
||||||
|
if (file_exists($previous)) {
|
||||||
|
self::move($previous, $path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unlink($pending);
|
||||||
|
} catch (Throwable $rollback) {
|
||||||
|
throw new RuntimeException('更新回退未完成。原文件保存在 ' . $work . '。' . $rollback->getMessage(), previous: $error);
|
||||||
|
}
|
||||||
|
throw new RuntimeException('更新失败,原程序文件已恢复。' . $error->getMessage(), previous: $error);
|
||||||
|
}
|
||||||
|
unlink($pending);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function move(string $from, string $to): void
|
||||||
|
{
|
||||||
|
if (!rename($from, $to)) {
|
||||||
|
throw new RuntimeException('无法移动 ' . $from . ' 到 ' . $to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function run(array $command, string $directory, ?array $environment = null): void
|
||||||
|
{
|
||||||
|
$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, $directory, $environment);
|
||||||
|
if (!is_resource($process) || proc_close($process) !== 0) {
|
||||||
|
throw new RuntimeException('命令执行失败:' . implode(' ', array_slice($command, 0, 2)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function makeDirectory(string $path): void
|
||||||
|
{
|
||||||
|
if (!is_dir($path) && !mkdir($path, 0755, true) && !is_dir($path)) {
|
||||||
|
throw new RuntimeException('无法建立目录 ' . $path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function removeDirectory(string $path): void
|
||||||
|
{
|
||||||
|
$entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
|
||||||
|
RecursiveIteratorIterator::CHILD_FIRST);
|
||||||
|
foreach ($entries as $entry) {
|
||||||
|
if ($entry->isDir() && !$entry->isLink()) {
|
||||||
|
rmdir($entry->getPathname());
|
||||||
|
} else {
|
||||||
|
unlink($entry->getPathname());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rmdir($path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$target = $argv[1] ?? null;
|
||||||
|
$backup = $argv[2] ?? null;
|
||||||
|
if ($argc > 3 || ($target === 'check' && $backup !== null)
|
||||||
|
|| ($target !== null && $target !== 'check' && !preg_match('/^v\d+\.\d+\.\d+$/D', $target))) {
|
||||||
|
fwrite(STDERR, "用法:php bin/update.php [check | vX.Y.Z [备份路径.tar]]\n");
|
||||||
|
exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
umask(0027);
|
||||||
|
try {
|
||||||
|
(new LaySiteUpdater(getcwd()))->execute($target, $backup);
|
||||||
|
} catch (Throwable $error) {
|
||||||
|
fwrite(STDERR, $error->getMessage() . PHP_EOL);
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
Vendored
+25
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// autoload.php @generated by Composer
|
||||||
|
|
||||||
|
if (PHP_VERSION_ID < 50600) {
|
||||||
|
if (!headers_sent()) {
|
||||||
|
header('HTTP/1.1 500 Internal Server Error');
|
||||||
|
}
|
||||||
|
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
|
||||||
|
if (!ini_get('display_errors')) {
|
||||||
|
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
|
||||||
|
fwrite(STDERR, $err);
|
||||||
|
} elseif (!headers_sent()) {
|
||||||
|
echo $err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trigger_error(
|
||||||
|
$err,
|
||||||
|
E_USER_ERROR
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
require_once __DIR__ . '/composer/autoload_real.php';
|
||||||
|
|
||||||
|
return ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56::getLoader();
|
||||||
Vendored
+579
@@ -0,0 +1,579 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is part of Composer.
|
||||||
|
*
|
||||||
|
* (c) Nils Adermann <naderman@naderman.de>
|
||||||
|
* Jordi Boggiano <j.boggiano@seld.be>
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Composer\Autoload;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
|
||||||
|
*
|
||||||
|
* $loader = new \Composer\Autoload\ClassLoader();
|
||||||
|
*
|
||||||
|
* // register classes with namespaces
|
||||||
|
* $loader->add('Symfony\Component', __DIR__.'/component');
|
||||||
|
* $loader->add('Symfony', __DIR__.'/framework');
|
||||||
|
*
|
||||||
|
* // activate the autoloader
|
||||||
|
* $loader->register();
|
||||||
|
*
|
||||||
|
* // to enable searching the include path (eg. for PEAR packages)
|
||||||
|
* $loader->setUseIncludePath(true);
|
||||||
|
*
|
||||||
|
* In this example, if you try to use a class in the Symfony\Component
|
||||||
|
* namespace or one of its children (Symfony\Component\Console for instance),
|
||||||
|
* the autoloader will first look for the class under the component/
|
||||||
|
* directory, and it will then fallback to the framework/ directory if not
|
||||||
|
* found before giving up.
|
||||||
|
*
|
||||||
|
* This class is loosely based on the Symfony UniversalClassLoader.
|
||||||
|
*
|
||||||
|
* @author Fabien Potencier <fabien@symfony.com>
|
||||||
|
* @author Jordi Boggiano <j.boggiano@seld.be>
|
||||||
|
* @see https://www.php-fig.org/psr/psr-0/
|
||||||
|
* @see https://www.php-fig.org/psr/psr-4/
|
||||||
|
*/
|
||||||
|
class ClassLoader
|
||||||
|
{
|
||||||
|
/** @var \Closure(string):void */
|
||||||
|
private static $includeFile;
|
||||||
|
|
||||||
|
/** @var string|null */
|
||||||
|
private $vendorDir;
|
||||||
|
|
||||||
|
// PSR-4
|
||||||
|
/**
|
||||||
|
* @var array<string, array<string, int>>
|
||||||
|
*/
|
||||||
|
private $prefixLengthsPsr4 = array();
|
||||||
|
/**
|
||||||
|
* @var array<string, list<string>>
|
||||||
|
*/
|
||||||
|
private $prefixDirsPsr4 = array();
|
||||||
|
/**
|
||||||
|
* @var list<string>
|
||||||
|
*/
|
||||||
|
private $fallbackDirsPsr4 = array();
|
||||||
|
|
||||||
|
// PSR-0
|
||||||
|
/**
|
||||||
|
* List of PSR-0 prefixes
|
||||||
|
*
|
||||||
|
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
|
||||||
|
*
|
||||||
|
* @var array<string, array<string, list<string>>>
|
||||||
|
*/
|
||||||
|
private $prefixesPsr0 = array();
|
||||||
|
/**
|
||||||
|
* @var list<string>
|
||||||
|
*/
|
||||||
|
private $fallbackDirsPsr0 = array();
|
||||||
|
|
||||||
|
/** @var bool */
|
||||||
|
private $useIncludePath = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
private $classMap = array();
|
||||||
|
|
||||||
|
/** @var bool */
|
||||||
|
private $classMapAuthoritative = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, bool>
|
||||||
|
*/
|
||||||
|
private $missingClasses = array();
|
||||||
|
|
||||||
|
/** @var string|null */
|
||||||
|
private $apcuPrefix;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, self>
|
||||||
|
*/
|
||||||
|
private static $registeredLoaders = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|null $vendorDir
|
||||||
|
*/
|
||||||
|
public function __construct($vendorDir = null)
|
||||||
|
{
|
||||||
|
$this->vendorDir = $vendorDir;
|
||||||
|
self::initializeIncludeClosure();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, list<string>>
|
||||||
|
*/
|
||||||
|
public function getPrefixes()
|
||||||
|
{
|
||||||
|
if (!empty($this->prefixesPsr0)) {
|
||||||
|
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
|
||||||
|
}
|
||||||
|
|
||||||
|
return array();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, list<string>>
|
||||||
|
*/
|
||||||
|
public function getPrefixesPsr4()
|
||||||
|
{
|
||||||
|
return $this->prefixDirsPsr4;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function getFallbackDirs()
|
||||||
|
{
|
||||||
|
return $this->fallbackDirsPsr0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function getFallbackDirsPsr4()
|
||||||
|
{
|
||||||
|
return $this->fallbackDirsPsr4;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string> Array of classname => path
|
||||||
|
*/
|
||||||
|
public function getClassMap()
|
||||||
|
{
|
||||||
|
return $this->classMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, string> $classMap Class to filename map
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function addClassMap(array $classMap)
|
||||||
|
{
|
||||||
|
if ($this->classMap) {
|
||||||
|
$this->classMap = array_merge($this->classMap, $classMap);
|
||||||
|
} else {
|
||||||
|
$this->classMap = $classMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a set of PSR-0 directories for a given prefix, either
|
||||||
|
* appending or prepending to the ones previously set for this prefix.
|
||||||
|
*
|
||||||
|
* @param string $prefix The prefix
|
||||||
|
* @param list<string>|string $paths The PSR-0 root directories
|
||||||
|
* @param bool $prepend Whether to prepend the directories
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function add($prefix, $paths, $prepend = false)
|
||||||
|
{
|
||||||
|
$paths = (array) $paths;
|
||||||
|
if (!$prefix) {
|
||||||
|
if ($prepend) {
|
||||||
|
$this->fallbackDirsPsr0 = array_merge(
|
||||||
|
$paths,
|
||||||
|
$this->fallbackDirsPsr0
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$this->fallbackDirsPsr0 = array_merge(
|
||||||
|
$this->fallbackDirsPsr0,
|
||||||
|
$paths
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$first = $prefix[0];
|
||||||
|
if (!isset($this->prefixesPsr0[$first][$prefix])) {
|
||||||
|
$this->prefixesPsr0[$first][$prefix] = $paths;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ($prepend) {
|
||||||
|
$this->prefixesPsr0[$first][$prefix] = array_merge(
|
||||||
|
$paths,
|
||||||
|
$this->prefixesPsr0[$first][$prefix]
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$this->prefixesPsr0[$first][$prefix] = array_merge(
|
||||||
|
$this->prefixesPsr0[$first][$prefix],
|
||||||
|
$paths
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a set of PSR-4 directories for a given namespace, either
|
||||||
|
* appending or prepending to the ones previously set for this namespace.
|
||||||
|
*
|
||||||
|
* @param string $prefix The prefix/namespace, with trailing '\\'
|
||||||
|
* @param list<string>|string $paths The PSR-4 base directories
|
||||||
|
* @param bool $prepend Whether to prepend the directories
|
||||||
|
*
|
||||||
|
* @throws \InvalidArgumentException
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function addPsr4($prefix, $paths, $prepend = false)
|
||||||
|
{
|
||||||
|
$paths = (array) $paths;
|
||||||
|
if (!$prefix) {
|
||||||
|
// Register directories for the root namespace.
|
||||||
|
if ($prepend) {
|
||||||
|
$this->fallbackDirsPsr4 = array_merge(
|
||||||
|
$paths,
|
||||||
|
$this->fallbackDirsPsr4
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$this->fallbackDirsPsr4 = array_merge(
|
||||||
|
$this->fallbackDirsPsr4,
|
||||||
|
$paths
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
|
||||||
|
// Register directories for a new namespace.
|
||||||
|
$length = strlen($prefix);
|
||||||
|
if ('\\' !== $prefix[$length - 1]) {
|
||||||
|
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
|
||||||
|
}
|
||||||
|
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
|
||||||
|
$this->prefixDirsPsr4[$prefix] = $paths;
|
||||||
|
} elseif ($prepend) {
|
||||||
|
// Prepend directories for an already registered namespace.
|
||||||
|
$this->prefixDirsPsr4[$prefix] = array_merge(
|
||||||
|
$paths,
|
||||||
|
$this->prefixDirsPsr4[$prefix]
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Append directories for an already registered namespace.
|
||||||
|
$this->prefixDirsPsr4[$prefix] = array_merge(
|
||||||
|
$this->prefixDirsPsr4[$prefix],
|
||||||
|
$paths
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a set of PSR-0 directories for a given prefix,
|
||||||
|
* replacing any others previously set for this prefix.
|
||||||
|
*
|
||||||
|
* @param string $prefix The prefix
|
||||||
|
* @param list<string>|string $paths The PSR-0 base directories
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function set($prefix, $paths)
|
||||||
|
{
|
||||||
|
if (!$prefix) {
|
||||||
|
$this->fallbackDirsPsr0 = (array) $paths;
|
||||||
|
} else {
|
||||||
|
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a set of PSR-4 directories for a given namespace,
|
||||||
|
* replacing any others previously set for this namespace.
|
||||||
|
*
|
||||||
|
* @param string $prefix The prefix/namespace, with trailing '\\'
|
||||||
|
* @param list<string>|string $paths The PSR-4 base directories
|
||||||
|
*
|
||||||
|
* @throws \InvalidArgumentException
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setPsr4($prefix, $paths)
|
||||||
|
{
|
||||||
|
if (!$prefix) {
|
||||||
|
$this->fallbackDirsPsr4 = (array) $paths;
|
||||||
|
} else {
|
||||||
|
$length = strlen($prefix);
|
||||||
|
if ('\\' !== $prefix[$length - 1]) {
|
||||||
|
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
|
||||||
|
}
|
||||||
|
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
|
||||||
|
$this->prefixDirsPsr4[$prefix] = (array) $paths;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns on searching the include path for class files.
|
||||||
|
*
|
||||||
|
* @param bool $useIncludePath
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setUseIncludePath($useIncludePath)
|
||||||
|
{
|
||||||
|
$this->useIncludePath = $useIncludePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Can be used to check if the autoloader uses the include path to check
|
||||||
|
* for classes.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function getUseIncludePath()
|
||||||
|
{
|
||||||
|
return $this->useIncludePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns off searching the prefix and fallback directories for classes
|
||||||
|
* that have not been registered with the class map.
|
||||||
|
*
|
||||||
|
* @param bool $classMapAuthoritative
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setClassMapAuthoritative($classMapAuthoritative)
|
||||||
|
{
|
||||||
|
$this->classMapAuthoritative = $classMapAuthoritative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Should class lookup fail if not found in the current class map?
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function isClassMapAuthoritative()
|
||||||
|
{
|
||||||
|
return $this->classMapAuthoritative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
|
||||||
|
*
|
||||||
|
* @param string|null $apcuPrefix
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setApcuPrefix($apcuPrefix)
|
||||||
|
{
|
||||||
|
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The APCu prefix in use, or null if APCu caching is not enabled.
|
||||||
|
*
|
||||||
|
* @return string|null
|
||||||
|
*/
|
||||||
|
public function getApcuPrefix()
|
||||||
|
{
|
||||||
|
return $this->apcuPrefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers this instance as an autoloader.
|
||||||
|
*
|
||||||
|
* @param bool $prepend Whether to prepend the autoloader or not
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function register($prepend = false)
|
||||||
|
{
|
||||||
|
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
|
||||||
|
|
||||||
|
if (null === $this->vendorDir) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($prepend) {
|
||||||
|
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
|
||||||
|
} else {
|
||||||
|
unset(self::$registeredLoaders[$this->vendorDir]);
|
||||||
|
self::$registeredLoaders[$this->vendorDir] = $this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unregisters this instance as an autoloader.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function unregister()
|
||||||
|
{
|
||||||
|
spl_autoload_unregister(array($this, 'loadClass'));
|
||||||
|
|
||||||
|
if (null !== $this->vendorDir) {
|
||||||
|
unset(self::$registeredLoaders[$this->vendorDir]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads the given class or interface.
|
||||||
|
*
|
||||||
|
* @param string $class The name of the class
|
||||||
|
* @return true|null True if loaded, null otherwise
|
||||||
|
*/
|
||||||
|
public function loadClass($class)
|
||||||
|
{
|
||||||
|
if ($file = $this->findFile($class)) {
|
||||||
|
$includeFile = self::$includeFile;
|
||||||
|
$includeFile($file);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the path to the file where the class is defined.
|
||||||
|
*
|
||||||
|
* @param string $class The name of the class
|
||||||
|
*
|
||||||
|
* @return string|false The path if found, false otherwise
|
||||||
|
*/
|
||||||
|
public function findFile($class)
|
||||||
|
{
|
||||||
|
// class map lookup
|
||||||
|
if (isset($this->classMap[$class])) {
|
||||||
|
return $this->classMap[$class];
|
||||||
|
}
|
||||||
|
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (null !== $this->apcuPrefix) {
|
||||||
|
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
|
||||||
|
if ($hit) {
|
||||||
|
return $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$file = $this->findFileWithExtension($class, '.php');
|
||||||
|
|
||||||
|
// Search for Hack files if we are running on HHVM
|
||||||
|
if (false === $file && defined('HHVM_VERSION')) {
|
||||||
|
$file = $this->findFileWithExtension($class, '.hh');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (null !== $this->apcuPrefix) {
|
||||||
|
apcu_add($this->apcuPrefix.$class, $file);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false === $file) {
|
||||||
|
// Remember that this class does not exist.
|
||||||
|
$this->missingClasses[$class] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $file;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the currently registered loaders keyed by their corresponding vendor directories.
|
||||||
|
*
|
||||||
|
* @return array<string, self>
|
||||||
|
*/
|
||||||
|
public static function getRegisteredLoaders()
|
||||||
|
{
|
||||||
|
return self::$registeredLoaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $class
|
||||||
|
* @param string $ext
|
||||||
|
* @return string|false
|
||||||
|
*/
|
||||||
|
private function findFileWithExtension($class, $ext)
|
||||||
|
{
|
||||||
|
// PSR-4 lookup
|
||||||
|
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
|
||||||
|
|
||||||
|
$first = $class[0];
|
||||||
|
if (isset($this->prefixLengthsPsr4[$first])) {
|
||||||
|
$subPath = $class;
|
||||||
|
while (false !== $lastPos = strrpos($subPath, '\\')) {
|
||||||
|
$subPath = substr($subPath, 0, $lastPos);
|
||||||
|
$search = $subPath . '\\';
|
||||||
|
if (isset($this->prefixDirsPsr4[$search])) {
|
||||||
|
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
|
||||||
|
foreach ($this->prefixDirsPsr4[$search] as $dir) {
|
||||||
|
if (file_exists($file = $dir . $pathEnd)) {
|
||||||
|
return $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSR-4 fallback dirs
|
||||||
|
foreach ($this->fallbackDirsPsr4 as $dir) {
|
||||||
|
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
|
||||||
|
return $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSR-0 lookup
|
||||||
|
if (false !== $pos = strrpos($class, '\\')) {
|
||||||
|
// namespaced class name
|
||||||
|
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
|
||||||
|
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
|
||||||
|
} else {
|
||||||
|
// PEAR-like class name
|
||||||
|
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($this->prefixesPsr0[$first])) {
|
||||||
|
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
|
||||||
|
if (0 === strpos($class, $prefix)) {
|
||||||
|
foreach ($dirs as $dir) {
|
||||||
|
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
|
||||||
|
return $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSR-0 fallback dirs
|
||||||
|
foreach ($this->fallbackDirsPsr0 as $dir) {
|
||||||
|
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
|
||||||
|
return $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSR-0 include paths.
|
||||||
|
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
|
||||||
|
return $file;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function initializeIncludeClosure()
|
||||||
|
{
|
||||||
|
if (self::$includeFile !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scope isolated include.
|
||||||
|
*
|
||||||
|
* Prevents access to $this/self from included files.
|
||||||
|
*
|
||||||
|
* @param string $file
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
self::$includeFile = \Closure::bind(static function($file) {
|
||||||
|
include $file;
|
||||||
|
}, null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
+359
@@ -0,0 +1,359 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is part of Composer.
|
||||||
|
*
|
||||||
|
* (c) Nils Adermann <naderman@naderman.de>
|
||||||
|
* Jordi Boggiano <j.boggiano@seld.be>
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Composer;
|
||||||
|
|
||||||
|
use Composer\Autoload\ClassLoader;
|
||||||
|
use Composer\Semver\VersionParser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This class is copied in every Composer installed project and available to all
|
||||||
|
*
|
||||||
|
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
|
||||||
|
*
|
||||||
|
* To require its presence, you can require `composer-runtime-api ^2.0`
|
||||||
|
*
|
||||||
|
* @final
|
||||||
|
*/
|
||||||
|
class InstalledVersions
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var mixed[]|null
|
||||||
|
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
|
||||||
|
*/
|
||||||
|
private static $installed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var bool|null
|
||||||
|
*/
|
||||||
|
private static $canGetVendors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array[]
|
||||||
|
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||||
|
*/
|
||||||
|
private static $installedByVendor = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a list of all package names which are present, either by being installed, replaced or provided
|
||||||
|
*
|
||||||
|
* @return string[]
|
||||||
|
* @psalm-return list<string>
|
||||||
|
*/
|
||||||
|
public static function getInstalledPackages()
|
||||||
|
{
|
||||||
|
$packages = array();
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
$packages[] = array_keys($installed['versions']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (1 === \count($packages)) {
|
||||||
|
return $packages[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a list of all package names with a specific type e.g. 'library'
|
||||||
|
*
|
||||||
|
* @param string $type
|
||||||
|
* @return string[]
|
||||||
|
* @psalm-return list<string>
|
||||||
|
*/
|
||||||
|
public static function getInstalledPackagesByType($type)
|
||||||
|
{
|
||||||
|
$packagesByType = array();
|
||||||
|
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
foreach ($installed['versions'] as $name => $package) {
|
||||||
|
if (isset($package['type']) && $package['type'] === $type) {
|
||||||
|
$packagesByType[] = $name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $packagesByType;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether the given package is installed
|
||||||
|
*
|
||||||
|
* This also returns true if the package name is provided or replaced by another package
|
||||||
|
*
|
||||||
|
* @param string $packageName
|
||||||
|
* @param bool $includeDevRequirements
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public static function isInstalled($packageName, $includeDevRequirements = true)
|
||||||
|
{
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
if (isset($installed['versions'][$packageName])) {
|
||||||
|
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether the given package satisfies a version constraint
|
||||||
|
*
|
||||||
|
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
|
||||||
|
*
|
||||||
|
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
|
||||||
|
*
|
||||||
|
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
|
||||||
|
* @param string $packageName
|
||||||
|
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public static function satisfies(VersionParser $parser, $packageName, $constraint)
|
||||||
|
{
|
||||||
|
$constraint = $parser->parseConstraints((string) $constraint);
|
||||||
|
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
|
||||||
|
|
||||||
|
return $provided->matches($constraint);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a version constraint representing all the range(s) which are installed for a given package
|
||||||
|
*
|
||||||
|
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
|
||||||
|
* whether a given version of a package is installed, and not just whether it exists
|
||||||
|
*
|
||||||
|
* @param string $packageName
|
||||||
|
* @return string Version constraint usable with composer/semver
|
||||||
|
*/
|
||||||
|
public static function getVersionRanges($packageName)
|
||||||
|
{
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
if (!isset($installed['versions'][$packageName])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$ranges = array();
|
||||||
|
if (isset($installed['versions'][$packageName]['pretty_version'])) {
|
||||||
|
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
|
||||||
|
}
|
||||||
|
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
|
||||||
|
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
|
||||||
|
}
|
||||||
|
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
|
||||||
|
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
|
||||||
|
}
|
||||||
|
if (array_key_exists('provided', $installed['versions'][$packageName])) {
|
||||||
|
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode(' || ', $ranges);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $packageName
|
||||||
|
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
|
||||||
|
*/
|
||||||
|
public static function getVersion($packageName)
|
||||||
|
{
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
if (!isset($installed['versions'][$packageName])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($installed['versions'][$packageName]['version'])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $installed['versions'][$packageName]['version'];
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $packageName
|
||||||
|
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
|
||||||
|
*/
|
||||||
|
public static function getPrettyVersion($packageName)
|
||||||
|
{
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
if (!isset($installed['versions'][$packageName])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $installed['versions'][$packageName]['pretty_version'];
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $packageName
|
||||||
|
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
|
||||||
|
*/
|
||||||
|
public static function getReference($packageName)
|
||||||
|
{
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
if (!isset($installed['versions'][$packageName])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($installed['versions'][$packageName]['reference'])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $installed['versions'][$packageName]['reference'];
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $packageName
|
||||||
|
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
|
||||||
|
*/
|
||||||
|
public static function getInstallPath($packageName)
|
||||||
|
{
|
||||||
|
foreach (self::getInstalled() as $installed) {
|
||||||
|
if (!isset($installed['versions'][$packageName])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
|
||||||
|
*/
|
||||||
|
public static function getRootPackage()
|
||||||
|
{
|
||||||
|
$installed = self::getInstalled();
|
||||||
|
|
||||||
|
return $installed[0]['root'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the raw installed.php data for custom implementations
|
||||||
|
*
|
||||||
|
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
|
||||||
|
* @return array[]
|
||||||
|
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
|
||||||
|
*/
|
||||||
|
public static function getRawData()
|
||||||
|
{
|
||||||
|
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
|
||||||
|
|
||||||
|
if (null === self::$installed) {
|
||||||
|
// only require the installed.php file if this file is loaded from its dumped location,
|
||||||
|
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
|
||||||
|
if (substr(__DIR__, -8, 1) !== 'C') {
|
||||||
|
self::$installed = include __DIR__ . '/installed.php';
|
||||||
|
} else {
|
||||||
|
self::$installed = array();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::$installed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the raw data of all installed.php which are currently loaded for custom implementations
|
||||||
|
*
|
||||||
|
* @return array[]
|
||||||
|
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||||
|
*/
|
||||||
|
public static function getAllRawData()
|
||||||
|
{
|
||||||
|
return self::getInstalled();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lets you reload the static array from another file
|
||||||
|
*
|
||||||
|
* This is only useful for complex integrations in which a project needs to use
|
||||||
|
* this class but then also needs to execute another project's autoloader in process,
|
||||||
|
* and wants to ensure both projects have access to their version of installed.php.
|
||||||
|
*
|
||||||
|
* A typical case would be PHPUnit, where it would need to make sure it reads all
|
||||||
|
* the data it needs from this class, then call reload() with
|
||||||
|
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
|
||||||
|
* the project in which it runs can then also use this class safely, without
|
||||||
|
* interference between PHPUnit's dependencies and the project's dependencies.
|
||||||
|
*
|
||||||
|
* @param array[] $data A vendor/composer/installed.php data set
|
||||||
|
* @return void
|
||||||
|
*
|
||||||
|
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
|
||||||
|
*/
|
||||||
|
public static function reload($data)
|
||||||
|
{
|
||||||
|
self::$installed = $data;
|
||||||
|
self::$installedByVendor = array();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array[]
|
||||||
|
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||||
|
*/
|
||||||
|
private static function getInstalled()
|
||||||
|
{
|
||||||
|
if (null === self::$canGetVendors) {
|
||||||
|
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
|
||||||
|
}
|
||||||
|
|
||||||
|
$installed = array();
|
||||||
|
|
||||||
|
if (self::$canGetVendors) {
|
||||||
|
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
|
||||||
|
if (isset(self::$installedByVendor[$vendorDir])) {
|
||||||
|
$installed[] = self::$installedByVendor[$vendorDir];
|
||||||
|
} elseif (is_file($vendorDir.'/composer/installed.php')) {
|
||||||
|
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
|
||||||
|
$required = require $vendorDir.'/composer/installed.php';
|
||||||
|
$installed[] = self::$installedByVendor[$vendorDir] = $required;
|
||||||
|
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
|
||||||
|
self::$installed = $installed[count($installed) - 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (null === self::$installed) {
|
||||||
|
// only require the installed.php file if this file is loaded from its dumped location,
|
||||||
|
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
|
||||||
|
if (substr(__DIR__, -8, 1) !== 'C') {
|
||||||
|
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
|
||||||
|
$required = require __DIR__ . '/installed.php';
|
||||||
|
self::$installed = $required;
|
||||||
|
} else {
|
||||||
|
self::$installed = array();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self::$installed !== array()) {
|
||||||
|
$installed[] = self::$installed;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $installed;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+21
@@ -0,0 +1,21 @@
|
|||||||
|
|
||||||
|
Copyright (c) Nils Adermann, Jordi Boggiano
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is furnished
|
||||||
|
to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// autoload_classmap.php @generated by Composer
|
||||||
|
|
||||||
|
$vendorDir = dirname(__DIR__);
|
||||||
|
$baseDir = dirname($vendorDir);
|
||||||
|
|
||||||
|
return array(
|
||||||
|
'AllowDynamicProperties' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php',
|
||||||
|
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
|
||||||
|
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
|
||||||
|
'Nette\\ArgumentOutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\DeprecatedException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\DirectoryNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\FileNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\HtmlStringable' => $vendorDir . '/nette/utils/src/HtmlStringable.php',
|
||||||
|
'Nette\\IOException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\InvalidArgumentException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\InvalidStateException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\Iterators\\CachingIterator' => $vendorDir . '/nette/utils/src/Iterators/CachingIterator.php',
|
||||||
|
'Nette\\Iterators\\Mapper' => $vendorDir . '/nette/utils/src/Iterators/Mapper.php',
|
||||||
|
'Nette\\Localization\\ITranslator' => $vendorDir . '/nette/utils/src/compatibility.php',
|
||||||
|
'Nette\\Localization\\Translator' => $vendorDir . '/nette/utils/src/Translator.php',
|
||||||
|
'Nette\\MemberAccessException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\NotImplementedException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\NotSupportedException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\OutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\Schema\\Context' => $vendorDir . '/nette/schema/src/Schema/Context.php',
|
||||||
|
'Nette\\Schema\\DynamicParameter' => $vendorDir . '/nette/schema/src/Schema/DynamicParameter.php',
|
||||||
|
'Nette\\Schema\\Elements\\AnyOf' => $vendorDir . '/nette/schema/src/Schema/Elements/AnyOf.php',
|
||||||
|
'Nette\\Schema\\Elements\\ArrayType' => $vendorDir . '/nette/schema/src/Schema/Elements/ArrayType.php',
|
||||||
|
'Nette\\Schema\\Elements\\Base' => $vendorDir . '/nette/schema/src/Schema/Elements/Base.php',
|
||||||
|
'Nette\\Schema\\Elements\\EnumType' => $vendorDir . '/nette/schema/src/Schema/Elements/EnumType.php',
|
||||||
|
'Nette\\Schema\\Elements\\NumberType' => $vendorDir . '/nette/schema/src/Schema/Elements/NumberType.php',
|
||||||
|
'Nette\\Schema\\Elements\\StringType' => $vendorDir . '/nette/schema/src/Schema/Elements/StringType.php',
|
||||||
|
'Nette\\Schema\\Elements\\Structure' => $vendorDir . '/nette/schema/src/Schema/Elements/Structure.php',
|
||||||
|
'Nette\\Schema\\Elements\\TupleType' => $vendorDir . '/nette/schema/src/Schema/Elements/TupleType.php',
|
||||||
|
'Nette\\Schema\\Elements\\Type' => $vendorDir . '/nette/schema/src/Schema/Elements/Type.php',
|
||||||
|
'Nette\\Schema\\Expect' => $vendorDir . '/nette/schema/src/Schema/Expect.php',
|
||||||
|
'Nette\\Schema\\Helpers' => $vendorDir . '/nette/schema/src/Schema/Helpers.php',
|
||||||
|
'Nette\\Schema\\JsonSchema' => $vendorDir . '/nette/schema/src/Schema/JsonSchema.php',
|
||||||
|
'Nette\\Schema\\Kind' => $vendorDir . '/nette/schema/src/Schema/enums.php',
|
||||||
|
'Nette\\Schema\\MergeMode' => $vendorDir . '/nette/schema/src/Schema/enums.php',
|
||||||
|
'Nette\\Schema\\Message' => $vendorDir . '/nette/schema/src/Schema/Message.php',
|
||||||
|
'Nette\\Schema\\Processor' => $vendorDir . '/nette/schema/src/Schema/Processor.php',
|
||||||
|
'Nette\\Schema\\Schema' => $vendorDir . '/nette/schema/src/Schema/Schema.php',
|
||||||
|
'Nette\\Schema\\TypeExpression' => $vendorDir . '/nette/schema/src/Schema/TypeExpression.php',
|
||||||
|
'Nette\\Schema\\ValidationException' => $vendorDir . '/nette/schema/src/Schema/ValidationException.php',
|
||||||
|
'Nette\\ShouldNotHappenException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\SmartObject' => $vendorDir . '/nette/utils/src/SmartObject.php',
|
||||||
|
'Nette\\StaticClass' => $vendorDir . '/nette/utils/src/StaticClass.php',
|
||||||
|
'Nette\\UnexpectedValueException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\Utils\\ArrayHash' => $vendorDir . '/nette/utils/src/Utils/ArrayHash.php',
|
||||||
|
'Nette\\Utils\\ArrayList' => $vendorDir . '/nette/utils/src/Utils/ArrayList.php',
|
||||||
|
'Nette\\Utils\\Arrays' => $vendorDir . '/nette/utils/src/Utils/Arrays.php',
|
||||||
|
'Nette\\Utils\\AssertionException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Callback' => $vendorDir . '/nette/utils/src/Utils/Callback.php',
|
||||||
|
'Nette\\Utils\\DateTime' => $vendorDir . '/nette/utils/src/Utils/DateTime.php',
|
||||||
|
'Nette\\Utils\\DateTimeImmutable' => $vendorDir . '/nette/utils/src/Utils/DateTimeImmutable.php',
|
||||||
|
'Nette\\Utils\\FileInfo' => $vendorDir . '/nette/utils/src/Utils/FileInfo.php',
|
||||||
|
'Nette\\Utils\\FileSystem' => $vendorDir . '/nette/utils/src/Utils/FileSystem.php',
|
||||||
|
'Nette\\Utils\\Finder' => $vendorDir . '/nette/utils/src/Utils/Finder.php',
|
||||||
|
'Nette\\Utils\\Floats' => $vendorDir . '/nette/utils/src/Utils/Floats.php',
|
||||||
|
'Nette\\Utils\\Helpers' => $vendorDir . '/nette/utils/src/Utils/Helpers.php',
|
||||||
|
'Nette\\Utils\\Html' => $vendorDir . '/nette/utils/src/Utils/Html.php',
|
||||||
|
'Nette\\Utils\\IHtmlString' => $vendorDir . '/nette/utils/src/compatibility.php',
|
||||||
|
'Nette\\Utils\\Image' => $vendorDir . '/nette/utils/src/Utils/Image.php',
|
||||||
|
'Nette\\Utils\\ImageColor' => $vendorDir . '/nette/utils/src/Utils/ImageColor.php',
|
||||||
|
'Nette\\Utils\\ImageException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\ImageType' => $vendorDir . '/nette/utils/src/Utils/ImageType.php',
|
||||||
|
'Nette\\Utils\\Iterables' => $vendorDir . '/nette/utils/src/Utils/Iterables.php',
|
||||||
|
'Nette\\Utils\\Json' => $vendorDir . '/nette/utils/src/Utils/Json.php',
|
||||||
|
'Nette\\Utils\\JsonException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\ObjectHelpers' => $vendorDir . '/nette/utils/src/Utils/ObjectHelpers.php',
|
||||||
|
'Nette\\Utils\\Paginator' => $vendorDir . '/nette/utils/src/Utils/Paginator.php',
|
||||||
|
'Nette\\Utils\\Process' => $vendorDir . '/nette/utils/src/Utils/Process.php',
|
||||||
|
'Nette\\Utils\\ProcessFailedException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\ProcessTimeoutException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Random' => $vendorDir . '/nette/utils/src/Utils/Random.php',
|
||||||
|
'Nette\\Utils\\Reflection' => $vendorDir . '/nette/utils/src/Utils/Reflection.php',
|
||||||
|
'Nette\\Utils\\ReflectionMethod' => $vendorDir . '/nette/utils/src/Utils/ReflectionMethod.php',
|
||||||
|
'Nette\\Utils\\RegexpException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Strings' => $vendorDir . '/nette/utils/src/Utils/Strings.php',
|
||||||
|
'Nette\\Utils\\Type' => $vendorDir . '/nette/utils/src/Utils/Type.php',
|
||||||
|
'Nette\\Utils\\UnknownImageFileException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Validators' => $vendorDir . '/nette/utils/src/Utils/Validators.php',
|
||||||
|
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
|
||||||
|
'Random\\BrokenRandomEngineError' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php',
|
||||||
|
'Random\\CryptoSafeEngine' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php',
|
||||||
|
'Random\\Engine' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/Engine.php',
|
||||||
|
'Random\\Engine\\Secure' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php',
|
||||||
|
'Random\\RandomError' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php',
|
||||||
|
'Random\\RandomException' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php',
|
||||||
|
'SensitiveParameter' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php',
|
||||||
|
'SensitiveParameterValue' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php',
|
||||||
|
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
|
||||||
|
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
|
||||||
|
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
|
||||||
|
);
|
||||||
Vendored
+16
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// autoload_files.php @generated by Composer
|
||||||
|
|
||||||
|
$vendorDir = dirname(__DIR__);
|
||||||
|
$baseDir = dirname($vendorDir);
|
||||||
|
|
||||||
|
return array(
|
||||||
|
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
|
||||||
|
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
|
||||||
|
'5897ea0ac4cccf14d323035e65887801' => $vendorDir . '/symfony/polyfill-php82/bootstrap.php',
|
||||||
|
'253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php',
|
||||||
|
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
|
||||||
|
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
|
||||||
|
'd2136ff22b54ac75cd96a40e0022218e' => $vendorDir . '/workerman/webman-framework/src/support/helpers.php',
|
||||||
|
);
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// autoload_namespaces.php @generated by Composer
|
||||||
|
|
||||||
|
$vendorDir = dirname(__DIR__);
|
||||||
|
$baseDir = dirname($vendorDir);
|
||||||
|
|
||||||
|
return array(
|
||||||
|
);
|
||||||
Vendored
+41
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// autoload_psr4.php @generated by Composer
|
||||||
|
|
||||||
|
$vendorDir = dirname(__DIR__);
|
||||||
|
$baseDir = dirname($vendorDir);
|
||||||
|
|
||||||
|
return array(
|
||||||
|
'support\\' => array($vendorDir . '/workerman/webman-framework/src/support'),
|
||||||
|
'Workerman\\Coroutine\\' => array($vendorDir . '/workerman/coroutine/src'),
|
||||||
|
'Workerman\\' => array($vendorDir . '/workerman/coroutine/src', $vendorDir . '/workerman/workerman/src'),
|
||||||
|
'Webman\\' => array($vendorDir . '/workerman/webman-framework/src'),
|
||||||
|
'Symfony\\Polyfill\\Php82\\' => array($vendorDir . '/symfony/polyfill-php82'),
|
||||||
|
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
|
||||||
|
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
|
||||||
|
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
|
||||||
|
'Support\\View\\' => array($vendorDir . '/workerman/webman-framework/src/support/view'),
|
||||||
|
'Support\\Exception\\' => array($vendorDir . '/workerman/webman-framework/src/support/exception'),
|
||||||
|
'Support\\Bootstrap\\' => array($vendorDir . '/workerman/webman-framework/src/support/bootstrap'),
|
||||||
|
'Support\\' => array($vendorDir . '/workerman/webman-framework/src/support'),
|
||||||
|
'Psr\\Log\\' => array($vendorDir . '/psr/log/src'),
|
||||||
|
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'),
|
||||||
|
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
|
||||||
|
'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'),
|
||||||
|
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
|
||||||
|
'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'),
|
||||||
|
'Nette\\' => array($vendorDir . '/nette/schema/src', $vendorDir . '/nette/utils/src'),
|
||||||
|
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
|
||||||
|
'League\\OAuth2\\Client\\' => array($vendorDir . '/league/oauth2-client/src'),
|
||||||
|
'League\\Config\\' => array($vendorDir . '/league/config/src'),
|
||||||
|
'League\\CommonMark\\' => array($vendorDir . '/league/commonmark/src'),
|
||||||
|
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
|
||||||
|
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
|
||||||
|
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
|
||||||
|
'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'),
|
||||||
|
'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'),
|
||||||
|
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
|
||||||
|
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
|
||||||
|
'Dflydev\\DotAccessData\\' => array($vendorDir . '/dflydev/dot-access-data/src'),
|
||||||
|
'App\\' => array($baseDir . '/app'),
|
||||||
|
);
|
||||||
Vendored
+50
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// autoload_real.php @generated by Composer
|
||||||
|
|
||||||
|
class ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56
|
||||||
|
{
|
||||||
|
private static $loader;
|
||||||
|
|
||||||
|
public static function loadClassLoader($class)
|
||||||
|
{
|
||||||
|
if ('Composer\Autoload\ClassLoader' === $class) {
|
||||||
|
require __DIR__ . '/ClassLoader.php';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return \Composer\Autoload\ClassLoader
|
||||||
|
*/
|
||||||
|
public static function getLoader()
|
||||||
|
{
|
||||||
|
if (null !== self::$loader) {
|
||||||
|
return self::$loader;
|
||||||
|
}
|
||||||
|
|
||||||
|
require __DIR__ . '/platform_check.php';
|
||||||
|
|
||||||
|
spl_autoload_register(array('ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56', 'loadClassLoader'), true, true);
|
||||||
|
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
|
||||||
|
spl_autoload_unregister(array('ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56', 'loadClassLoader'));
|
||||||
|
|
||||||
|
require __DIR__ . '/autoload_static.php';
|
||||||
|
call_user_func(\Composer\Autoload\ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::getInitializer($loader));
|
||||||
|
|
||||||
|
$loader->register(true);
|
||||||
|
|
||||||
|
$filesToLoad = \Composer\Autoload\ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$files;
|
||||||
|
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
|
||||||
|
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
|
||||||
|
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
|
||||||
|
|
||||||
|
require $file;
|
||||||
|
}
|
||||||
|
}, null, null);
|
||||||
|
foreach ($filesToLoad as $fileIdentifier => $file) {
|
||||||
|
$requireFile($fileIdentifier, $file);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $loader;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+323
@@ -0,0 +1,323 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// autoload_static.php @generated by Composer
|
||||||
|
|
||||||
|
namespace Composer\Autoload;
|
||||||
|
|
||||||
|
class ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56
|
||||||
|
{
|
||||||
|
public static $files = array (
|
||||||
|
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
|
||||||
|
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
|
||||||
|
'5897ea0ac4cccf14d323035e65887801' => __DIR__ . '/..' . '/symfony/polyfill-php82/bootstrap.php',
|
||||||
|
'253c157292f75eb38082b5acb06f3f01' => __DIR__ . '/..' . '/nikic/fast-route/src/functions.php',
|
||||||
|
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
|
||||||
|
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
|
||||||
|
'd2136ff22b54ac75cd96a40e0022218e' => __DIR__ . '/..' . '/workerman/webman-framework/src/support/helpers.php',
|
||||||
|
);
|
||||||
|
|
||||||
|
public static $prefixLengthsPsr4 = array (
|
||||||
|
's' =>
|
||||||
|
array (
|
||||||
|
'support\\' => 8,
|
||||||
|
),
|
||||||
|
'W' =>
|
||||||
|
array (
|
||||||
|
'Workerman\\Coroutine\\' => 20,
|
||||||
|
'Workerman\\' => 10,
|
||||||
|
'Webman\\' => 7,
|
||||||
|
),
|
||||||
|
'S' =>
|
||||||
|
array (
|
||||||
|
'Symfony\\Polyfill\\Php82\\' => 23,
|
||||||
|
'Symfony\\Polyfill\\Php80\\' => 23,
|
||||||
|
'Symfony\\Polyfill\\Mbstring\\' => 26,
|
||||||
|
'Symfony\\Polyfill\\Ctype\\' => 23,
|
||||||
|
'Support\\View\\' => 13,
|
||||||
|
'Support\\Exception\\' => 18,
|
||||||
|
'Support\\Bootstrap\\' => 18,
|
||||||
|
'Support\\' => 8,
|
||||||
|
),
|
||||||
|
'P' =>
|
||||||
|
array (
|
||||||
|
'Psr\\Log\\' => 8,
|
||||||
|
'Psr\\Http\\Message\\' => 17,
|
||||||
|
'Psr\\Http\\Client\\' => 16,
|
||||||
|
'Psr\\EventDispatcher\\' => 20,
|
||||||
|
'Psr\\Container\\' => 14,
|
||||||
|
'PhpOption\\' => 10,
|
||||||
|
),
|
||||||
|
'N' =>
|
||||||
|
array (
|
||||||
|
'Nette\\' => 6,
|
||||||
|
),
|
||||||
|
'M' =>
|
||||||
|
array (
|
||||||
|
'Monolog\\' => 8,
|
||||||
|
),
|
||||||
|
'L' =>
|
||||||
|
array (
|
||||||
|
'League\\OAuth2\\Client\\' => 21,
|
||||||
|
'League\\Config\\' => 14,
|
||||||
|
'League\\CommonMark\\' => 18,
|
||||||
|
),
|
||||||
|
'G' =>
|
||||||
|
array (
|
||||||
|
'GuzzleHttp\\Psr7\\' => 16,
|
||||||
|
'GuzzleHttp\\Promise\\' => 19,
|
||||||
|
'GuzzleHttp\\' => 11,
|
||||||
|
'GrahamCampbell\\ResultType\\' => 26,
|
||||||
|
),
|
||||||
|
'F' =>
|
||||||
|
array (
|
||||||
|
'Firebase\\JWT\\' => 13,
|
||||||
|
'FastRoute\\' => 10,
|
||||||
|
),
|
||||||
|
'D' =>
|
||||||
|
array (
|
||||||
|
'Dotenv\\' => 7,
|
||||||
|
'Dflydev\\DotAccessData\\' => 22,
|
||||||
|
),
|
||||||
|
'A' =>
|
||||||
|
array (
|
||||||
|
'App\\' => 4,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
public static $prefixDirsPsr4 = array (
|
||||||
|
'support\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support',
|
||||||
|
),
|
||||||
|
'Workerman\\Coroutine\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/coroutine/src',
|
||||||
|
),
|
||||||
|
'Workerman\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/coroutine/src',
|
||||||
|
1 => __DIR__ . '/..' . '/workerman/workerman/src',
|
||||||
|
),
|
||||||
|
'Webman\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/webman-framework/src',
|
||||||
|
),
|
||||||
|
'Symfony\\Polyfill\\Php82\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/symfony/polyfill-php82',
|
||||||
|
),
|
||||||
|
'Symfony\\Polyfill\\Php80\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
|
||||||
|
),
|
||||||
|
'Symfony\\Polyfill\\Mbstring\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
|
||||||
|
),
|
||||||
|
'Symfony\\Polyfill\\Ctype\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
|
||||||
|
),
|
||||||
|
'Support\\View\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/view',
|
||||||
|
),
|
||||||
|
'Support\\Exception\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/exception',
|
||||||
|
),
|
||||||
|
'Support\\Bootstrap\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/bootstrap',
|
||||||
|
),
|
||||||
|
'Support\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support',
|
||||||
|
),
|
||||||
|
'Psr\\Log\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/psr/log/src',
|
||||||
|
),
|
||||||
|
'Psr\\Http\\Message\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/psr/http-message/src',
|
||||||
|
1 => __DIR__ . '/..' . '/psr/http-factory/src',
|
||||||
|
),
|
||||||
|
'Psr\\Http\\Client\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/psr/http-client/src',
|
||||||
|
),
|
||||||
|
'Psr\\EventDispatcher\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/psr/event-dispatcher/src',
|
||||||
|
),
|
||||||
|
'Psr\\Container\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/psr/container/src',
|
||||||
|
),
|
||||||
|
'PhpOption\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption',
|
||||||
|
),
|
||||||
|
'Nette\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/nette/schema/src',
|
||||||
|
1 => __DIR__ . '/..' . '/nette/utils/src',
|
||||||
|
),
|
||||||
|
'Monolog\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
|
||||||
|
),
|
||||||
|
'League\\OAuth2\\Client\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/league/oauth2-client/src',
|
||||||
|
),
|
||||||
|
'League\\Config\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/league/config/src',
|
||||||
|
),
|
||||||
|
'League\\CommonMark\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/league/commonmark/src',
|
||||||
|
),
|
||||||
|
'GuzzleHttp\\Psr7\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
|
||||||
|
),
|
||||||
|
'GuzzleHttp\\Promise\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/guzzlehttp/promises/src',
|
||||||
|
),
|
||||||
|
'GuzzleHttp\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src',
|
||||||
|
),
|
||||||
|
'GrahamCampbell\\ResultType\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/graham-campbell/result-type/src',
|
||||||
|
),
|
||||||
|
'Firebase\\JWT\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/firebase/php-jwt/src',
|
||||||
|
),
|
||||||
|
'FastRoute\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/nikic/fast-route/src',
|
||||||
|
),
|
||||||
|
'Dotenv\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src',
|
||||||
|
),
|
||||||
|
'Dflydev\\DotAccessData\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/..' . '/dflydev/dot-access-data/src',
|
||||||
|
),
|
||||||
|
'App\\' =>
|
||||||
|
array (
|
||||||
|
0 => __DIR__ . '/../..' . '/app',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
public static $classMap = array (
|
||||||
|
'AllowDynamicProperties' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php',
|
||||||
|
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
|
||||||
|
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
|
||||||
|
'Nette\\ArgumentOutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\DeprecatedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\DirectoryNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\FileNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\HtmlStringable' => __DIR__ . '/..' . '/nette/utils/src/HtmlStringable.php',
|
||||||
|
'Nette\\IOException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\InvalidArgumentException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\InvalidStateException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\Iterators\\CachingIterator' => __DIR__ . '/..' . '/nette/utils/src/Iterators/CachingIterator.php',
|
||||||
|
'Nette\\Iterators\\Mapper' => __DIR__ . '/..' . '/nette/utils/src/Iterators/Mapper.php',
|
||||||
|
'Nette\\Localization\\ITranslator' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php',
|
||||||
|
'Nette\\Localization\\Translator' => __DIR__ . '/..' . '/nette/utils/src/Translator.php',
|
||||||
|
'Nette\\MemberAccessException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\NotImplementedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\NotSupportedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\OutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\Schema\\Context' => __DIR__ . '/..' . '/nette/schema/src/Schema/Context.php',
|
||||||
|
'Nette\\Schema\\DynamicParameter' => __DIR__ . '/..' . '/nette/schema/src/Schema/DynamicParameter.php',
|
||||||
|
'Nette\\Schema\\Elements\\AnyOf' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/AnyOf.php',
|
||||||
|
'Nette\\Schema\\Elements\\ArrayType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/ArrayType.php',
|
||||||
|
'Nette\\Schema\\Elements\\Base' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Base.php',
|
||||||
|
'Nette\\Schema\\Elements\\EnumType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/EnumType.php',
|
||||||
|
'Nette\\Schema\\Elements\\NumberType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/NumberType.php',
|
||||||
|
'Nette\\Schema\\Elements\\StringType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/StringType.php',
|
||||||
|
'Nette\\Schema\\Elements\\Structure' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Structure.php',
|
||||||
|
'Nette\\Schema\\Elements\\TupleType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/TupleType.php',
|
||||||
|
'Nette\\Schema\\Elements\\Type' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Type.php',
|
||||||
|
'Nette\\Schema\\Expect' => __DIR__ . '/..' . '/nette/schema/src/Schema/Expect.php',
|
||||||
|
'Nette\\Schema\\Helpers' => __DIR__ . '/..' . '/nette/schema/src/Schema/Helpers.php',
|
||||||
|
'Nette\\Schema\\JsonSchema' => __DIR__ . '/..' . '/nette/schema/src/Schema/JsonSchema.php',
|
||||||
|
'Nette\\Schema\\Kind' => __DIR__ . '/..' . '/nette/schema/src/Schema/enums.php',
|
||||||
|
'Nette\\Schema\\MergeMode' => __DIR__ . '/..' . '/nette/schema/src/Schema/enums.php',
|
||||||
|
'Nette\\Schema\\Message' => __DIR__ . '/..' . '/nette/schema/src/Schema/Message.php',
|
||||||
|
'Nette\\Schema\\Processor' => __DIR__ . '/..' . '/nette/schema/src/Schema/Processor.php',
|
||||||
|
'Nette\\Schema\\Schema' => __DIR__ . '/..' . '/nette/schema/src/Schema/Schema.php',
|
||||||
|
'Nette\\Schema\\TypeExpression' => __DIR__ . '/..' . '/nette/schema/src/Schema/TypeExpression.php',
|
||||||
|
'Nette\\Schema\\ValidationException' => __DIR__ . '/..' . '/nette/schema/src/Schema/ValidationException.php',
|
||||||
|
'Nette\\ShouldNotHappenException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\SmartObject' => __DIR__ . '/..' . '/nette/utils/src/SmartObject.php',
|
||||||
|
'Nette\\StaticClass' => __DIR__ . '/..' . '/nette/utils/src/StaticClass.php',
|
||||||
|
'Nette\\UnexpectedValueException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||||
|
'Nette\\Utils\\ArrayHash' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayHash.php',
|
||||||
|
'Nette\\Utils\\ArrayList' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayList.php',
|
||||||
|
'Nette\\Utils\\Arrays' => __DIR__ . '/..' . '/nette/utils/src/Utils/Arrays.php',
|
||||||
|
'Nette\\Utils\\AssertionException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Callback' => __DIR__ . '/..' . '/nette/utils/src/Utils/Callback.php',
|
||||||
|
'Nette\\Utils\\DateTime' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTime.php',
|
||||||
|
'Nette\\Utils\\DateTimeImmutable' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTimeImmutable.php',
|
||||||
|
'Nette\\Utils\\FileInfo' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileInfo.php',
|
||||||
|
'Nette\\Utils\\FileSystem' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileSystem.php',
|
||||||
|
'Nette\\Utils\\Finder' => __DIR__ . '/..' . '/nette/utils/src/Utils/Finder.php',
|
||||||
|
'Nette\\Utils\\Floats' => __DIR__ . '/..' . '/nette/utils/src/Utils/Floats.php',
|
||||||
|
'Nette\\Utils\\Helpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/Helpers.php',
|
||||||
|
'Nette\\Utils\\Html' => __DIR__ . '/..' . '/nette/utils/src/Utils/Html.php',
|
||||||
|
'Nette\\Utils\\IHtmlString' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php',
|
||||||
|
'Nette\\Utils\\Image' => __DIR__ . '/..' . '/nette/utils/src/Utils/Image.php',
|
||||||
|
'Nette\\Utils\\ImageColor' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageColor.php',
|
||||||
|
'Nette\\Utils\\ImageException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\ImageType' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageType.php',
|
||||||
|
'Nette\\Utils\\Iterables' => __DIR__ . '/..' . '/nette/utils/src/Utils/Iterables.php',
|
||||||
|
'Nette\\Utils\\Json' => __DIR__ . '/..' . '/nette/utils/src/Utils/Json.php',
|
||||||
|
'Nette\\Utils\\JsonException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\ObjectHelpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectHelpers.php',
|
||||||
|
'Nette\\Utils\\Paginator' => __DIR__ . '/..' . '/nette/utils/src/Utils/Paginator.php',
|
||||||
|
'Nette\\Utils\\Process' => __DIR__ . '/..' . '/nette/utils/src/Utils/Process.php',
|
||||||
|
'Nette\\Utils\\ProcessFailedException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\ProcessTimeoutException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Random' => __DIR__ . '/..' . '/nette/utils/src/Utils/Random.php',
|
||||||
|
'Nette\\Utils\\Reflection' => __DIR__ . '/..' . '/nette/utils/src/Utils/Reflection.php',
|
||||||
|
'Nette\\Utils\\ReflectionMethod' => __DIR__ . '/..' . '/nette/utils/src/Utils/ReflectionMethod.php',
|
||||||
|
'Nette\\Utils\\RegexpException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Strings' => __DIR__ . '/..' . '/nette/utils/src/Utils/Strings.php',
|
||||||
|
'Nette\\Utils\\Type' => __DIR__ . '/..' . '/nette/utils/src/Utils/Type.php',
|
||||||
|
'Nette\\Utils\\UnknownImageFileException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||||
|
'Nette\\Utils\\Validators' => __DIR__ . '/..' . '/nette/utils/src/Utils/Validators.php',
|
||||||
|
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
|
||||||
|
'Random\\BrokenRandomEngineError' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php',
|
||||||
|
'Random\\CryptoSafeEngine' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php',
|
||||||
|
'Random\\Engine' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/Engine.php',
|
||||||
|
'Random\\Engine\\Secure' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php',
|
||||||
|
'Random\\RandomError' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php',
|
||||||
|
'Random\\RandomException' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php',
|
||||||
|
'SensitiveParameter' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php',
|
||||||
|
'SensitiveParameterValue' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php',
|
||||||
|
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
|
||||||
|
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
|
||||||
|
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
|
||||||
|
);
|
||||||
|
|
||||||
|
public static function getInitializer(ClassLoader $loader)
|
||||||
|
{
|
||||||
|
return \Closure::bind(function () use ($loader) {
|
||||||
|
$loader->prefixLengthsPsr4 = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$prefixLengthsPsr4;
|
||||||
|
$loader->prefixDirsPsr4 = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$prefixDirsPsr4;
|
||||||
|
$loader->classMap = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$classMap;
|
||||||
|
|
||||||
|
}, null, ClassLoader::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+2266
File diff suppressed because it is too large
Load Diff
Vendored
+308
@@ -0,0 +1,308 @@
|
|||||||
|
<?php return array(
|
||||||
|
'root' => array(
|
||||||
|
'name' => 'laysense/laysite',
|
||||||
|
'pretty_version' => 'dev-main',
|
||||||
|
'version' => 'dev-main',
|
||||||
|
'reference' => '89f363186becd5bb733f30901af79903f47c9627',
|
||||||
|
'type' => 'project',
|
||||||
|
'install_path' => __DIR__ . '/../../',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev' => true,
|
||||||
|
),
|
||||||
|
'versions' => array(
|
||||||
|
'dflydev/dot-access-data' => array(
|
||||||
|
'pretty_version' => 'v3.0.3',
|
||||||
|
'version' => '3.0.3.0',
|
||||||
|
'reference' => 'a23a2bf4f31d3518f3ecb38660c95715dfead60f',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../dflydev/dot-access-data',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'firebase/php-jwt' => array(
|
||||||
|
'pretty_version' => 'v7.2.2',
|
||||||
|
'version' => '7.2.2.0',
|
||||||
|
'reference' => '99efeb17d6def8c0295777f2d45b07ff4fdb4e40',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../firebase/php-jwt',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'graham-campbell/result-type' => array(
|
||||||
|
'pretty_version' => 'v1.2.0',
|
||||||
|
'version' => '1.2.0.0',
|
||||||
|
'reference' => 'adccca3324eece92ca35463648c12b9e6293c05b',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../graham-campbell/result-type',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'guzzlehttp/guzzle' => array(
|
||||||
|
'pretty_version' => '8.5.5',
|
||||||
|
'version' => '8.5.5.0',
|
||||||
|
'reference' => 'd1a26e6ce24268e740af501de8748d1c945e6f4b',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../guzzlehttp/guzzle',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'guzzlehttp/promises' => array(
|
||||||
|
'pretty_version' => '3.2.0',
|
||||||
|
'version' => '3.2.0.0',
|
||||||
|
'reference' => 'a201cc78db93065f891278f86eaeaa1c97c5a158',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../guzzlehttp/promises',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'guzzlehttp/psr7' => array(
|
||||||
|
'pretty_version' => '3.6.0',
|
||||||
|
'version' => '3.6.0.0',
|
||||||
|
'reference' => '1fa0f8319c046b7dec80030460254283d851388e',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../guzzlehttp/psr7',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'laysense/laysite' => array(
|
||||||
|
'pretty_version' => 'dev-main',
|
||||||
|
'version' => 'dev-main',
|
||||||
|
'reference' => '89f363186becd5bb733f30901af79903f47c9627',
|
||||||
|
'type' => 'project',
|
||||||
|
'install_path' => __DIR__ . '/../../',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'league/commonmark' => array(
|
||||||
|
'pretty_version' => '2.10.7',
|
||||||
|
'version' => '2.10.7.0',
|
||||||
|
'reference' => '8eb53e906fd60c67038d22f1f1cab420ed58b8be',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../league/commonmark',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'league/config' => array(
|
||||||
|
'pretty_version' => 'v1.2.0',
|
||||||
|
'version' => '1.2.0.0',
|
||||||
|
'reference' => '754b3604fb2984c71f4af4a9cbe7b57f346ec1f3',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../league/config',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'league/oauth2-client' => array(
|
||||||
|
'pretty_version' => '2.10.0',
|
||||||
|
'version' => '2.10.0.0',
|
||||||
|
'reference' => '25d240c6804f975909f8cdd131345949d8642535',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../league/oauth2-client',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'monolog/monolog' => array(
|
||||||
|
'pretty_version' => '3.13.0',
|
||||||
|
'version' => '3.13.0.0',
|
||||||
|
'reference' => '1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../monolog/monolog',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'nette/schema' => array(
|
||||||
|
'pretty_version' => 'v1.4.0',
|
||||||
|
'version' => '1.4.0.0',
|
||||||
|
'reference' => 'af9fa8a86bfca9b02b10346220db26e62ef942ec',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../nette/schema',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'nette/utils' => array(
|
||||||
|
'pretty_version' => 'v4.1.6',
|
||||||
|
'version' => '4.1.6.0',
|
||||||
|
'reference' => '6bf24518accf32cf845bca305e0b92078700fd01',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../nette/utils',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'nikic/fast-route' => array(
|
||||||
|
'pretty_version' => '1.3.1',
|
||||||
|
'version' => '1.3.1.0',
|
||||||
|
'reference' => '7476684f39bb9124b3be69ed3d84b66723920298',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../nikic/fast-route',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'phpoption/phpoption' => array(
|
||||||
|
'pretty_version' => '1.10.0',
|
||||||
|
'version' => '1.10.0.0',
|
||||||
|
'reference' => '67b192b6a42ec03944b972d6e633ddec78ad2c6d',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../phpoption/phpoption',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'psr/container' => array(
|
||||||
|
'pretty_version' => '2.0.2',
|
||||||
|
'version' => '2.0.2.0',
|
||||||
|
'reference' => 'c71ecc56dfe541dbd90c5360474fbc405f8d5963',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../psr/container',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'psr/event-dispatcher' => array(
|
||||||
|
'pretty_version' => '1.0.0',
|
||||||
|
'version' => '1.0.0.0',
|
||||||
|
'reference' => 'dbefd12671e8a14ec7f180cab83036ed26714bb0',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../psr/event-dispatcher',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'psr/http-client' => array(
|
||||||
|
'pretty_version' => '1.0.3',
|
||||||
|
'version' => '1.0.3.0',
|
||||||
|
'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../psr/http-client',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'psr/http-client-implementation' => array(
|
||||||
|
'dev_requirement' => false,
|
||||||
|
'provided' => array(
|
||||||
|
0 => '1.0',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
'psr/http-factory' => array(
|
||||||
|
'pretty_version' => '1.1.0',
|
||||||
|
'version' => '1.1.0.0',
|
||||||
|
'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../psr/http-factory',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'psr/http-factory-implementation' => array(
|
||||||
|
'dev_requirement' => false,
|
||||||
|
'provided' => array(
|
||||||
|
0 => '1.1',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
'psr/http-message' => array(
|
||||||
|
'pretty_version' => '2.0',
|
||||||
|
'version' => '2.0.0.0',
|
||||||
|
'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../psr/http-message',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'psr/http-message-implementation' => array(
|
||||||
|
'dev_requirement' => false,
|
||||||
|
'provided' => array(
|
||||||
|
0 => '2.0',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
'psr/log' => array(
|
||||||
|
'pretty_version' => '3.0.2',
|
||||||
|
'version' => '3.0.2.0',
|
||||||
|
'reference' => 'f16e1d5863e37f8d8c2a01719f5b34baa2b714d3',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../psr/log',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'psr/log-implementation' => array(
|
||||||
|
'dev_requirement' => false,
|
||||||
|
'provided' => array(
|
||||||
|
0 => '3.0.0',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
'symfony/deprecation-contracts' => array(
|
||||||
|
'pretty_version' => 'v3.8.1',
|
||||||
|
'version' => '3.8.1.0',
|
||||||
|
'reference' => 'feb1edf4e546af3b85c5caebe8359a20db230ca3',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../symfony/deprecation-contracts',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'symfony/polyfill-ctype' => array(
|
||||||
|
'pretty_version' => 'v1.37.0',
|
||||||
|
'version' => '1.37.0.0',
|
||||||
|
'reference' => '141046a8f9477948ff284fa65be2095baafb94f2',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../symfony/polyfill-ctype',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'symfony/polyfill-mbstring' => array(
|
||||||
|
'pretty_version' => 'v1.43.3',
|
||||||
|
'version' => '1.43.3.0',
|
||||||
|
'reference' => '122889ed24dc000165bcbfd77ec412f15cbdfc6a',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'symfony/polyfill-php80' => array(
|
||||||
|
'pretty_version' => 'v1.43.0',
|
||||||
|
'version' => '1.43.0.0',
|
||||||
|
'reference' => '9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'symfony/polyfill-php82' => array(
|
||||||
|
'pretty_version' => 'v1.43.0',
|
||||||
|
'version' => '1.43.0.0',
|
||||||
|
'reference' => '843bbe8b2a7934307b749751eede0f111f5d1cfc',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../symfony/polyfill-php82',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'vlucas/phpdotenv' => array(
|
||||||
|
'pretty_version' => 'v5.8.1',
|
||||||
|
'version' => '5.8.1.0',
|
||||||
|
'reference' => 'ba37876e98122ca15151247ce1187d20ee8bf4e0',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../vlucas/phpdotenv',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'workerman/coroutine' => array(
|
||||||
|
'pretty_version' => 'v1.1.7',
|
||||||
|
'version' => '1.1.7.0',
|
||||||
|
'reference' => '68a905d50f7ec1efcedc1ec317a75dcc3dea3f0f',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../workerman/coroutine',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'workerman/webman-framework' => array(
|
||||||
|
'pretty_version' => 'v2.2.5',
|
||||||
|
'version' => '2.2.5.0',
|
||||||
|
'reference' => '263ef955d8ba6a0cb6fbc1bd0912589ed67c0c8d',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../workerman/webman-framework',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
'workerman/workerman' => array(
|
||||||
|
'pretty_version' => 'v5.2.4',
|
||||||
|
'version' => '5.2.4.0',
|
||||||
|
'reference' => '4c817dec82c9ea223879b019600db58f62199abc',
|
||||||
|
'type' => 'library',
|
||||||
|
'install_path' => __DIR__ . '/../workerman/workerman',
|
||||||
|
'aliases' => array(),
|
||||||
|
'dev_requirement' => false,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
Vendored
+26
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// platform_check.php @generated by Composer
|
||||||
|
|
||||||
|
$issues = array();
|
||||||
|
|
||||||
|
if (!(PHP_VERSION_ID >= 80200)) {
|
||||||
|
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($issues) {
|
||||||
|
if (!headers_sent()) {
|
||||||
|
header('HTTP/1.1 500 Internal Server Error');
|
||||||
|
}
|
||||||
|
if (!ini_get('display_errors')) {
|
||||||
|
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
|
||||||
|
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
|
||||||
|
} elseif (!headers_sent()) {
|
||||||
|
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trigger_error(
|
||||||
|
'Composer detected issues in your platform: ' . implode(' ', $issues),
|
||||||
|
E_USER_ERROR
|
||||||
|
);
|
||||||
|
}
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [3.0.3] - 2024-07-08
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed PHP 8.4 deprecation notices (#47)
|
||||||
|
|
||||||
|
## [3.0.2] - 2022-10-27
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Added missing return types to docblocks (#44, #45)
|
||||||
|
|
||||||
|
## [3.0.1] - 2021-08-13
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Adds ReturnTypeWillChange to suppress PHP 8.1 warnings (#40)
|
||||||
|
|
||||||
|
## [3.0.0] - 2021-01-01
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added support for both `.` and `/`-delimited key paths (#24)
|
||||||
|
- Added parameter and return types to everything; enabled strict type checks (#18)
|
||||||
|
- Added new exception classes to better identify certain types of errors (#20)
|
||||||
|
- `Data` now implements `ArrayAccess` (#17)
|
||||||
|
- Added ability to merge non-associative array values (#31, #32)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- All thrown exceptions are now instances or subclasses of `DataException` (#20)
|
||||||
|
- Calling `get()` on a missing key path without providing a default will throw a `MissingPathException` instead of returning `null` (#29)
|
||||||
|
- Bumped supported PHP versions to 7.1 - 8.x (#18)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Fixed incorrect merging of array values into string values (#32)
|
||||||
|
- Fixed `get()` method behaving as if keys with `null` values didn't exist
|
||||||
|
|
||||||
|
## [2.0.0] - 2017-12-21
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Bumped supported PHP versions to 7.0 - 7.4 (#12)
|
||||||
|
- Switched to PSR-4 autoloading
|
||||||
|
|
||||||
|
## [1.1.0] - 2017-01-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added new `has()` method to check for the existence of the given key (#4, #7)
|
||||||
|
|
||||||
|
## [1.0.1] - 2015-08-12
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added new optional `$default` parameter to the `get()` method (#2)
|
||||||
|
|
||||||
|
## [1.0.0] - 2012-07-17
|
||||||
|
|
||||||
|
**Initial release!**
|
||||||
|
|
||||||
|
[Unreleased]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.3...main
|
||||||
|
[3.0.3]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.2...v3.0.3
|
||||||
|
[3.0.2]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.1...v3.0.2
|
||||||
|
[3.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.0...v3.0.1
|
||||||
|
[3.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v2.0.0...v3.0.0
|
||||||
|
[2.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.1.0...v2.0.0
|
||||||
|
[1.1.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.1...v1.1.0
|
||||||
|
[1.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.0...v1.0.1
|
||||||
|
[1.0.0]: https://github.com/dflydev/dflydev-dot-access-data/releases/tag/v1.0.0
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
Copyright (c) 2012 Dragonfly Development Inc.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is furnished
|
||||||
|
to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
Dot Access Data
|
||||||
|
===============
|
||||||
|
|
||||||
|
[](https://packagist.org/packages/dflydev/dot-access-data)
|
||||||
|
[](https://packagist.org/packages/dflydev/dot-access-data)
|
||||||
|
[](LICENSE)
|
||||||
|
[](https://github.com/dflydev/dflydev-dot-access-data/actions?query=workflow%3ATests+branch%3Amain)
|
||||||
|
[](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data/code-structure/)
|
||||||
|
[](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data)
|
||||||
|
|
||||||
|
Given a deep data structure, access data by dot notation.
|
||||||
|
|
||||||
|
|
||||||
|
Requirements
|
||||||
|
------------
|
||||||
|
|
||||||
|
* PHP (7.1+)
|
||||||
|
|
||||||
|
> For PHP (5.3+) please refer to version `1.0`.
|
||||||
|
|
||||||
|
|
||||||
|
Usage
|
||||||
|
-----
|
||||||
|
|
||||||
|
Abstract example:
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Dflydev\DotAccessData\Data;
|
||||||
|
|
||||||
|
$data = new Data;
|
||||||
|
|
||||||
|
$data->set('a.b.c', 'C');
|
||||||
|
$data->set('a.b.d', 'D1');
|
||||||
|
$data->append('a.b.d', 'D2');
|
||||||
|
$data->set('a.b.e', ['E0', 'E1', 'E2']);
|
||||||
|
|
||||||
|
// C
|
||||||
|
$data->get('a.b.c');
|
||||||
|
|
||||||
|
// ['D1', 'D2']
|
||||||
|
$data->get('a.b.d');
|
||||||
|
|
||||||
|
// ['E0', 'E1', 'E2']
|
||||||
|
$data->get('a.b.e');
|
||||||
|
|
||||||
|
// true
|
||||||
|
$data->has('a.b.c');
|
||||||
|
|
||||||
|
// false
|
||||||
|
$data->has('a.b.d.j');
|
||||||
|
|
||||||
|
|
||||||
|
// 'some-default-value'
|
||||||
|
$data->get('some.path.that.does.not.exist', 'some-default-value');
|
||||||
|
|
||||||
|
// throws a MissingPathException because no default was given
|
||||||
|
$data->get('some.path.that.does.not.exist');
|
||||||
|
```
|
||||||
|
|
||||||
|
A more concrete example:
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Dflydev\DotAccessData\Data;
|
||||||
|
|
||||||
|
$data = new Data([
|
||||||
|
'hosts' => [
|
||||||
|
'hewey' => [
|
||||||
|
'username' => 'hman',
|
||||||
|
'password' => 'HPASS',
|
||||||
|
'roles' => ['web'],
|
||||||
|
],
|
||||||
|
'dewey' => [
|
||||||
|
'username' => 'dman',
|
||||||
|
'password' => 'D---S',
|
||||||
|
'roles' => ['web', 'db'],
|
||||||
|
'nick' => 'dewey dman',
|
||||||
|
],
|
||||||
|
'lewey' => [
|
||||||
|
'username' => 'lman',
|
||||||
|
'password' => 'LP@$$',
|
||||||
|
'roles' => ['db'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
// hman
|
||||||
|
$username = $data->get('hosts.hewey.username');
|
||||||
|
// HPASS
|
||||||
|
$password = $data->get('hosts.hewey.password');
|
||||||
|
// ['web']
|
||||||
|
$roles = $data->get('hosts.hewey.roles');
|
||||||
|
// dewey dman
|
||||||
|
$nick = $data->get('hosts.dewey.nick');
|
||||||
|
// Unknown
|
||||||
|
$nick = $data->get('hosts.lewey.nick', 'Unknown');
|
||||||
|
|
||||||
|
// DataInterface instance
|
||||||
|
$dewey = $data->getData('hosts.dewey');
|
||||||
|
// dman
|
||||||
|
$username = $dewey->get('username');
|
||||||
|
// D---S
|
||||||
|
$password = $dewey->get('password');
|
||||||
|
// ['web', 'db']
|
||||||
|
$roles = $dewey->get('roles');
|
||||||
|
|
||||||
|
// No more lewey
|
||||||
|
$data->remove('hosts.lewey');
|
||||||
|
|
||||||
|
// Add DB to hewey's roles
|
||||||
|
$data->append('hosts.hewey.roles', 'db');
|
||||||
|
|
||||||
|
$data->set('hosts.april', [
|
||||||
|
'username' => 'aman',
|
||||||
|
'password' => '@---S',
|
||||||
|
'roles' => ['web'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Check if a key exists (true to this case)
|
||||||
|
$hasKey = $data->has('hosts.dewey.username');
|
||||||
|
```
|
||||||
|
|
||||||
|
`Data` may be used as an array, since it implements `ArrayAccess` interface:
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Get
|
||||||
|
$data->get('name') === $data['name']; // true
|
||||||
|
|
||||||
|
$data['name'] = 'Dewey';
|
||||||
|
// is equivalent to
|
||||||
|
$data->set($name, 'Dewey');
|
||||||
|
|
||||||
|
isset($data['name']) === $data->has('name');
|
||||||
|
|
||||||
|
// Remove key
|
||||||
|
unset($data['name']);
|
||||||
|
```
|
||||||
|
|
||||||
|
`/` can also be used as a path delimiter:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$data->set('a/b/c', 'd');
|
||||||
|
echo $data->get('a/b/c'); // "d"
|
||||||
|
|
||||||
|
$data->get('a/b/c') === $data->get('a.b.c'); // true
|
||||||
|
```
|
||||||
|
|
||||||
|
License
|
||||||
|
-------
|
||||||
|
|
||||||
|
This library is licensed under the MIT License - see the LICENSE file
|
||||||
|
for details.
|
||||||
|
|
||||||
|
|
||||||
|
Community
|
||||||
|
---------
|
||||||
|
|
||||||
|
If you have questions or want to help out, join us in the
|
||||||
|
[#dflydev](irc://irc.freenode.net/#dflydev) channel on irc.freenode.net.
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
{
|
||||||
|
"name": "dflydev/dot-access-data",
|
||||||
|
"type": "library",
|
||||||
|
"description": "Given a deep data structure, access data by dot notation.",
|
||||||
|
"homepage": "https://github.com/dflydev/dflydev-dot-access-data",
|
||||||
|
"keywords": ["dot", "access", "data", "notation"],
|
||||||
|
"license": "MIT",
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Dragonfly Development Inc.",
|
||||||
|
"email": "info@dflydev.com",
|
||||||
|
"homepage": "http://dflydev.com"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Beau Simensen",
|
||||||
|
"email": "beau@dflydev.com",
|
||||||
|
"homepage": "http://beausimensen.com"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Carlos Frutos",
|
||||||
|
"email": "carlos@kiwing.it",
|
||||||
|
"homepage": "https://github.com/cfrutos"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Colin O'Dell",
|
||||||
|
"email": "colinodell@gmail.com",
|
||||||
|
"homepage": "https://www.colinodell.com"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"require": {
|
||||||
|
"php": "^7.1 || ^8.0"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"phpstan/phpstan": "^0.12.42",
|
||||||
|
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.3",
|
||||||
|
"scrutinizer/ocular": "1.6.0",
|
||||||
|
"squizlabs/php_codesniffer": "^3.5",
|
||||||
|
"vimeo/psalm": "^4.0.0"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"Dflydev\\DotAccessData\\": "src/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload-dev": {
|
||||||
|
"psr-4": {
|
||||||
|
"Dflydev\\DotAccessData\\": "tests/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"extra": {
|
||||||
|
"branch-alias": {
|
||||||
|
"dev-main": "3.x-dev"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"phpcs": "phpcs",
|
||||||
|
"phpstan": "phpstan analyse",
|
||||||
|
"phpunit": "phpunit --no-coverage",
|
||||||
|
"psalm": "psalm",
|
||||||
|
"test": [
|
||||||
|
"@phpcs",
|
||||||
|
"@phpstan",
|
||||||
|
"@psalm",
|
||||||
|
"@phpunit"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
+286
@@ -0,0 +1,286 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is a part of dflydev/dot-access-data.
|
||||||
|
*
|
||||||
|
* (c) Dragonfly Development Inc.
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Dflydev\DotAccessData;
|
||||||
|
|
||||||
|
use ArrayAccess;
|
||||||
|
use Dflydev\DotAccessData\Exception\DataException;
|
||||||
|
use Dflydev\DotAccessData\Exception\InvalidPathException;
|
||||||
|
use Dflydev\DotAccessData\Exception\MissingPathException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @implements ArrayAccess<string, mixed>
|
||||||
|
*/
|
||||||
|
class Data implements DataInterface, ArrayAccess
|
||||||
|
{
|
||||||
|
private const DELIMITERS = ['.', '/'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal representation of data data
|
||||||
|
*
|
||||||
|
* @var array<string, mixed>
|
||||||
|
*/
|
||||||
|
protected $data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $data
|
||||||
|
*/
|
||||||
|
public function __construct(array $data = [])
|
||||||
|
{
|
||||||
|
$this->data = $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function append(string $key, $value = null): void
|
||||||
|
{
|
||||||
|
$currentValue =& $this->data;
|
||||||
|
$keyPath = self::keyToPathArray($key);
|
||||||
|
|
||||||
|
$endKey = array_pop($keyPath);
|
||||||
|
foreach ($keyPath as $currentKey) {
|
||||||
|
if (! isset($currentValue[$currentKey])) {
|
||||||
|
$currentValue[$currentKey] = [];
|
||||||
|
}
|
||||||
|
$currentValue =& $currentValue[$currentKey];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($currentValue[$endKey])) {
|
||||||
|
$currentValue[$endKey] = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_array($currentValue[$endKey])) {
|
||||||
|
// Promote this key to an array.
|
||||||
|
// TODO: Is this really what we want to do?
|
||||||
|
$currentValue[$endKey] = [$currentValue[$endKey]];
|
||||||
|
}
|
||||||
|
|
||||||
|
$currentValue[$endKey][] = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function set(string $key, $value = null): void
|
||||||
|
{
|
||||||
|
$currentValue =& $this->data;
|
||||||
|
$keyPath = self::keyToPathArray($key);
|
||||||
|
|
||||||
|
$endKey = array_pop($keyPath);
|
||||||
|
foreach ($keyPath as $currentKey) {
|
||||||
|
if (!isset($currentValue[$currentKey])) {
|
||||||
|
$currentValue[$currentKey] = [];
|
||||||
|
}
|
||||||
|
if (!is_array($currentValue[$currentKey])) {
|
||||||
|
throw new DataException(sprintf('Key path "%s" within "%s" cannot be indexed into (is not an array)', $currentKey, self::formatPath($key)));
|
||||||
|
}
|
||||||
|
$currentValue =& $currentValue[$currentKey];
|
||||||
|
}
|
||||||
|
$currentValue[$endKey] = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function remove(string $key): void
|
||||||
|
{
|
||||||
|
$currentValue =& $this->data;
|
||||||
|
$keyPath = self::keyToPathArray($key);
|
||||||
|
|
||||||
|
$endKey = array_pop($keyPath);
|
||||||
|
foreach ($keyPath as $currentKey) {
|
||||||
|
if (!isset($currentValue[$currentKey])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$currentValue =& $currentValue[$currentKey];
|
||||||
|
}
|
||||||
|
unset($currentValue[$endKey]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function get(string $key, $default = null)
|
||||||
|
{
|
||||||
|
/** @psalm-suppress ImpureFunctionCall */
|
||||||
|
$hasDefault = \func_num_args() > 1;
|
||||||
|
|
||||||
|
$currentValue = $this->data;
|
||||||
|
$keyPath = self::keyToPathArray($key);
|
||||||
|
|
||||||
|
foreach ($keyPath as $currentKey) {
|
||||||
|
if (!is_array($currentValue) || !array_key_exists($currentKey, $currentValue)) {
|
||||||
|
if ($hasDefault) {
|
||||||
|
return $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new MissingPathException($key, sprintf('No data exists at the given path: "%s"', self::formatPath($keyPath)));
|
||||||
|
}
|
||||||
|
|
||||||
|
$currentValue = $currentValue[$currentKey];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $currentValue === null ? $default : $currentValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function has(string $key): bool
|
||||||
|
{
|
||||||
|
$currentValue = $this->data;
|
||||||
|
|
||||||
|
foreach (self::keyToPathArray($key) as $currentKey) {
|
||||||
|
if (
|
||||||
|
!is_array($currentValue) ||
|
||||||
|
!array_key_exists($currentKey, $currentValue)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$currentValue = $currentValue[$currentKey];
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function getData(string $key): DataInterface
|
||||||
|
{
|
||||||
|
$value = $this->get($key);
|
||||||
|
if (is_array($value) && Util::isAssoc($value)) {
|
||||||
|
return new Data($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new DataException(sprintf('Value at "%s" could not be represented as a DataInterface', self::formatPath($key)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function import(array $data, int $mode = self::REPLACE): void
|
||||||
|
{
|
||||||
|
$this->data = Util::mergeAssocArray($this->data, $data, $mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function importData(DataInterface $data, int $mode = self::REPLACE): void
|
||||||
|
{
|
||||||
|
$this->import($data->export(), $mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function export(): array
|
||||||
|
{
|
||||||
|
return $this->data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
#[\ReturnTypeWillChange]
|
||||||
|
public function offsetExists($key)
|
||||||
|
{
|
||||||
|
return $this->has($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
#[\ReturnTypeWillChange]
|
||||||
|
public function offsetGet($key)
|
||||||
|
{
|
||||||
|
return $this->get($key, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @param string $key
|
||||||
|
* @param mixed $value
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
#[\ReturnTypeWillChange]
|
||||||
|
public function offsetSet($key, $value)
|
||||||
|
{
|
||||||
|
$this->set($key, $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
#[\ReturnTypeWillChange]
|
||||||
|
public function offsetUnset($key)
|
||||||
|
{
|
||||||
|
$this->remove($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $path
|
||||||
|
*
|
||||||
|
* @return string[]
|
||||||
|
*
|
||||||
|
* @psalm-return non-empty-list<string>
|
||||||
|
*
|
||||||
|
* @psalm-pure
|
||||||
|
*/
|
||||||
|
protected static function keyToPathArray(string $path): array
|
||||||
|
{
|
||||||
|
if (\strlen($path) === 0) {
|
||||||
|
throw new InvalidPathException('Path cannot be an empty string');
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = \str_replace(self::DELIMITERS, '.', $path);
|
||||||
|
|
||||||
|
return \explode('.', $path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|string[] $path
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*
|
||||||
|
* @psalm-pure
|
||||||
|
*/
|
||||||
|
protected static function formatPath($path): string
|
||||||
|
{
|
||||||
|
if (is_string($path)) {
|
||||||
|
$path = self::keyToPathArray($path);
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode(' » ', $path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is a part of dflydev/dot-access-data.
|
||||||
|
*
|
||||||
|
* (c) Dragonfly Development Inc.
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Dflydev\DotAccessData;
|
||||||
|
|
||||||
|
use Dflydev\DotAccessData\Exception\DataException;
|
||||||
|
use Dflydev\DotAccessData\Exception\InvalidPathException;
|
||||||
|
|
||||||
|
interface DataInterface
|
||||||
|
{
|
||||||
|
public const PRESERVE = 0;
|
||||||
|
public const REPLACE = 1;
|
||||||
|
public const MERGE = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Append a value to a key (assumes key refers to an array value)
|
||||||
|
*
|
||||||
|
* If the key does not yet exist it will be created.
|
||||||
|
* If the key references a non-array it's existing contents will be added into a new array before appending the new value.
|
||||||
|
*
|
||||||
|
* @param string $key
|
||||||
|
* @param mixed $value
|
||||||
|
*
|
||||||
|
* @throws InvalidPathException if the given key is empty
|
||||||
|
*/
|
||||||
|
public function append(string $key, $value = null): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set a value for a key
|
||||||
|
*
|
||||||
|
* If the key does not yet exist it will be created.
|
||||||
|
*
|
||||||
|
* @param string $key
|
||||||
|
* @param mixed $value
|
||||||
|
*
|
||||||
|
* @throws InvalidPathException if the given key is empty
|
||||||
|
* @throws DataException if the given key does not target an array
|
||||||
|
*/
|
||||||
|
public function set(string $key, $value = null): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a key
|
||||||
|
*
|
||||||
|
* No exception will be thrown if the key does not exist
|
||||||
|
*
|
||||||
|
* @param string $key
|
||||||
|
*
|
||||||
|
* @throws InvalidPathException if the given key is empty
|
||||||
|
*/
|
||||||
|
public function remove(string $key): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the raw value for a key
|
||||||
|
*
|
||||||
|
* If the key does not exist, an optional default value can be returned instead.
|
||||||
|
* If no default is provided then an exception will be thrown instead.
|
||||||
|
*
|
||||||
|
* @param string $key
|
||||||
|
* @param mixed $default
|
||||||
|
*
|
||||||
|
* @return mixed
|
||||||
|
*
|
||||||
|
* @throws InvalidPathException if the given key is empty
|
||||||
|
* @throws InvalidPathException if the given key does not exist and no default value was given
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function get(string $key, $default = null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the key exists
|
||||||
|
*
|
||||||
|
* @param string $key
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*
|
||||||
|
* @throws InvalidPathException if the given key is empty
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function has(string $key): bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a data instance for a key
|
||||||
|
*
|
||||||
|
* @param string $key
|
||||||
|
*
|
||||||
|
* @return DataInterface
|
||||||
|
*
|
||||||
|
* @throws InvalidPathException if the given key is empty
|
||||||
|
* @throws DataException if the given key does not reference an array
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function getData(string $key): DataInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import data into existing data
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $data
|
||||||
|
* @param self::PRESERVE|self::REPLACE|self::MERGE $mode
|
||||||
|
*/
|
||||||
|
public function import(array $data, int $mode = self::REPLACE): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import data from an external data into existing data
|
||||||
|
*
|
||||||
|
* @param DataInterface $data
|
||||||
|
* @param self::PRESERVE|self::REPLACE|self::MERGE $mode
|
||||||
|
*/
|
||||||
|
public function importData(DataInterface $data, int $mode = self::REPLACE): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export data as raw data
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*
|
||||||
|
* @psalm-mutation-free
|
||||||
|
*/
|
||||||
|
public function export(): array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is a part of dflydev/dot-access-data.
|
||||||
|
*
|
||||||
|
* (c) Dragonfly Development Inc.
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Dflydev\DotAccessData\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base runtime exception type thrown by this library
|
||||||
|
*/
|
||||||
|
class DataException extends \RuntimeException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is a part of dflydev/dot-access-data.
|
||||||
|
*
|
||||||
|
* (c) Dragonfly Development Inc.
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Dflydev\DotAccessData\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown when trying to access an invalid path in the data array
|
||||||
|
*/
|
||||||
|
class InvalidPathException extends DataException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is a part of dflydev/dot-access-data.
|
||||||
|
*
|
||||||
|
* (c) Dragonfly Development Inc.
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Dflydev\DotAccessData\Exception;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown when trying to access a path that does not exist
|
||||||
|
*/
|
||||||
|
class MissingPathException extends DataException
|
||||||
|
{
|
||||||
|
/** @var string */
|
||||||
|
protected $path;
|
||||||
|
|
||||||
|
public function __construct(string $path, string $message = '', int $code = 0, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$this->path = $path;
|
||||||
|
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPath(): string
|
||||||
|
{
|
||||||
|
return $this->path;
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is a part of dflydev/dot-access-data.
|
||||||
|
*
|
||||||
|
* (c) Dragonfly Development Inc.
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Dflydev\DotAccessData;
|
||||||
|
|
||||||
|
class Util
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Test if array is an associative array
|
||||||
|
*
|
||||||
|
* Note that this function will return true if an array is empty. Meaning
|
||||||
|
* empty arrays will be treated as if they are associative arrays.
|
||||||
|
*
|
||||||
|
* @param array<mixed> $arr
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*
|
||||||
|
* @psalm-pure
|
||||||
|
*/
|
||||||
|
public static function isAssoc(array $arr): bool
|
||||||
|
{
|
||||||
|
return !count($arr) || count(array_filter(array_keys($arr), 'is_string')) == count($arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge contents from one associtative array to another
|
||||||
|
*
|
||||||
|
* @param mixed $to
|
||||||
|
* @param mixed $from
|
||||||
|
* @param DataInterface::PRESERVE|DataInterface::REPLACE|DataInterface::MERGE $mode
|
||||||
|
*
|
||||||
|
* @return mixed
|
||||||
|
*
|
||||||
|
* @psalm-pure
|
||||||
|
*/
|
||||||
|
public static function mergeAssocArray($to, $from, int $mode = DataInterface::REPLACE)
|
||||||
|
{
|
||||||
|
if ($mode === DataInterface::MERGE && self::isList($to) && self::isList($from)) {
|
||||||
|
return array_merge($to, $from);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_array($from) && is_array($to)) {
|
||||||
|
foreach ($from as $k => $v) {
|
||||||
|
if (!isset($to[$k])) {
|
||||||
|
$to[$k] = $v;
|
||||||
|
} else {
|
||||||
|
$to[$k] = self::mergeAssocArray($to[$k], $v, $mode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $to;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $mode === DataInterface::PRESERVE ? $to : $from;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mixed $value
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*
|
||||||
|
* @psalm-pure
|
||||||
|
*/
|
||||||
|
private static function isList($value): bool
|
||||||
|
{
|
||||||
|
return is_array($value) && array_values($value) === $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+272
@@ -0,0 +1,272 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## [7.1.1](https://github.com/googleapis/php-jwt/compare/v7.1.0...v7.1.1) (2026-09-02)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* Limit the number of segments a JWT can be exploded into ([#639](https://github.com/googleapis/php-jwt/issues/639)) ([93d248c](https://github.com/googleapis/php-jwt/commit/93d248c650aea615d74a5ffa20c91c7a818e9b8d))
|
||||||
|
|
||||||
|
## [7.1.0](https://github.com/googleapis/php-jwt/compare/v7.0.5...v7.1.0) (2026-06-11)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* Add support for PS256 ([#637](https://github.com/googleapis/php-jwt/issues/637)) ([aa0b447](https://github.com/googleapis/php-jwt/commit/aa0b4472c137255545b177a1840891304eac55f1))
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* Skip parsing valid unsupported curves ([#638](https://github.com/googleapis/php-jwt/issues/638)) ([8a6c2a7](https://github.com/googleapis/php-jwt/commit/8a6c2a75d7f45e781c93d618939f8a045fe69f53))
|
||||||
|
* Update homepage URL in composer.json ([#635](https://github.com/googleapis/php-jwt/issues/635)) ([f7ae571](https://github.com/googleapis/php-jwt/commit/f7ae571efe255aed89c8f8d0f2cb7f71c5835664))
|
||||||
|
* Validate numeric type of iat, nbf and exp claims in encode ([#634](https://github.com/googleapis/php-jwt/issues/634)) ([958e422](https://github.com/googleapis/php-jwt/commit/958e422961e874843a7fcc339e55a0101a66201d))
|
||||||
|
|
||||||
|
## [7.0.5](https://github.com/firebase/php-jwt/compare/v7.0.4...v7.0.5) (2026-03-31)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* RSA from JWK sometimes returns empty Instance ([#628](https://github.com/firebase/php-jwt/issues/628)) ([b4c78aa](https://github.com/firebase/php-jwt/commit/b4c78aa731664122198ad36c0033aa29e807397a))
|
||||||
|
|
||||||
|
## [7.0.4](https://github.com/firebase/php-jwt/compare/v7.0.3...v7.0.4) (2026-03-27)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* readme examples, add tests for all examples ([#626](https://github.com/firebase/php-jwt/issues/626)) ([510a00c](https://github.com/firebase/php-jwt/commit/510a00c0e6353bc7d68412fab67e57a13954cb46))
|
||||||
|
* use urlsafeB64Decode everywhere ([#627](https://github.com/firebase/php-jwt/issues/627)) ([b889495](https://github.com/firebase/php-jwt/commit/b889495c83ddc3f3885ca3f0b65b41b1cb37a3b1))
|
||||||
|
|
||||||
|
## [7.0.3](https://github.com/firebase/php-jwt/compare/v7.0.2...v7.0.3) (2026-02-18)
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Chores
|
||||||
|
|
||||||
|
* add environment for Release Please job ([#619](https://github.com/firebase/php-jwt/issues/619)) ([300fd02](https://github.com/firebase/php-jwt/commit/300fd02c883f096c9067df652dbd23f62cb5e2a7))
|
||||||
|
|
||||||
|
## [7.0.2](https://github.com/firebase/php-jwt/compare/v7.0.1...v7.0.2) (2025-12-16)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* add key length validation for ec keys ([#615](https://github.com/firebase/php-jwt/issues/615)) ([7044f9a](https://github.com/firebase/php-jwt/commit/7044f9ae7e7d175d28cca71714feb236f1c0e252))
|
||||||
|
|
||||||
|
## [7.0.0](https://github.com/firebase/php-jwt/compare/v6.11.1...v7.0.0) (2025-12-15)
|
||||||
|
|
||||||
|
|
||||||
|
### ⚠️ ⚠️ ⚠️ Security Fixes ⚠️ ⚠️ ⚠️
|
||||||
|
* add key size validation ([#613](https://github.com/firebase/php-jwt/issues/613)) ([6b80341](https://github.com/firebase/php-jwt/commit/6b80341bf57838ea2d011487917337901cd71576))
|
||||||
|
**NOTE**: This fix will cause keys with a size below the minimally allowed size to break.
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add SensitiveParameter attribute to security-critical parameters ([#603](https://github.com/firebase/php-jwt/issues/603)) ([4dbfac0](https://github.com/firebase/php-jwt/commit/4dbfac0260eeb0e9e643063c99998e3219cc539b))
|
||||||
|
* store timestamp in `ExpiredException` ([#604](https://github.com/firebase/php-jwt/issues/604)) ([f174826](https://github.com/firebase/php-jwt/commit/f1748260d218a856b6a0c23715ac7fae1d7ca95b))
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* validate iat and nbf on payload ([#568](https://github.com/firebase/php-jwt/issues/568)) ([953b2c8](https://github.com/firebase/php-jwt/commit/953b2c88bb445b7e3bb82a5141928f13d7343afd))
|
||||||
|
|
||||||
|
## [6.11.1](https://github.com/firebase/php-jwt/compare/v6.11.0...v6.11.1) (2025-04-09)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* update error text for consistency ([#528](https://github.com/firebase/php-jwt/issues/528)) ([c11113a](https://github.com/firebase/php-jwt/commit/c11113afa13265e016a669e75494b9203b8a7775))
|
||||||
|
|
||||||
|
## [6.11.0](https://github.com/firebase/php-jwt/compare/v6.10.2...v6.11.0) (2025-01-23)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* support octet typed JWK ([#587](https://github.com/firebase/php-jwt/issues/587)) ([7cb8a26](https://github.com/firebase/php-jwt/commit/7cb8a265fa81edf2fa6ef8098f5bc5ae573c33ad))
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* refactor constructor Key to use PHP 8.0 syntax ([#577](https://github.com/firebase/php-jwt/issues/577)) ([29fa2ce](https://github.com/firebase/php-jwt/commit/29fa2ce9e0582cd397711eec1e80c05ce20fabca))
|
||||||
|
|
||||||
|
## [6.10.2](https://github.com/firebase/php-jwt/compare/v6.10.1...v6.10.2) (2024-11-24)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* Mitigate PHP8.4 deprecation warnings ([#570](https://github.com/firebase/php-jwt/issues/570)) ([76808fa](https://github.com/firebase/php-jwt/commit/76808fa227f3811aa5cdb3bf81233714b799a5b5))
|
||||||
|
* support php 8.4 ([#583](https://github.com/firebase/php-jwt/issues/583)) ([e3d68b0](https://github.com/firebase/php-jwt/commit/e3d68b044421339443c74199edd020e03fb1887e))
|
||||||
|
|
||||||
|
## [6.10.1](https://github.com/firebase/php-jwt/compare/v6.10.0...v6.10.1) (2024-05-18)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* ensure ratelimit expiry is set every time ([#556](https://github.com/firebase/php-jwt/issues/556)) ([09cb208](https://github.com/firebase/php-jwt/commit/09cb2081c2c3bc0f61e2f2a5fbea5741f7498648))
|
||||||
|
* ratelimit cache expiration ([#550](https://github.com/firebase/php-jwt/issues/550)) ([dda7250](https://github.com/firebase/php-jwt/commit/dda725033585ece30ff8cae8937320d7e9f18bae))
|
||||||
|
|
||||||
|
## [6.10.0](https://github.com/firebase/php-jwt/compare/v6.9.0...v6.10.0) (2023-11-28)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* allow typ header override ([#546](https://github.com/firebase/php-jwt/issues/546)) ([79cb30b](https://github.com/firebase/php-jwt/commit/79cb30b729a22931b2fbd6b53f20629a83031ba9))
|
||||||
|
|
||||||
|
## [6.9.0](https://github.com/firebase/php-jwt/compare/v6.8.1...v6.9.0) (2023-10-04)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add payload to jwt exception ([#521](https://github.com/firebase/php-jwt/issues/521)) ([175edf9](https://github.com/firebase/php-jwt/commit/175edf958bb61922ec135b2333acf5622f2238a2))
|
||||||
|
|
||||||
|
## [6.8.1](https://github.com/firebase/php-jwt/compare/v6.8.0...v6.8.1) (2023-07-14)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* accept float claims but round down to ignore them ([#492](https://github.com/firebase/php-jwt/issues/492)) ([3936842](https://github.com/firebase/php-jwt/commit/39368423beeaacb3002afa7dcb75baebf204fe7e))
|
||||||
|
* different BeforeValidException messages for nbf and iat ([#526](https://github.com/firebase/php-jwt/issues/526)) ([0a53cf2](https://github.com/firebase/php-jwt/commit/0a53cf2986e45c2bcbf1a269f313ebf56a154ee4))
|
||||||
|
|
||||||
|
## [6.8.0](https://github.com/firebase/php-jwt/compare/v6.7.0...v6.8.0) (2023-06-14)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add support for P-384 curve ([#515](https://github.com/firebase/php-jwt/issues/515)) ([5de4323](https://github.com/firebase/php-jwt/commit/5de4323f4baf4d70bca8663bd87682a69c656c3d))
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* handle invalid http responses ([#508](https://github.com/firebase/php-jwt/issues/508)) ([91c39c7](https://github.com/firebase/php-jwt/commit/91c39c72b22fc3e1191e574089552c1f2041c718))
|
||||||
|
|
||||||
|
## [6.7.0](https://github.com/firebase/php-jwt/compare/v6.6.0...v6.7.0) (2023-06-14)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add ed25519 support to JWK (public keys) ([#452](https://github.com/firebase/php-jwt/issues/452)) ([e53979a](https://github.com/firebase/php-jwt/commit/e53979abae927de916a75b9d239cfda8ce32be2a))
|
||||||
|
|
||||||
|
## [6.6.0](https://github.com/firebase/php-jwt/compare/v6.5.0...v6.6.0) (2023-06-13)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* allow get headers when decoding token ([#442](https://github.com/firebase/php-jwt/issues/442)) ([fb85f47](https://github.com/firebase/php-jwt/commit/fb85f47cfaeffdd94faf8defdf07164abcdad6c3))
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* only check iat if nbf is not used ([#493](https://github.com/firebase/php-jwt/issues/493)) ([398ccd2](https://github.com/firebase/php-jwt/commit/398ccd25ea12fa84b9e4f1085d5ff448c21ec797))
|
||||||
|
|
||||||
|
## [6.5.0](https://github.com/firebase/php-jwt/compare/v6.4.0...v6.5.0) (2023-05-12)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* allow KID of '0' ([#505](https://github.com/firebase/php-jwt/issues/505)) ([9dc46a9](https://github.com/firebase/php-jwt/commit/9dc46a9c3e5801294249cfd2554c5363c9f9326a))
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Chores
|
||||||
|
|
||||||
|
* drop support for PHP 7.3 ([#495](https://github.com/firebase/php-jwt/issues/495))
|
||||||
|
|
||||||
|
## [6.4.0](https://github.com/firebase/php-jwt/compare/v6.3.2...v6.4.0) (2023-02-08)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add support for W3C ES256K ([#462](https://github.com/firebase/php-jwt/issues/462)) ([213924f](https://github.com/firebase/php-jwt/commit/213924f51936291fbbca99158b11bd4ae56c2c95))
|
||||||
|
* improve caching by only decoding jwks when necessary ([#486](https://github.com/firebase/php-jwt/issues/486)) ([78d3ed1](https://github.com/firebase/php-jwt/commit/78d3ed1073553f7d0bbffa6c2010009a0d483d5c))
|
||||||
|
|
||||||
|
## [6.3.2](https://github.com/firebase/php-jwt/compare/v6.3.1...v6.3.2) (2022-11-01)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* check kid before using as array index ([bad1b04](https://github.com/firebase/php-jwt/commit/bad1b040d0c736bbf86814c6b5ae614f517cf7bd))
|
||||||
|
|
||||||
|
## [6.3.1](https://github.com/firebase/php-jwt/compare/v6.3.0...v6.3.1) (2022-11-01)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* casing of GET for PSR compat ([#451](https://github.com/firebase/php-jwt/issues/451)) ([60b52b7](https://github.com/firebase/php-jwt/commit/60b52b71978790eafcf3b95cfbd83db0439e8d22))
|
||||||
|
* string interpolation format for php 8.2 ([#446](https://github.com/firebase/php-jwt/issues/446)) ([2e07d8a](https://github.com/firebase/php-jwt/commit/2e07d8a1524d12b69b110ad649f17461d068b8f2))
|
||||||
|
|
||||||
|
## 6.3.0 / 2022-07-15
|
||||||
|
|
||||||
|
- Added ES256 support to JWK parsing ([#399](https://github.com/firebase/php-jwt/pull/399))
|
||||||
|
- Fixed potential caching error in `CachedKeySet` by caching jwks as strings ([#435](https://github.com/firebase/php-jwt/pull/435))
|
||||||
|
|
||||||
|
## 6.2.0 / 2022-05-14
|
||||||
|
|
||||||
|
- Added `CachedKeySet` ([#397](https://github.com/firebase/php-jwt/pull/397))
|
||||||
|
- Added `$defaultAlg` parameter to `JWT::parseKey` and `JWT::parseKeySet` ([#426](https://github.com/firebase/php-jwt/pull/426)).
|
||||||
|
|
||||||
|
## 6.1.0 / 2022-03-23
|
||||||
|
|
||||||
|
- Drop support for PHP 5.3, 5.4, 5.5, 5.6, and 7.0
|
||||||
|
- Add parameter typing and return types where possible
|
||||||
|
|
||||||
|
## 6.0.0 / 2022-01-24
|
||||||
|
|
||||||
|
- **Backwards-Compatibility Breaking Changes**: See the [Release Notes](https://github.com/firebase/php-jwt/releases/tag/v6.0.0) for more information.
|
||||||
|
- New Key object to prevent key/algorithm type confusion (#365)
|
||||||
|
- Add JWK support (#273)
|
||||||
|
- Add ES256 support (#256)
|
||||||
|
- Add ES384 support (#324)
|
||||||
|
- Add Ed25519 support (#343)
|
||||||
|
|
||||||
|
## 5.0.0 / 2017-06-26
|
||||||
|
- Support RS384 and RS512.
|
||||||
|
See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)!
|
||||||
|
- Add an example for RS256 openssl.
|
||||||
|
See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)!
|
||||||
|
- Detect invalid Base64 encoding in signature.
|
||||||
|
See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)!
|
||||||
|
- Update `JWT::verify` to handle OpenSSL errors.
|
||||||
|
See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)!
|
||||||
|
- Add `array` type hinting to `decode` method
|
||||||
|
See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)!
|
||||||
|
- Add all JSON error types.
|
||||||
|
See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)!
|
||||||
|
- Bugfix 'kid' not in given key list.
|
||||||
|
See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)!
|
||||||
|
- Miscellaneous cleanup, documentation and test fixes.
|
||||||
|
See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115),
|
||||||
|
[#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and
|
||||||
|
[#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman),
|
||||||
|
[@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)!
|
||||||
|
|
||||||
|
## 4.0.0 / 2016-07-17
|
||||||
|
- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)!
|
||||||
|
- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)!
|
||||||
|
- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)!
|
||||||
|
- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)!
|
||||||
|
|
||||||
|
## 3.0.0 / 2015-07-22
|
||||||
|
- Minimum PHP version updated from `5.2.0` to `5.3.0`.
|
||||||
|
- Add `\Firebase\JWT` namespace. See
|
||||||
|
[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to
|
||||||
|
[@Dashron](https://github.com/Dashron)!
|
||||||
|
- Require a non-empty key to decode and verify a JWT. See
|
||||||
|
[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to
|
||||||
|
[@sjones608](https://github.com/sjones608)!
|
||||||
|
- Cleaner documentation blocks in the code. See
|
||||||
|
[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to
|
||||||
|
[@johanderuijter](https://github.com/johanderuijter)!
|
||||||
|
|
||||||
|
## 2.2.0 / 2015-06-22
|
||||||
|
- Add support for adding custom, optional JWT headers to `JWT::encode()`. See
|
||||||
|
[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to
|
||||||
|
[@mcocaro](https://github.com/mcocaro)!
|
||||||
|
|
||||||
|
## 2.1.0 / 2015-05-20
|
||||||
|
- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew
|
||||||
|
between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)!
|
||||||
|
- Add support for passing an object implementing the `ArrayAccess` interface for
|
||||||
|
`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)!
|
||||||
|
|
||||||
|
## 2.0.0 / 2015-04-01
|
||||||
|
- **Note**: It is strongly recommended that you update to > v2.0.0 to address
|
||||||
|
known security vulnerabilities in prior versions when both symmetric and
|
||||||
|
asymmetric keys are used together.
|
||||||
|
- Update signature for `JWT::decode(...)` to require an array of supported
|
||||||
|
algorithms to use when verifying token signatures.
|
||||||
Vendored
+30
@@ -0,0 +1,30 @@
|
|||||||
|
Copyright (c) 2011, Neuman Vong
|
||||||
|
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
* Redistributions of source code must retain the above copyright
|
||||||
|
notice, this list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
* Redistributions in binary form must reproduce the above
|
||||||
|
copyright notice, this list of conditions and the following
|
||||||
|
disclaimer in the documentation and/or other materials provided
|
||||||
|
with the distribution.
|
||||||
|
|
||||||
|
* Neither the name of the copyright holder nor the names of other
|
||||||
|
contributors may be used to endorse or promote products derived
|
||||||
|
from this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
Vendored
+469
@@ -0,0 +1,469 @@
|
|||||||
|

|
||||||
|
[](https://packagist.org/packages/firebase/php-jwt)
|
||||||
|
[](https://packagist.org/packages/firebase/php-jwt)
|
||||||
|
[](https://packagist.org/packages/firebase/php-jwt)
|
||||||
|
|
||||||
|
PHP-JWT
|
||||||
|
=======
|
||||||
|
A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519).
|
||||||
|
|
||||||
|
Supported Specifications
|
||||||
|
------------------------
|
||||||
|
|
||||||
|
- [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) — JSON Web Token (JWT)
|
||||||
|
- [RFC 7515](https://datatracker.ietf.org/doc/html/rfc7515) — JSON Web Signature (JWS)
|
||||||
|
- [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517) — JSON Web Key (JWK)
|
||||||
|
- [RFC 7518](https://datatracker.ietf.org/doc/html/rfc7518) — JSON Web Algorithms (JWA) (`HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `ES256`, `ES384`, `PS256`)
|
||||||
|
- [RFC 8037](https://datatracker.ietf.org/doc/html/rfc8037) — CFRG Elliptic Curve Diffie-Hellman (ECDH) and Signatures in JOSE (`EdDSA` / `Ed25519` and `OKP` JWKs)
|
||||||
|
- [RFC 8812](https://datatracker.ietf.org/doc/html/rfc8812) — CBOR Object Signing and Encryption (COSE) and JSON Object Signing and Encryption (JOSE) Registrations for Web Authentication (WebAuthn) Algorithms (`ES256K` / `secp256k1`)
|
||||||
|
|
||||||
|
> **Note:** This library only supports signed JWTs (JWS, [RFC 7515](https://datatracker.ietf.org/doc/html/rfc7515)). Encrypted JWTs (JWE, [RFC 7516](https://datatracker.ietf.org/doc/html/rfc7516)) are not supported.
|
||||||
|
|
||||||
|
Installation
|
||||||
|
------------
|
||||||
|
|
||||||
|
Use composer to manage your dependencies and download PHP-JWT:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require firebase/php-jwt
|
||||||
|
```
|
||||||
|
|
||||||
|
Optionally, install the `paragonie/sodium_compat` package from composer if your
|
||||||
|
php env does not have libsodium installed:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require paragonie/sodium_compat
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
|
||||||
|
$key = 'example_key_of_sufficient_length';
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'example.org',
|
||||||
|
'aud' => 'example.com',
|
||||||
|
'iat' => 1356999524,
|
||||||
|
'nbf' => 1357000000
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IMPORTANT:
|
||||||
|
* You must specify supported algorithms for your application. See
|
||||||
|
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
|
||||||
|
* for a list of spec-compliant algorithms.
|
||||||
|
*/
|
||||||
|
$jwt = JWT::encode($payload, $key, 'HS256');
|
||||||
|
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
|
||||||
|
print_r($decoded);
|
||||||
|
|
||||||
|
// Pass a stdClass in as the third parameter to get the decoded header values
|
||||||
|
$headers = new stdClass();
|
||||||
|
$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers);
|
||||||
|
print_r($headers);
|
||||||
|
|
||||||
|
/*
|
||||||
|
NOTE: This will now be an object instead of an associative array. To get
|
||||||
|
an associative array, you will need to cast it as such:
|
||||||
|
*/
|
||||||
|
|
||||||
|
$decoded_array = (array) $decoded;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* You can add a leeway to account for when there is a clock skew times between
|
||||||
|
* the signing and verifying servers. It is recommended that this leeway should
|
||||||
|
* not be bigger than a few minutes.
|
||||||
|
*
|
||||||
|
* Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
|
||||||
|
*/
|
||||||
|
JWT::$leeway = 60; // $leeway in seconds
|
||||||
|
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example encode/decode headers
|
||||||
|
|
||||||
|
Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by
|
||||||
|
this library. This is because without verifying the JWT, the header values could have been tampered with.
|
||||||
|
Any value pulled from an unverified header should be treated as if it could be any string sent in from an
|
||||||
|
attacker. If this is something you still want to do in your application for whatever reason, it's possible to
|
||||||
|
decode the header values manually simply by calling `json_decode` and `base64_decode` on the JWT
|
||||||
|
header part:
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
|
||||||
|
$key = 'example_key_of_sufficient_length';
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'example.org',
|
||||||
|
'aud' => 'example.com',
|
||||||
|
'iat' => 1356999524,
|
||||||
|
'nbf' => 1357000000
|
||||||
|
];
|
||||||
|
|
||||||
|
$headers = [
|
||||||
|
'x-forwarded-for' => 'www.google.com'
|
||||||
|
];
|
||||||
|
|
||||||
|
// Encode headers in the JWT string
|
||||||
|
$jwt = JWT::encode($payload, $key, 'HS256', null, $headers);
|
||||||
|
|
||||||
|
// Decode headers from the JWT string WITHOUT validation
|
||||||
|
// **IMPORTANT**: This operation is vulnerable to attacks, as the JWT has not yet been verified.
|
||||||
|
// These headers could be any value sent by an attacker.
|
||||||
|
list($headersB64, $payloadB64, $sig) = explode('.', $jwt);
|
||||||
|
$decoded = json_decode(base64_decode($headersB64), true);
|
||||||
|
|
||||||
|
print_r($decoded);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example with RS256 (openssl)
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
|
||||||
|
$privateKey = <<<EOD
|
||||||
|
-----BEGIN RSA PRIVATE KEY-----
|
||||||
|
MIIEowIBAAKCAQEAuzWHNM5f+amCjQztc5QTfJfzCC5J4nuW+L/aOxZ4f8J3Frew
|
||||||
|
M2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJhzkPYLae7bTVro3hok0zDITR8F6S
|
||||||
|
JGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548tu4czCuqU8BGVOlnp6IqBHhAswNMM
|
||||||
|
78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vSopcT51koWOgiTf3C7nJUoMWZHZI5
|
||||||
|
HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTzTTqo1SCSH2pooJl9O8at6kkRYsrZ
|
||||||
|
WwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/BwQIDAQABAoIBAFtGaOqNKGwggn9k
|
||||||
|
6yzr6GhZ6Wt2rh1Xpq8XUz514UBhPxD7dFRLpbzCrLVpzY80LbmVGJ9+1pJozyWc
|
||||||
|
VKeCeUdNwbqkr240Oe7GTFmGjDoxU+5/HX/SJYPpC8JZ9oqgEA87iz+WQX9hVoP2
|
||||||
|
oF6EB4ckDvXmk8FMwVZW2l2/kd5mrEVbDaXKxhvUDf52iVD+sGIlTif7mBgR99/b
|
||||||
|
c3qiCnxCMmfYUnT2eh7Vv2LhCR/G9S6C3R4lA71rEyiU3KgsGfg0d82/XWXbegJW
|
||||||
|
h3QbWNtQLxTuIvLq5aAryV3PfaHlPgdgK0ft6ocU2de2FagFka3nfVEyC7IUsNTK
|
||||||
|
bq6nhAECgYEA7d/0DPOIaItl/8BWKyCuAHMss47j0wlGbBSHdJIiS55akMvnAG0M
|
||||||
|
39y22Qqfzh1at9kBFeYeFIIU82ZLF3xOcE3z6pJZ4Dyvx4BYdXH77odo9uVK9s1l
|
||||||
|
3T3BlMcqd1hvZLMS7dviyH79jZo4CXSHiKzc7pQ2YfK5eKxKqONeXuECgYEAyXlG
|
||||||
|
vonaus/YTb1IBei9HwaccnQ/1HRn6MvfDjb7JJDIBhNClGPt6xRlzBbSZ73c2QEC
|
||||||
|
6Fu9h36K/HZ2qcLd2bXiNyhIV7b6tVKk+0Psoj0dL9EbhsD1OsmE1nTPyAc9XZbb
|
||||||
|
OPYxy+dpBCUA8/1U9+uiFoCa7mIbWcSQ+39gHuECgYAz82pQfct30aH4JiBrkNqP
|
||||||
|
nJfRq05UY70uk5k1u0ikLTRoVS/hJu/d4E1Kv4hBMqYCavFSwAwnvHUo51lVCr/y
|
||||||
|
xQOVYlsgnwBg2MX4+GjmIkqpSVCC8D7j/73MaWb746OIYZervQ8dbKahi2HbpsiG
|
||||||
|
8AHcVSA/agxZr38qvWV54QKBgCD5TlDE8x18AuTGQ9FjxAAd7uD0kbXNz2vUYg9L
|
||||||
|
hFL5tyL3aAAtUrUUw4xhd9IuysRhW/53dU+FsG2dXdJu6CxHjlyEpUJl2iZu/j15
|
||||||
|
YnMzGWHIEX8+eWRDsw/+Ujtko/B7TinGcWPz3cYl4EAOiCeDUyXnqnO1btCEUU44
|
||||||
|
DJ1BAoGBAJuPD27ErTSVtId90+M4zFPNibFP50KprVdc8CR37BE7r8vuGgNYXmnI
|
||||||
|
RLnGP9p3pVgFCktORuYS2J/6t84I3+A17nEoB4xvhTLeAinAW/uTQOUmNicOP4Ek
|
||||||
|
2MsLL2kHgL8bLTmvXV4FX+PXphrDKg1XxzOYn0otuoqdAQrkK4og
|
||||||
|
-----END RSA PRIVATE KEY-----
|
||||||
|
EOD;
|
||||||
|
|
||||||
|
$publicKey = <<<EOD
|
||||||
|
-----BEGIN PUBLIC KEY-----
|
||||||
|
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzWHNM5f+amCjQztc5QT
|
||||||
|
fJfzCC5J4nuW+L/aOxZ4f8J3FrewM2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJ
|
||||||
|
hzkPYLae7bTVro3hok0zDITR8F6SJGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548t
|
||||||
|
u4czCuqU8BGVOlnp6IqBHhAswNMM78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vS
|
||||||
|
opcT51koWOgiTf3C7nJUoMWZHZI5HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTz
|
||||||
|
TTqo1SCSH2pooJl9O8at6kkRYsrZWwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/B
|
||||||
|
wQIDAQAB
|
||||||
|
-----END PUBLIC KEY-----
|
||||||
|
EOD;
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'example.org',
|
||||||
|
'aud' => 'example.com',
|
||||||
|
'iat' => 1356999524,
|
||||||
|
'nbf' => 1357000000
|
||||||
|
];
|
||||||
|
|
||||||
|
$jwt = JWT::encode($payload, $privateKey, 'RS256');
|
||||||
|
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||||
|
|
||||||
|
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
|
||||||
|
|
||||||
|
/*
|
||||||
|
NOTE: This will now be an object instead of an associative array. To get
|
||||||
|
an associative array, you will need to cast it as such:
|
||||||
|
*/
|
||||||
|
|
||||||
|
$decoded_array = (array) $decoded;
|
||||||
|
echo "Decode:\n" . print_r($decoded_array, true) . "\n";
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example with a passphrase
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
|
||||||
|
// Your passphrase
|
||||||
|
$passphrase = '[YOUR_PASSPHRASE]';
|
||||||
|
|
||||||
|
// Your private key file with passphrase
|
||||||
|
// Can be generated with "ssh-keygen -t rsa -m pem"
|
||||||
|
$privateKeyFile = '/path/to/key-with-passphrase.pem';
|
||||||
|
|
||||||
|
/** @var OpenSSLAsymmetricKey $privateKey */
|
||||||
|
$privateKey = openssl_pkey_get_private(
|
||||||
|
file_get_contents($privateKeyFile),
|
||||||
|
$passphrase
|
||||||
|
);
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'example.org',
|
||||||
|
'aud' => 'example.com',
|
||||||
|
'iat' => 1356999524,
|
||||||
|
'nbf' => 1357000000
|
||||||
|
];
|
||||||
|
|
||||||
|
$jwt = JWT::encode($payload, $privateKey, 'RS256');
|
||||||
|
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||||
|
|
||||||
|
// Get public key from the private key, or pull from from a file.
|
||||||
|
$publicKey = openssl_pkey_get_details($privateKey)['key'];
|
||||||
|
|
||||||
|
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
|
||||||
|
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example with EdDSA (libsodium and Ed25519 signature)
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
|
||||||
|
// Public and private keys are expected to be Base64 encoded. The last
|
||||||
|
// non-empty line is used so that keys can be generated with
|
||||||
|
// sodium_crypto_sign_keypair(). The secret keys generated by other tools may
|
||||||
|
// need to be adjusted to match the input expected by libsodium.
|
||||||
|
|
||||||
|
$keyPair = sodium_crypto_sign_keypair();
|
||||||
|
|
||||||
|
$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair));
|
||||||
|
|
||||||
|
$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair));
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'example.org',
|
||||||
|
'aud' => 'example.com',
|
||||||
|
'iat' => 1356999524,
|
||||||
|
'nbf' => 1357000000
|
||||||
|
];
|
||||||
|
|
||||||
|
$jwt = JWT::encode($payload, $privateKey, 'EdDSA');
|
||||||
|
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||||
|
|
||||||
|
$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA'));
|
||||||
|
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example with multiple keys
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
|
||||||
|
// Example RSA keys from previous example
|
||||||
|
// $privateRsKey = '...';
|
||||||
|
// $publicRsKey = '...';
|
||||||
|
|
||||||
|
// Example EdDSA keys from previous example
|
||||||
|
// $privateEcKey = '...';
|
||||||
|
// $publicEcKey = '...';
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'example.org',
|
||||||
|
'aud' => 'example.com',
|
||||||
|
'iat' => 1356999524,
|
||||||
|
'nbf' => 1357000000
|
||||||
|
];
|
||||||
|
|
||||||
|
$jwt1 = JWT::encode($payload, $privateRsKey, 'RS256', 'kid1');
|
||||||
|
$jwt2 = JWT::encode($payload, $privateEcKey, 'EdDSA', 'kid2');
|
||||||
|
echo "Encode 1:\n" . print_r($jwt1, true) . "\n";
|
||||||
|
echo "Encode 2:\n" . print_r($jwt2, true) . "\n";
|
||||||
|
|
||||||
|
$keys = [
|
||||||
|
'kid1' => new Key($publicRsKey, 'RS256'),
|
||||||
|
'kid2' => new Key($publicEcKey, 'EdDSA'),
|
||||||
|
];
|
||||||
|
|
||||||
|
$decoded1 = JWT::decode($jwt1, $keys);
|
||||||
|
$decoded2 = JWT::decode($jwt2, $keys);
|
||||||
|
|
||||||
|
echo "Decode 1:\n" . print_r((array) $decoded1, true) . "\n";
|
||||||
|
echo "Decode 2:\n" . print_r((array) $decoded2, true) . "\n";
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example with PS256
|
||||||
|
|
||||||
|
### Note
|
||||||
|
PHP's OpenSSL extension does not support RSASSA-PSS signatures (PS256) by default, so we provide support via a soft dependency on the [phpseclib/phpseclib](https://github.com/phpseclib/phpseclib) library. It is necessary to install this library in your project if you plan to use PS256.
|
||||||
|
```bash
|
||||||
|
composer install phpseclib/phpseclib:^3.0
|
||||||
|
```
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
|
||||||
|
$privateRsKey = '-----BEGIN RSA PRIVATE KEY----- ...';
|
||||||
|
$publicKey = '-----BEGIN PUBLIC KEY----- ...';
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'example.org',
|
||||||
|
'aud' => 'example.com',
|
||||||
|
'iat' => 1356999524,
|
||||||
|
'nbf' => 1357000000
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PS256 support requires phpseclib/phpseclib
|
||||||
|
*/
|
||||||
|
$jwt = JWT::encode($payload, $privateRsKey, 'PS256', 'keyid');
|
||||||
|
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||||
|
|
||||||
|
$decoded = JWT::decode($jwt, new Key($publicKey, 'PS256'));
|
||||||
|
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||||
|
```
|
||||||
|
|
||||||
|
## Using JWKs
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWK;
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
|
||||||
|
// Set of keys. The "keys" key is required. For example, the JSON response to
|
||||||
|
// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk
|
||||||
|
$jwks = ['keys' => []];
|
||||||
|
|
||||||
|
// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key
|
||||||
|
// objects. Pass this as the second parameter to JWT::decode.
|
||||||
|
$decoded = JWT::decode($jwt, JWK::parseKeySet($jwks));
|
||||||
|
print_r($decoded);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Using Cached Key Sets
|
||||||
|
|
||||||
|
The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI.
|
||||||
|
This has the following advantages:
|
||||||
|
|
||||||
|
1. The results are cached for performance.
|
||||||
|
2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation.
|
||||||
|
3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second.
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\CachedKeySet;
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
|
||||||
|
// The URI for the JWKS you wish to cache the results from
|
||||||
|
$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk';
|
||||||
|
|
||||||
|
// Create an HTTP client (can be any PSR-7 compatible HTTP client)
|
||||||
|
$httpClient = new GuzzleHttp\Client();
|
||||||
|
|
||||||
|
// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory)
|
||||||
|
$httpFactory = new GuzzleHttp\Psr7\HttpFactory();
|
||||||
|
|
||||||
|
// Create a cache item pool (can be any PSR-6 compatible cache item pool)
|
||||||
|
$cacheItemPool = Phpfastcache\CacheManager::getInstance('files');
|
||||||
|
|
||||||
|
$keySet = new CachedKeySet(
|
||||||
|
$jwksUri,
|
||||||
|
$httpClient,
|
||||||
|
$httpFactory,
|
||||||
|
$cacheItemPool,
|
||||||
|
null, // $expiresAfter int seconds to set the JWKS to expire
|
||||||
|
true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys
|
||||||
|
);
|
||||||
|
|
||||||
|
$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above
|
||||||
|
$decoded = JWT::decode($jwt, $keySet);
|
||||||
|
```
|
||||||
|
|
||||||
|
Miscellaneous
|
||||||
|
-------------
|
||||||
|
|
||||||
|
#### Exception Handling
|
||||||
|
|
||||||
|
When a call to `JWT::decode` is invalid, it will throw one of the following exceptions:
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\SignatureInvalidException;
|
||||||
|
use Firebase\JWT\BeforeValidException;
|
||||||
|
use Firebase\JWT\ExpiredException;
|
||||||
|
use DomainException;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use UnexpectedValueException;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$decoded = JWT::decode($jwt, $keys);
|
||||||
|
} catch (InvalidArgumentException $e) {
|
||||||
|
// provided key/key-array is empty or malformed.
|
||||||
|
} catch (DomainException $e) {
|
||||||
|
// provided algorithm is unsupported OR
|
||||||
|
// provided key is invalid OR
|
||||||
|
// unknown error thrown in openSSL or libsodium OR
|
||||||
|
// libsodium is required but not available.
|
||||||
|
} catch (SignatureInvalidException $e) {
|
||||||
|
// provided JWT signature verification failed.
|
||||||
|
} catch (BeforeValidException $e) {
|
||||||
|
// provided JWT is trying to be used before "nbf" claim OR
|
||||||
|
// provided JWT is trying to be used before "iat" claim.
|
||||||
|
} catch (ExpiredException $e) {
|
||||||
|
// provided JWT is trying to be used after "exp" claim.
|
||||||
|
} catch (UnexpectedValueException $e) {
|
||||||
|
// provided JWT is malformed OR
|
||||||
|
// provided JWT is missing an algorithm / using an unsupported algorithm OR
|
||||||
|
// provided JWT algorithm does not match provided key OR
|
||||||
|
// provided key ID in key/key-array is empty or invalid.
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified
|
||||||
|
like this:
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use UnexpectedValueException;
|
||||||
|
try {
|
||||||
|
$decoded = JWT::decode($jwt, $keys);
|
||||||
|
} catch (LogicException $e) {
|
||||||
|
// errors having to do with environmental setup or malformed JWT Keys
|
||||||
|
} catch (UnexpectedValueException $e) {
|
||||||
|
// errors having to do with JWT signature and claims
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Casting to array
|
||||||
|
|
||||||
|
The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays
|
||||||
|
instead, you can do the following:
|
||||||
|
|
||||||
|
```php
|
||||||
|
// return type is stdClass
|
||||||
|
$decoded = JWT::decode($jwt, $keys);
|
||||||
|
|
||||||
|
// cast to array
|
||||||
|
$decoded = json_decode(json_encode($decoded), true);
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests
|
||||||
|
-----
|
||||||
|
Run the tests using phpunit:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ composer update
|
||||||
|
$ vendor/bin/phpunit -c phpunit.xml.dist
|
||||||
|
PHPUnit 3.7.10 by Sebastian Bergmann.
|
||||||
|
.....
|
||||||
|
Time: 0 seconds, Memory: 2.50Mb
|
||||||
|
OK (5 tests, 5 assertions)
|
||||||
|
```
|
||||||
|
|
||||||
|
New Lines in private keys
|
||||||
|
-----
|
||||||
|
|
||||||
|
If your private key contains `\n` characters, be sure to wrap it in double quotes `""`
|
||||||
|
and not single quotes `''` in order to properly interpret the escaped characters.
|
||||||
|
|
||||||
|
License
|
||||||
|
-------
|
||||||
|
[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause).
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
7.2.2
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"name": "firebase/php-jwt",
|
||||||
|
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
|
||||||
|
"homepage": "https://github.com/googleapis/php-jwt",
|
||||||
|
"keywords": [
|
||||||
|
"php",
|
||||||
|
"jwt"
|
||||||
|
],
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Neuman Vong",
|
||||||
|
"email": "neuman+pear@twilio.com",
|
||||||
|
"role": "Developer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Anant Narayanan",
|
||||||
|
"email": "anant@php.net",
|
||||||
|
"role": "Developer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"require": {
|
||||||
|
"php": "^8.0"
|
||||||
|
},
|
||||||
|
"suggest": {
|
||||||
|
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present",
|
||||||
|
"ext-sodium": "Support EdDSA (Ed25519) signatures",
|
||||||
|
"phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"Firebase\\JWT\\": "src"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"guzzlehttp/guzzle": "^7.4||^8.0",
|
||||||
|
"phpspec/prophecy-phpunit": "^2.2",
|
||||||
|
"phpunit/phpunit": "^9.5",
|
||||||
|
"psr/cache": "^2.0||^3.0",
|
||||||
|
"psr/http-client": "^1.0",
|
||||||
|
"psr/http-factory": "^1.0",
|
||||||
|
"phpfastcache/phpfastcache": "^9.2",
|
||||||
|
"phpseclib/phpseclib": "~3.0"
|
||||||
|
},
|
||||||
|
"extra": {
|
||||||
|
"component": {
|
||||||
|
"id": "jwt",
|
||||||
|
"target": "googleapis/php-jwt.git",
|
||||||
|
"path": "Jwt",
|
||||||
|
"entry": "README.md"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
class BeforeValidException extends \UnexpectedValueException implements JWTExceptionWithPayloadInterface
|
||||||
|
{
|
||||||
|
private object $payload;
|
||||||
|
|
||||||
|
public function setPayload(object $payload): void
|
||||||
|
{
|
||||||
|
$this->payload = $payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPayload(): object
|
||||||
|
{
|
||||||
|
return $this->payload;
|
||||||
|
}
|
||||||
|
}
|
||||||
+275
@@ -0,0 +1,275 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
use ArrayAccess;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use LogicException;
|
||||||
|
use OutOfBoundsException;
|
||||||
|
use Psr\Cache\CacheItemInterface;
|
||||||
|
use Psr\Cache\CacheItemPoolInterface;
|
||||||
|
use Psr\Http\Client\ClientInterface;
|
||||||
|
use Psr\Http\Message\RequestFactoryInterface;
|
||||||
|
use RuntimeException;
|
||||||
|
use UnexpectedValueException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @implements ArrayAccess<string, Key>
|
||||||
|
*/
|
||||||
|
class CachedKeySet implements ArrayAccess
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private $jwksUri;
|
||||||
|
/**
|
||||||
|
* @var ClientInterface
|
||||||
|
*/
|
||||||
|
private $httpClient;
|
||||||
|
/**
|
||||||
|
* @var RequestFactoryInterface
|
||||||
|
*/
|
||||||
|
private $httpFactory;
|
||||||
|
/**
|
||||||
|
* @var CacheItemPoolInterface
|
||||||
|
*/
|
||||||
|
private $cache;
|
||||||
|
/**
|
||||||
|
* @var ?int
|
||||||
|
*/
|
||||||
|
private $expiresAfter;
|
||||||
|
/**
|
||||||
|
* @var ?CacheItemInterface
|
||||||
|
*/
|
||||||
|
private $cacheItem;
|
||||||
|
/**
|
||||||
|
* @var array<string, array<mixed>>
|
||||||
|
*/
|
||||||
|
private $keySet;
|
||||||
|
/**
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private $cacheKey;
|
||||||
|
/**
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private $cacheKeyPrefix = 'jwks';
|
||||||
|
/**
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
private $maxKeyLength = 64;
|
||||||
|
/**
|
||||||
|
* @var bool
|
||||||
|
*/
|
||||||
|
private $rateLimit;
|
||||||
|
/**
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private $rateLimitCacheKey;
|
||||||
|
/**
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
private $maxCallsPerMinute = 10;
|
||||||
|
/**
|
||||||
|
* @var string|null
|
||||||
|
*/
|
||||||
|
private $defaultAlg;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
string $jwksUri,
|
||||||
|
ClientInterface $httpClient,
|
||||||
|
RequestFactoryInterface $httpFactory,
|
||||||
|
CacheItemPoolInterface $cache,
|
||||||
|
?int $expiresAfter = null,
|
||||||
|
bool $rateLimit = false,
|
||||||
|
?string $defaultAlg = null
|
||||||
|
) {
|
||||||
|
$this->jwksUri = $jwksUri;
|
||||||
|
$this->httpClient = $httpClient;
|
||||||
|
$this->httpFactory = $httpFactory;
|
||||||
|
$this->cache = $cache;
|
||||||
|
$this->expiresAfter = $expiresAfter;
|
||||||
|
$this->rateLimit = $rateLimit;
|
||||||
|
$this->defaultAlg = $defaultAlg;
|
||||||
|
$this->setCacheKeys();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $keyId
|
||||||
|
* @return Key
|
||||||
|
*/
|
||||||
|
public function offsetGet($keyId): Key
|
||||||
|
{
|
||||||
|
if (!$this->keyIdExists($keyId)) {
|
||||||
|
throw new OutOfBoundsException('Key ID not found');
|
||||||
|
}
|
||||||
|
return JWK::parseKey($this->keySet[$keyId], $this->defaultAlg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $keyId
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function offsetExists($keyId): bool
|
||||||
|
{
|
||||||
|
return $this->keyIdExists($keyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $offset
|
||||||
|
* @param Key $value
|
||||||
|
*/
|
||||||
|
public function offsetSet($offset, $value): void
|
||||||
|
{
|
||||||
|
throw new LogicException('Method not implemented');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $offset
|
||||||
|
*/
|
||||||
|
public function offsetUnset($offset): void
|
||||||
|
{
|
||||||
|
throw new LogicException('Method not implemented');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<mixed>
|
||||||
|
*/
|
||||||
|
private function formatJwksForCache(string $jwks): array
|
||||||
|
{
|
||||||
|
$jwks = json_decode($jwks, true);
|
||||||
|
|
||||||
|
if (!isset($jwks['keys'])) {
|
||||||
|
throw new UnexpectedValueException('"keys" member must exist in the JWK Set');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($jwks['keys'])) {
|
||||||
|
throw new InvalidArgumentException('JWK Set did not contain any keys');
|
||||||
|
}
|
||||||
|
|
||||||
|
$keys = [];
|
||||||
|
foreach ($jwks['keys'] as $k => $v) {
|
||||||
|
$kid = isset($v['kid']) ? $v['kid'] : $k;
|
||||||
|
$keys[(string) $kid] = $v;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function keyIdExists(string $keyId): bool
|
||||||
|
{
|
||||||
|
if (null === $this->keySet) {
|
||||||
|
$item = $this->getCacheItem();
|
||||||
|
// Try to load keys from cache
|
||||||
|
if ($item->isHit()) {
|
||||||
|
// item found! retrieve it
|
||||||
|
$this->keySet = $item->get();
|
||||||
|
// If the cached item is a string, the JWKS response was cached (previous behavior).
|
||||||
|
// Parse this into expected format array<kid, jwk> instead.
|
||||||
|
if (\is_string($this->keySet)) {
|
||||||
|
$this->keySet = $this->formatJwksForCache($this->keySet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($this->keySet[$keyId])) {
|
||||||
|
if ($this->rateLimitExceeded()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$request = $this->httpFactory->createRequest('GET', $this->jwksUri);
|
||||||
|
$jwksResponse = $this->httpClient->sendRequest($request);
|
||||||
|
if ($jwksResponse->getStatusCode() !== 200) {
|
||||||
|
throw new UnexpectedValueException(
|
||||||
|
\sprintf(
|
||||||
|
'HTTP Error: %d %s for URI "%s"',
|
||||||
|
$jwksResponse->getStatusCode(),
|
||||||
|
$jwksResponse->getReasonPhrase(),
|
||||||
|
$this->jwksUri,
|
||||||
|
),
|
||||||
|
$jwksResponse->getStatusCode()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
$this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody());
|
||||||
|
|
||||||
|
if (!isset($this->keySet[$keyId])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$item = $this->getCacheItem();
|
||||||
|
$item->set($this->keySet);
|
||||||
|
if ($this->expiresAfter) {
|
||||||
|
$item->expiresAfter($this->expiresAfter);
|
||||||
|
}
|
||||||
|
$this->cache->save($item);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function rateLimitExceeded(): bool
|
||||||
|
{
|
||||||
|
if (!$this->rateLimit) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cacheItem = $this->cache->getItem($this->rateLimitCacheKey);
|
||||||
|
|
||||||
|
$cacheItemData = [];
|
||||||
|
if ($cacheItem->isHit() && \is_array($data = $cacheItem->get())) {
|
||||||
|
$cacheItemData = $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
$callsPerMinute = $cacheItemData['callsPerMinute'] ?? 0;
|
||||||
|
$expiry = $cacheItemData['expiry'] ?? new \DateTime('+60 seconds', new \DateTimeZone('UTC'));
|
||||||
|
|
||||||
|
if (++$callsPerMinute > $this->maxCallsPerMinute) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cacheItem->set(['expiry' => $expiry, 'callsPerMinute' => $callsPerMinute]);
|
||||||
|
$cacheItem->expiresAt($expiry);
|
||||||
|
$this->cache->save($cacheItem);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getCacheItem(): CacheItemInterface
|
||||||
|
{
|
||||||
|
if (\is_null($this->cacheItem)) {
|
||||||
|
$this->cacheItem = $this->cache->getItem($this->cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->cacheItem;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function setCacheKeys(): void
|
||||||
|
{
|
||||||
|
if (empty($this->jwksUri)) {
|
||||||
|
throw new RuntimeException('JWKS URI is empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensure we do not have illegal characters
|
||||||
|
$key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $this->jwksUri);
|
||||||
|
|
||||||
|
// add prefix
|
||||||
|
$key = $this->cacheKeyPrefix . $key;
|
||||||
|
|
||||||
|
// Hash keys if they exceed $maxKeyLength of 64
|
||||||
|
if (\strlen($key) > $this->maxKeyLength) {
|
||||||
|
$key = substr(hash('sha256', $key), 0, $this->maxKeyLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->cacheKey = $key;
|
||||||
|
|
||||||
|
if ($this->rateLimit) {
|
||||||
|
// add prefix
|
||||||
|
$rateLimitKey = $this->cacheKeyPrefix . 'ratelimit' . $key;
|
||||||
|
|
||||||
|
// Hash keys if they exceed $maxKeyLength of 64
|
||||||
|
if (\strlen($rateLimitKey) > $this->maxKeyLength) {
|
||||||
|
$rateLimitKey = substr(hash('sha256', $rateLimitKey), 0, $this->maxKeyLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->rateLimitCacheKey = $rateLimitKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
class ExpiredException extends \UnexpectedValueException implements JWTExceptionWithPayloadInterface
|
||||||
|
{
|
||||||
|
private object $payload;
|
||||||
|
|
||||||
|
private ?int $timestamp = null;
|
||||||
|
|
||||||
|
public function setPayload(object $payload): void
|
||||||
|
{
|
||||||
|
$this->payload = $payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPayload(): object
|
||||||
|
{
|
||||||
|
return $this->payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setTimestamp(int $timestamp): void
|
||||||
|
{
|
||||||
|
$this->timestamp = $timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getTimestamp(): ?int
|
||||||
|
{
|
||||||
|
return $this->timestamp;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+376
@@ -0,0 +1,376 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
use DomainException;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use UnexpectedValueException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSON Web Key implementation, based on this spec:
|
||||||
|
* https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41
|
||||||
|
*
|
||||||
|
* PHP version 5
|
||||||
|
*
|
||||||
|
* @category Authentication
|
||||||
|
* @package Authentication_JWT
|
||||||
|
* @author Bui Sy Nguyen <nguyenbs@gmail.com>
|
||||||
|
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
|
||||||
|
* @link https://github.com/firebase/php-jwt
|
||||||
|
*/
|
||||||
|
class JWK
|
||||||
|
{
|
||||||
|
private const OID = '1.2.840.10045.2.1';
|
||||||
|
private const ASN1_OBJECT_IDENTIFIER = 0x06;
|
||||||
|
private const ASN1_SEQUENCE = 0x10; // also defined in JWT
|
||||||
|
private const ASN1_BIT_STRING = 0x03;
|
||||||
|
private const EC_CURVES = [
|
||||||
|
'P-256' => '1.2.840.10045.3.1.7', // Len: 64
|
||||||
|
'secp256k1' => '1.3.132.0.10', // Len: 64
|
||||||
|
'P-384' => '1.3.132.0.34', // Len: 96
|
||||||
|
// 'P-521' => '1.3.132.0.35', // Len: 132 (not supported)
|
||||||
|
];
|
||||||
|
|
||||||
|
// Known standard curves from the IANA JOSE registry which are not supported
|
||||||
|
private const KNOWN_UNSUPPORTED_EC_CURVES = [
|
||||||
|
'P-521', // RFC 7518
|
||||||
|
'Ed25519', // RFC 8037
|
||||||
|
'Ed448', // RFC 8037
|
||||||
|
'X25519', // RFC 8037
|
||||||
|
'X448' // RFC 8037
|
||||||
|
];
|
||||||
|
|
||||||
|
// For keys with "kty" equal to "OKP" (Octet Key Pair), the "crv" parameter must contain the key subtype.
|
||||||
|
// This library supports the following subtypes:
|
||||||
|
private const OKP_SUBTYPES = [
|
||||||
|
'Ed25519' => true, // RFC 8037
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a set of JWK keys
|
||||||
|
*
|
||||||
|
* @param array<mixed> $jwks The JSON Web Key Set as an associative array
|
||||||
|
* @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
|
||||||
|
* JSON Web Key Set
|
||||||
|
*
|
||||||
|
* @return array<string, Key> An associative array of key IDs (kid) to Key objects
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException Provided JWK Set is empty
|
||||||
|
* @throws UnexpectedValueException Provided JWK Set was invalid
|
||||||
|
* @throws DomainException OpenSSL failure
|
||||||
|
*
|
||||||
|
* @uses parseKey
|
||||||
|
*/
|
||||||
|
public static function parseKeySet(#[\SensitiveParameter] array $jwks, ?string $defaultAlg = null): array
|
||||||
|
{
|
||||||
|
$keys = [];
|
||||||
|
|
||||||
|
if (!isset($jwks['keys'])) {
|
||||||
|
throw new UnexpectedValueException('"keys" member must exist in the JWK Set');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($jwks['keys'])) {
|
||||||
|
throw new InvalidArgumentException('JWK Set did not contain any keys');
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($jwks['keys'] as $k => $v) {
|
||||||
|
$kid = isset($v['kid']) ? $v['kid'] : $k;
|
||||||
|
if ($key = self::parseKey($v, $defaultAlg)) {
|
||||||
|
$keys[(string) $kid] = $key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (0 === \count($keys)) {
|
||||||
|
throw new UnexpectedValueException('No supported algorithms found in JWK Set');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a JWK key
|
||||||
|
*
|
||||||
|
* @param array<mixed> $jwk An individual JWK
|
||||||
|
* @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
|
||||||
|
* JSON Web Key Set
|
||||||
|
*
|
||||||
|
* @return Key The key object for the JWK
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException Provided JWK is empty
|
||||||
|
* @throws UnexpectedValueException Provided JWK was invalid
|
||||||
|
* @throws DomainException OpenSSL failure
|
||||||
|
*
|
||||||
|
* @uses createPemFromModulusAndExponent
|
||||||
|
*/
|
||||||
|
public static function parseKey(#[\SensitiveParameter] array $jwk, ?string $defaultAlg = null): ?Key
|
||||||
|
{
|
||||||
|
if (empty($jwk)) {
|
||||||
|
throw new InvalidArgumentException('JWK must not be empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($jwk['kty'])) {
|
||||||
|
throw new UnexpectedValueException('JWK must contain a "kty" parameter');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($jwk['alg'])) {
|
||||||
|
if (\is_null($defaultAlg)) {
|
||||||
|
// The "alg" parameter is optional in a KTY, but an algorithm is required
|
||||||
|
// for parsing in this library. Use the $defaultAlg parameter when parsing the
|
||||||
|
// key set in order to prevent this error.
|
||||||
|
// @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4
|
||||||
|
throw new UnexpectedValueException('JWK must contain an "alg" parameter');
|
||||||
|
}
|
||||||
|
$jwk['alg'] = $defaultAlg;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch ($jwk['kty']) {
|
||||||
|
case 'RSA':
|
||||||
|
if (!empty($jwk['d'])) {
|
||||||
|
throw new UnexpectedValueException('RSA private keys are not supported');
|
||||||
|
}
|
||||||
|
if (!isset($jwk['n']) || !isset($jwk['e'])) {
|
||||||
|
throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"');
|
||||||
|
}
|
||||||
|
|
||||||
|
$pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']);
|
||||||
|
$publicKey = \openssl_pkey_get_public($pem);
|
||||||
|
if (false === $publicKey) {
|
||||||
|
throw new DomainException(
|
||||||
|
'OpenSSL error: ' . \openssl_error_string()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return new Key($publicKey, $jwk['alg']);
|
||||||
|
case 'EC':
|
||||||
|
if (isset($jwk['d'])) {
|
||||||
|
// The key is actually a private key
|
||||||
|
throw new UnexpectedValueException('Key data must be for a public key');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($jwk['crv'])) {
|
||||||
|
throw new UnexpectedValueException('crv not set');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset(self::EC_CURVES[$jwk['crv']])) {
|
||||||
|
if (!\in_array($jwk['crv'], self::KNOWN_UNSUPPORTED_EC_CURVES)) {
|
||||||
|
throw new DomainException('Unrecognised EC curve');
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($jwk['x']) || empty($jwk['y'])) {
|
||||||
|
throw new UnexpectedValueException('x and y not set');
|
||||||
|
}
|
||||||
|
|
||||||
|
$publicKey = self::createPemFromCrvAndXYCoordinates($jwk['crv'], $jwk['x'], $jwk['y']);
|
||||||
|
return new Key($publicKey, $jwk['alg']);
|
||||||
|
case 'OKP':
|
||||||
|
if (isset($jwk['d'])) {
|
||||||
|
// The key is actually a private key
|
||||||
|
throw new UnexpectedValueException('Key data must be for a public key');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($jwk['crv'])) {
|
||||||
|
throw new UnexpectedValueException('crv not set');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty(self::OKP_SUBTYPES[$jwk['crv']])) {
|
||||||
|
throw new DomainException('Unrecognised or unsupported OKP key subtype');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($jwk['x'])) {
|
||||||
|
throw new UnexpectedValueException('x not set');
|
||||||
|
}
|
||||||
|
|
||||||
|
// This library works internally with EdDSA keys (Ed25519) encoded in standard base64.
|
||||||
|
$publicKey = JWT::convertBase64urlToBase64($jwk['x']);
|
||||||
|
return new Key($publicKey, $jwk['alg']);
|
||||||
|
case 'oct':
|
||||||
|
if (!isset($jwk['k'])) {
|
||||||
|
throw new UnexpectedValueException('k not set');
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Key(JWT::urlsafeB64Decode($jwk['k']), $jwk['alg']);
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts the EC JWK values to pem format.
|
||||||
|
*
|
||||||
|
* @param string $crv The EC curve (only P-256 & P-384 is supported)
|
||||||
|
* @param string $x The EC x-coordinate
|
||||||
|
* @param string $y The EC y-coordinate
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
private static function createPemFromCrvAndXYCoordinates(string $crv, string $x, string $y): string
|
||||||
|
{
|
||||||
|
$pem =
|
||||||
|
self::encodeDER(
|
||||||
|
self::ASN1_SEQUENCE,
|
||||||
|
self::encodeDER(
|
||||||
|
self::ASN1_SEQUENCE,
|
||||||
|
self::encodeDER(
|
||||||
|
self::ASN1_OBJECT_IDENTIFIER,
|
||||||
|
self::encodeOID(self::OID)
|
||||||
|
)
|
||||||
|
. self::encodeDER(
|
||||||
|
self::ASN1_OBJECT_IDENTIFIER,
|
||||||
|
self::encodeOID(self::EC_CURVES[$crv])
|
||||||
|
)
|
||||||
|
) .
|
||||||
|
self::encodeDER(
|
||||||
|
self::ASN1_BIT_STRING,
|
||||||
|
\chr(0x00) . \chr(0x04)
|
||||||
|
. JWT::urlsafeB64Decode($x)
|
||||||
|
. JWT::urlsafeB64Decode($y)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
return \sprintf(
|
||||||
|
"-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n",
|
||||||
|
wordwrap(base64_encode($pem), 64, "\n", true)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a public key represented in PEM format from RSA modulus and exponent information
|
||||||
|
*
|
||||||
|
* @param string $n The RSA modulus encoded in Base64
|
||||||
|
* @param string $e The RSA exponent encoded in Base64
|
||||||
|
*
|
||||||
|
* @return string The RSA public key represented in PEM format
|
||||||
|
*
|
||||||
|
* @uses encodeLength
|
||||||
|
*/
|
||||||
|
private static function createPemFromModulusAndExponent(
|
||||||
|
string $n,
|
||||||
|
string $e
|
||||||
|
): string {
|
||||||
|
$mod = JWT::urlsafeB64Decode($n);
|
||||||
|
$exp = JWT::urlsafeB64Decode($e);
|
||||||
|
// Correct encoding for ASN1, as ints are represented as unsigned in jwk
|
||||||
|
// but signed in ASN1. Prepending null byte makes it unsigned.
|
||||||
|
if (\strlen($mod) > 0 && \ord($mod[0]) >= 128) {
|
||||||
|
$mod = \chr(0) . $mod;
|
||||||
|
}
|
||||||
|
if (\strlen($exp) > 0 && \ord($exp[0]) >= 128) {
|
||||||
|
$exp = \chr(0) . $exp;
|
||||||
|
}
|
||||||
|
|
||||||
|
$modulus = \pack('Ca*a*', 2, self::encodeLength(\strlen($mod)), $mod);
|
||||||
|
$publicExponent = \pack('Ca*a*', 2, self::encodeLength(\strlen($exp)), $exp);
|
||||||
|
|
||||||
|
$rsaPublicKey = \pack(
|
||||||
|
'Ca*a*a*',
|
||||||
|
48,
|
||||||
|
self::encodeLength(\strlen($modulus) + \strlen($publicExponent)),
|
||||||
|
$modulus,
|
||||||
|
$publicExponent
|
||||||
|
);
|
||||||
|
|
||||||
|
// sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
|
||||||
|
$rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
|
||||||
|
$rsaPublicKey = \chr(0) . $rsaPublicKey;
|
||||||
|
$rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey;
|
||||||
|
|
||||||
|
$rsaPublicKey = \pack(
|
||||||
|
'Ca*a*',
|
||||||
|
48,
|
||||||
|
self::encodeLength(\strlen($rsaOID . $rsaPublicKey)),
|
||||||
|
$rsaOID . $rsaPublicKey
|
||||||
|
);
|
||||||
|
|
||||||
|
return "-----BEGIN PUBLIC KEY-----\r\n" .
|
||||||
|
\chunk_split(\base64_encode($rsaPublicKey), 64) .
|
||||||
|
'-----END PUBLIC KEY-----';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DER-encode the length
|
||||||
|
*
|
||||||
|
* DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
|
||||||
|
* {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3}
|
||||||
|
* for more information.
|
||||||
|
*
|
||||||
|
* @param int $length
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
private static function encodeLength(int $length): string
|
||||||
|
{
|
||||||
|
if ($length <= 0x7F) {
|
||||||
|
return \chr($length);
|
||||||
|
}
|
||||||
|
|
||||||
|
$temp = \ltrim(\pack('N', $length), \chr(0));
|
||||||
|
|
||||||
|
return \pack('Ca*', 0x80 | \strlen($temp), $temp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encodes a value into a DER object.
|
||||||
|
* Also defined in Firebase\JWT\JWT
|
||||||
|
*
|
||||||
|
* @param int $type DER tag
|
||||||
|
* @param string $value the value to encode
|
||||||
|
* @return string the encoded object
|
||||||
|
*/
|
||||||
|
private static function encodeDER(int $type, string $value): string
|
||||||
|
{
|
||||||
|
$tag_header = 0;
|
||||||
|
if ($type === self::ASN1_SEQUENCE) {
|
||||||
|
$tag_header |= 0x20;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type
|
||||||
|
$der = \chr($tag_header | $type);
|
||||||
|
|
||||||
|
// Length
|
||||||
|
$der .= \chr(\strlen($value));
|
||||||
|
|
||||||
|
return $der . $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encodes a string into a DER-encoded OID.
|
||||||
|
*
|
||||||
|
* @param string $oid the OID string
|
||||||
|
* @return string the binary DER-encoded OID
|
||||||
|
*/
|
||||||
|
private static function encodeOID(string $oid): string
|
||||||
|
{
|
||||||
|
$octets = explode('.', $oid);
|
||||||
|
|
||||||
|
// Get the first octet
|
||||||
|
$first = (int) array_shift($octets);
|
||||||
|
$second = (int) array_shift($octets);
|
||||||
|
$oid = \chr($first * 40 + $second);
|
||||||
|
|
||||||
|
// Iterate over subsequent octets
|
||||||
|
foreach ($octets as $octet) {
|
||||||
|
if ($octet == 0) {
|
||||||
|
$oid .= \chr(0x00);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$bin = '';
|
||||||
|
|
||||||
|
while ($octet) {
|
||||||
|
$bin .= \chr(0x80 | ($octet & 0x7f));
|
||||||
|
$octet >>= 7;
|
||||||
|
}
|
||||||
|
$bin[0] = $bin[0] & \chr(0x7f);
|
||||||
|
|
||||||
|
// Convert to big endian if necessary
|
||||||
|
if (pack('V', 65534) == pack('L', 65534)) {
|
||||||
|
$oid .= strrev($bin);
|
||||||
|
} else {
|
||||||
|
$oid .= $bin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $oid;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+835
@@ -0,0 +1,835 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
use ArrayAccess;
|
||||||
|
use DateTime;
|
||||||
|
use DomainException;
|
||||||
|
use Exception;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use OpenSSLAsymmetricKey;
|
||||||
|
use OpenSSLCertificate;
|
||||||
|
use stdClass;
|
||||||
|
use UnexpectedValueException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSON Web Token implementation, based on this spec:
|
||||||
|
* https://tools.ietf.org/html/rfc7519
|
||||||
|
*
|
||||||
|
* PHP version 5
|
||||||
|
*
|
||||||
|
* @category Authentication
|
||||||
|
* @package Authentication_JWT
|
||||||
|
* @author Neuman Vong <neuman@twilio.com>
|
||||||
|
* @author Anant Narayanan <anant@php.net>
|
||||||
|
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
|
||||||
|
* @link https://github.com/firebase/php-jwt
|
||||||
|
*/
|
||||||
|
class JWT
|
||||||
|
{
|
||||||
|
private const ASN1_INTEGER = 0x02;
|
||||||
|
private const ASN1_SEQUENCE = 0x10;
|
||||||
|
private const ASN1_BIT_STRING = 0x03;
|
||||||
|
|
||||||
|
private const RSA_KEY_MIN_LENGTH = 2048;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When checking nbf, iat or expiration times,
|
||||||
|
* we want to provide some extra leeway time to
|
||||||
|
* account for clock skew.
|
||||||
|
*
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
public static $leeway = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allow the current timestamp to be specified.
|
||||||
|
* Useful for fixing a value within unit testing.
|
||||||
|
* Will default to PHP time() value if null.
|
||||||
|
*
|
||||||
|
* @var ?int
|
||||||
|
*/
|
||||||
|
public static $timestamp = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, string[]>
|
||||||
|
*/
|
||||||
|
public static $supported_algs = [
|
||||||
|
'ES384' => ['openssl', 'SHA384'],
|
||||||
|
'ES256' => ['openssl', 'SHA256'],
|
||||||
|
'ES256K' => ['openssl', 'SHA256'],
|
||||||
|
'HS256' => ['hash_hmac', 'SHA256'],
|
||||||
|
'HS384' => ['hash_hmac', 'SHA384'],
|
||||||
|
'HS512' => ['hash_hmac', 'SHA512'],
|
||||||
|
'RS256' => ['openssl', 'SHA256'],
|
||||||
|
'RS384' => ['openssl', 'SHA384'],
|
||||||
|
'RS512' => ['openssl', 'SHA512'],
|
||||||
|
'PS256' => ['openssl', 'SHA256'],
|
||||||
|
'EdDSA' => ['sodium_crypto', 'EdDSA']
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes a JWT string into a PHP object.
|
||||||
|
*
|
||||||
|
* @param string $jwt The JWT
|
||||||
|
* @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs
|
||||||
|
* (kid) to Key objects.
|
||||||
|
* If the algorithm used is asymmetric, this is
|
||||||
|
* the public key.
|
||||||
|
* Each Key object contains an algorithm and
|
||||||
|
* matching key.
|
||||||
|
* Supported algorithms are 'ES384','ES256',
|
||||||
|
* 'HS256', 'HS384', 'HS512', 'RS256', 'RS384'
|
||||||
|
* and 'RS512'.
|
||||||
|
* @param stdClass $headers Optional. Populates stdClass with headers.
|
||||||
|
*
|
||||||
|
* @return stdClass The JWT's payload as a PHP object
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException Provided key/key-array was empty or malformed
|
||||||
|
* @throws DomainException Provided JWT is malformed
|
||||||
|
* @throws UnexpectedValueException Provided JWT was invalid
|
||||||
|
* @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
|
||||||
|
* @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
|
||||||
|
* @throws BeforeValidException Provided JWT is trying to be used before it's
|
||||||
|
* been created as defined by 'iat'
|
||||||
|
* @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
|
||||||
|
*
|
||||||
|
* @uses jsonDecode
|
||||||
|
* @uses urlsafeB64Decode
|
||||||
|
*/
|
||||||
|
public static function decode(
|
||||||
|
string $jwt,
|
||||||
|
#[\SensitiveParameter] $keyOrKeyArray,
|
||||||
|
?stdClass &$headers = null
|
||||||
|
): stdClass {
|
||||||
|
// Validate JWT
|
||||||
|
$timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
|
||||||
|
|
||||||
|
if (empty($keyOrKeyArray)) {
|
||||||
|
throw new InvalidArgumentException('Key may not be empty');
|
||||||
|
}
|
||||||
|
$tks = \explode('.', $jwt, 4);
|
||||||
|
if (\count($tks) !== 3) {
|
||||||
|
throw new UnexpectedValueException('Wrong number of segments');
|
||||||
|
}
|
||||||
|
list($headb64, $bodyb64, $cryptob64) = $tks;
|
||||||
|
$headerRaw = static::urlsafeB64Decode($headb64);
|
||||||
|
if (null === ($header = static::jsonDecode($headerRaw))) {
|
||||||
|
throw new UnexpectedValueException('Invalid header encoding');
|
||||||
|
}
|
||||||
|
if ($headers !== null) {
|
||||||
|
$headers = $header;
|
||||||
|
}
|
||||||
|
$payloadRaw = static::urlsafeB64Decode($bodyb64);
|
||||||
|
if (null === ($payload = static::jsonDecode($payloadRaw))) {
|
||||||
|
throw new UnexpectedValueException('Invalid claims encoding');
|
||||||
|
}
|
||||||
|
if (\is_array($payload)) {
|
||||||
|
// prevent PHP Fatal Error in edge-cases when payload is empty array
|
||||||
|
$payload = (object) $payload;
|
||||||
|
}
|
||||||
|
if (!$payload instanceof stdClass) {
|
||||||
|
throw new UnexpectedValueException('Payload must be a JSON object');
|
||||||
|
}
|
||||||
|
if (isset($payload->iat) && !\is_numeric($payload->iat)) {
|
||||||
|
throw new UnexpectedValueException('Payload iat must be a number');
|
||||||
|
}
|
||||||
|
if (isset($payload->nbf) && !\is_numeric($payload->nbf)) {
|
||||||
|
throw new UnexpectedValueException('Payload nbf must be a number');
|
||||||
|
}
|
||||||
|
if (isset($payload->exp) && !\is_numeric($payload->exp)) {
|
||||||
|
throw new UnexpectedValueException('Payload exp must be a number');
|
||||||
|
}
|
||||||
|
|
||||||
|
$sig = static::urlsafeB64Decode($cryptob64);
|
||||||
|
if (empty($header->alg)) {
|
||||||
|
throw new UnexpectedValueException('Empty algorithm');
|
||||||
|
}
|
||||||
|
if (empty(static::$supported_algs[$header->alg])) {
|
||||||
|
throw new UnexpectedValueException('Algorithm not supported');
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null);
|
||||||
|
|
||||||
|
// Check the algorithm
|
||||||
|
if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) {
|
||||||
|
// See issue #351
|
||||||
|
throw new UnexpectedValueException('Incorrect key for this algorithm');
|
||||||
|
}
|
||||||
|
if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) {
|
||||||
|
// OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures
|
||||||
|
$sig = self::signatureToDER($sig);
|
||||||
|
}
|
||||||
|
if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) {
|
||||||
|
throw new SignatureInvalidException('Signature verification failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check the nbf if it is defined. This is the time that the
|
||||||
|
// token can actually be used. If it's not yet that time, abort.
|
||||||
|
if (isset($payload->nbf) && floor($payload->nbf) > ($timestamp + static::$leeway)) {
|
||||||
|
$ex = new BeforeValidException(
|
||||||
|
'Cannot handle token with nbf prior to ' . \date(DateTime::ATOM, (int) floor($payload->nbf))
|
||||||
|
);
|
||||||
|
$ex->setPayload($payload);
|
||||||
|
throw $ex;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check that this token has been created before 'now'. This prevents
|
||||||
|
// using tokens that have been created for later use (and haven't
|
||||||
|
// correctly used the nbf claim).
|
||||||
|
if (!isset($payload->nbf) && isset($payload->iat) && floor($payload->iat) > ($timestamp + static::$leeway)) {
|
||||||
|
$ex = new BeforeValidException(
|
||||||
|
'Cannot handle token with iat prior to ' . \date(DateTime::ATOM, (int) floor($payload->iat))
|
||||||
|
);
|
||||||
|
$ex->setPayload($payload);
|
||||||
|
throw $ex;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if this token has expired.
|
||||||
|
if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
|
||||||
|
$ex = new ExpiredException('Expired token');
|
||||||
|
$ex->setPayload($payload);
|
||||||
|
$ex->setTimestamp($timestamp);
|
||||||
|
throw $ex;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts and signs a PHP array into a JWT string.
|
||||||
|
*
|
||||||
|
* @param array<mixed> $payload PHP array
|
||||||
|
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
|
||||||
|
* @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
|
||||||
|
* 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
|
||||||
|
* @param string $keyId
|
||||||
|
* @param array<string, string|string[]> $head An array with header elements to attach
|
||||||
|
*
|
||||||
|
* @return string A signed JWT
|
||||||
|
*
|
||||||
|
* @uses jsonEncode
|
||||||
|
* @uses urlsafeB64Encode
|
||||||
|
*/
|
||||||
|
public static function encode(
|
||||||
|
array $payload,
|
||||||
|
#[\SensitiveParameter] $key,
|
||||||
|
string $alg,
|
||||||
|
?string $keyId = null,
|
||||||
|
?array $head = null
|
||||||
|
): string {
|
||||||
|
$header = ['typ' => 'JWT'];
|
||||||
|
if (isset($head)) {
|
||||||
|
$header = \array_merge($header, $head);
|
||||||
|
}
|
||||||
|
$header['alg'] = $alg;
|
||||||
|
if ($keyId !== null) {
|
||||||
|
$header['kid'] = $keyId;
|
||||||
|
}
|
||||||
|
if (isset($payload['nbf']) && !\is_numeric($payload['nbf'])) {
|
||||||
|
throw new UnexpectedValueException('Payload nbf must be a number');
|
||||||
|
}
|
||||||
|
if (isset($payload['iat']) && !\is_numeric($payload['iat'])) {
|
||||||
|
throw new UnexpectedValueException('Payload iat must be a number');
|
||||||
|
}
|
||||||
|
if (isset($payload['exp']) && !\is_numeric($payload['exp'])) {
|
||||||
|
throw new UnexpectedValueException('Payload exp must be a number');
|
||||||
|
}
|
||||||
|
$segments = [];
|
||||||
|
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
|
||||||
|
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
|
||||||
|
$signing_input = \implode('.', $segments);
|
||||||
|
|
||||||
|
$signature = static::sign($signing_input, $key, $alg);
|
||||||
|
$segments[] = static::urlsafeB64Encode($signature);
|
||||||
|
|
||||||
|
return \implode('.', $segments);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign a string with a given key and algorithm.
|
||||||
|
*
|
||||||
|
* @param string $msg The message to sign
|
||||||
|
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
|
||||||
|
* @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256',
|
||||||
|
* 'HS384', 'HS512', 'RS256', 'RS384', 'PS256' and 'RS512'
|
||||||
|
*
|
||||||
|
* @return string An encrypted message
|
||||||
|
*
|
||||||
|
* @throws DomainException Unsupported algorithm or bad key was specified
|
||||||
|
*/
|
||||||
|
public static function sign(
|
||||||
|
string $msg,
|
||||||
|
#[\SensitiveParameter] $key,
|
||||||
|
string $alg
|
||||||
|
): string {
|
||||||
|
if (empty(static::$supported_algs[$alg])) {
|
||||||
|
throw new DomainException('Algorithm not supported');
|
||||||
|
}
|
||||||
|
list($function, $algorithm) = static::$supported_algs[$alg];
|
||||||
|
switch ($function) {
|
||||||
|
case 'hash_hmac':
|
||||||
|
if (!\is_string($key)) {
|
||||||
|
throw new InvalidArgumentException('key must be a string when using hmac');
|
||||||
|
}
|
||||||
|
self::validateHmacKeyLength($key, $algorithm);
|
||||||
|
return \hash_hmac($algorithm, $msg, $key, true);
|
||||||
|
case 'openssl':
|
||||||
|
if ($alg === 'PS256') {
|
||||||
|
return self::signPS256($key, $msg);
|
||||||
|
}
|
||||||
|
$signature = '';
|
||||||
|
if (!$key = openssl_pkey_get_private($key)) {
|
||||||
|
throw new DomainException('OpenSSL unable to validate key');
|
||||||
|
}
|
||||||
|
if (str_starts_with($alg, 'RS')) {
|
||||||
|
self::validateRsaKeyLength($key);
|
||||||
|
} elseif (str_starts_with($alg, 'ES')) {
|
||||||
|
self::validateEcKeyLength($key, $alg);
|
||||||
|
}
|
||||||
|
$success = \openssl_sign($msg, $signature, $key, $algorithm);
|
||||||
|
if (!$success) {
|
||||||
|
throw new DomainException('OpenSSL unable to sign data');
|
||||||
|
}
|
||||||
|
if ($alg === 'ES256' || $alg === 'ES256K') {
|
||||||
|
$signature = self::signatureFromDER($signature, 256);
|
||||||
|
} elseif ($alg === 'ES384') {
|
||||||
|
$signature = self::signatureFromDER($signature, 384);
|
||||||
|
}
|
||||||
|
return $signature;
|
||||||
|
case 'sodium_crypto':
|
||||||
|
try {
|
||||||
|
return sodium_crypto_sign_detached($msg, self::validateEdDSAKey($key));
|
||||||
|
} catch (Exception $e) {
|
||||||
|
throw new DomainException($e->getMessage(), 0, $e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new DomainException('Algorithm not supported');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a signature with the message, key and method. Not all methods
|
||||||
|
* are symmetric, so we must have a separate verify and sign method.
|
||||||
|
*
|
||||||
|
* @param string $msg The original message (header and body)
|
||||||
|
* @param string $signature The original signature
|
||||||
|
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works.
|
||||||
|
* for RS*, must be an instance of OpenSSLAsymmetricKey
|
||||||
|
* @param string $alg The algorithm
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*
|
||||||
|
* @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
|
||||||
|
*/
|
||||||
|
private static function verify(
|
||||||
|
string $msg,
|
||||||
|
string $signature,
|
||||||
|
#[\SensitiveParameter] $keyMaterial,
|
||||||
|
string $alg
|
||||||
|
): bool {
|
||||||
|
if (empty(static::$supported_algs[$alg])) {
|
||||||
|
throw new DomainException('Algorithm not supported');
|
||||||
|
}
|
||||||
|
|
||||||
|
list($function, $algorithm) = static::$supported_algs[$alg];
|
||||||
|
switch ($function) {
|
||||||
|
case 'openssl':
|
||||||
|
if ($alg === 'PS256') {
|
||||||
|
return self::verifyPS256($keyMaterial, $msg, $signature);
|
||||||
|
}
|
||||||
|
if (!$key = openssl_pkey_get_public($keyMaterial)) {
|
||||||
|
throw new DomainException('OpenSSL unable to validate key');
|
||||||
|
}
|
||||||
|
if (str_starts_with($alg, 'RS')) {
|
||||||
|
self::validateRsaKeyLength($key);
|
||||||
|
} elseif (str_starts_with($alg, 'ES')) {
|
||||||
|
self::validateEcKeyLength($key, $alg);
|
||||||
|
}
|
||||||
|
$success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm);
|
||||||
|
if ($success === 1) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if ($success === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// returns 1 on success, 0 on failure, -1 on error.
|
||||||
|
throw new DomainException(
|
||||||
|
'OpenSSL error: ' . \openssl_error_string()
|
||||||
|
);
|
||||||
|
case 'sodium_crypto':
|
||||||
|
try {
|
||||||
|
$key = self::validateEdDSAKey($keyMaterial);
|
||||||
|
if (\strlen($signature) === 0) {
|
||||||
|
throw new DomainException('Signature cannot be empty string');
|
||||||
|
}
|
||||||
|
return sodium_crypto_sign_verify_detached($signature, $msg, $key);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
throw new DomainException($e->getMessage(), 0, $e);
|
||||||
|
}
|
||||||
|
case 'hash_hmac':
|
||||||
|
default:
|
||||||
|
if (!\is_string($keyMaterial)) {
|
||||||
|
throw new InvalidArgumentException('key must be a string when using hmac');
|
||||||
|
}
|
||||||
|
self::validateHmacKeyLength($keyMaterial, $algorithm);
|
||||||
|
$hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
|
||||||
|
return self::constantTimeEquals($hash, $signature);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decode a JSON string into a PHP object.
|
||||||
|
*
|
||||||
|
* @param string $input JSON string
|
||||||
|
*
|
||||||
|
* @return mixed The decoded JSON string
|
||||||
|
*
|
||||||
|
* @throws DomainException Provided string was invalid JSON
|
||||||
|
*/
|
||||||
|
public static function jsonDecode(string $input)
|
||||||
|
{
|
||||||
|
$obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
|
||||||
|
|
||||||
|
if ($errno = \json_last_error()) {
|
||||||
|
self::handleJsonError($errno);
|
||||||
|
} elseif ($obj === null && $input !== 'null') {
|
||||||
|
throw new DomainException('Null result with non-null input');
|
||||||
|
}
|
||||||
|
return $obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encode a PHP array into a JSON string.
|
||||||
|
*
|
||||||
|
* @param array<mixed> $input A PHP array
|
||||||
|
*
|
||||||
|
* @return string JSON representation of the PHP array
|
||||||
|
*
|
||||||
|
* @throws DomainException Provided object could not be encoded to valid JSON
|
||||||
|
*/
|
||||||
|
public static function jsonEncode(array $input): string
|
||||||
|
{
|
||||||
|
$json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
|
||||||
|
if ($errno = \json_last_error()) {
|
||||||
|
self::handleJsonError($errno);
|
||||||
|
} elseif ($json === 'null') {
|
||||||
|
throw new DomainException('Null result with non-null input');
|
||||||
|
}
|
||||||
|
if ($json === false) {
|
||||||
|
throw new DomainException('Provided object could not be encoded to valid JSON');
|
||||||
|
}
|
||||||
|
return $json;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decode a string with URL-safe Base64.
|
||||||
|
*
|
||||||
|
* @param string $input A Base64 encoded string
|
||||||
|
*
|
||||||
|
* @return string A decoded string
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException invalid base64 characters
|
||||||
|
*/
|
||||||
|
public static function urlsafeB64Decode(string $input): string
|
||||||
|
{
|
||||||
|
return \base64_decode(self::convertBase64UrlToBase64($input));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a string in the base64url (URL-safe Base64) encoding to standard base64.
|
||||||
|
*
|
||||||
|
* @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding)
|
||||||
|
*
|
||||||
|
* @return string A Base64 encoded string with standard characters (+/) and padding (=), when
|
||||||
|
* needed.
|
||||||
|
*
|
||||||
|
* @see https://www.rfc-editor.org/rfc/rfc4648
|
||||||
|
*/
|
||||||
|
public static function convertBase64UrlToBase64(string $input): string
|
||||||
|
{
|
||||||
|
$remainder = \strlen($input) % 4;
|
||||||
|
if ($remainder) {
|
||||||
|
$padlen = 4 - $remainder;
|
||||||
|
$input .= \str_repeat('=', $padlen);
|
||||||
|
}
|
||||||
|
return \strtr($input, '-_', '+/');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encode a string with URL-safe Base64.
|
||||||
|
*
|
||||||
|
* @param string $input The string you want encoded
|
||||||
|
*
|
||||||
|
* @return string The base64 encode of what you passed in
|
||||||
|
*/
|
||||||
|
public static function urlsafeB64Encode(string $input): string
|
||||||
|
{
|
||||||
|
return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if an algorithm has been provided for each Key
|
||||||
|
*
|
||||||
|
* @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray
|
||||||
|
* @param string|null $kid
|
||||||
|
*
|
||||||
|
* @throws UnexpectedValueException
|
||||||
|
*
|
||||||
|
* @return Key
|
||||||
|
*/
|
||||||
|
private static function getKey(
|
||||||
|
#[\SensitiveParameter] $keyOrKeyArray,
|
||||||
|
?string $kid
|
||||||
|
): Key {
|
||||||
|
if ($keyOrKeyArray instanceof Key) {
|
||||||
|
return $keyOrKeyArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($kid) && $kid !== '0') {
|
||||||
|
throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($keyOrKeyArray instanceof CachedKeySet) {
|
||||||
|
// Skip "isset" check, as this will automatically refresh if not set
|
||||||
|
return $keyOrKeyArray[$kid];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($keyOrKeyArray[$kid])) {
|
||||||
|
throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $keyOrKeyArray[$kid];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $left The string of known length to compare against
|
||||||
|
* @param string $right The user-supplied string
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public static function constantTimeEquals(string $left, string $right): bool
|
||||||
|
{
|
||||||
|
if (\function_exists('hash_equals')) {
|
||||||
|
return \hash_equals($left, $right);
|
||||||
|
}
|
||||||
|
$len = \min(self::safeStrlen($left), self::safeStrlen($right));
|
||||||
|
|
||||||
|
$status = 0;
|
||||||
|
for ($i = 0; $i < $len; $i++) {
|
||||||
|
$status |= (\ord($left[$i]) ^ \ord($right[$i]));
|
||||||
|
}
|
||||||
|
$status |= (self::safeStrlen($left) ^ self::safeStrlen($right));
|
||||||
|
|
||||||
|
return ($status === 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to create a JSON error.
|
||||||
|
*
|
||||||
|
* @param int $errno An error number from json_last_error()
|
||||||
|
*
|
||||||
|
* @throws DomainException
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function handleJsonError(int $errno): void
|
||||||
|
{
|
||||||
|
$messages = [
|
||||||
|
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
|
||||||
|
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
|
||||||
|
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
|
||||||
|
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
|
||||||
|
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
|
||||||
|
];
|
||||||
|
throw new DomainException(
|
||||||
|
isset($messages[$errno])
|
||||||
|
? $messages[$errno]
|
||||||
|
: 'Unknown JSON error: ' . $errno
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the number of bytes in cryptographic strings.
|
||||||
|
*
|
||||||
|
* @param string $str
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
private static function safeStrlen(string $str): int
|
||||||
|
{
|
||||||
|
if (\function_exists('mb_strlen')) {
|
||||||
|
return \mb_strlen($str, '8bit');
|
||||||
|
}
|
||||||
|
return \strlen($str);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert an ECDSA signature to an ASN.1 DER sequence
|
||||||
|
*
|
||||||
|
* @param string $sig The ECDSA signature to convert
|
||||||
|
* @return string The encoded DER object
|
||||||
|
*/
|
||||||
|
private static function signatureToDER(string $sig): string
|
||||||
|
{
|
||||||
|
// Separate the signature into r-value and s-value
|
||||||
|
$length = max(1, (int) (\strlen($sig) / 2));
|
||||||
|
list($r, $s) = \str_split($sig, $length);
|
||||||
|
|
||||||
|
// Trim leading zeros
|
||||||
|
$r = \ltrim($r, "\x00");
|
||||||
|
$s = \ltrim($s, "\x00");
|
||||||
|
|
||||||
|
// Convert r-value and s-value from unsigned big-endian integers to
|
||||||
|
// signed two's complement
|
||||||
|
if (\ord($r[0]) > 0x7f) {
|
||||||
|
$r = "\x00" . $r;
|
||||||
|
}
|
||||||
|
if (\ord($s[0]) > 0x7f) {
|
||||||
|
$s = "\x00" . $s;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::encodeDER(
|
||||||
|
self::ASN1_SEQUENCE,
|
||||||
|
self::encodeDER(self::ASN1_INTEGER, $r) .
|
||||||
|
self::encodeDER(self::ASN1_INTEGER, $s)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encodes a value into a DER object.
|
||||||
|
*
|
||||||
|
* @param int $type DER tag
|
||||||
|
* @param string $value the value to encode
|
||||||
|
*
|
||||||
|
* @return string the encoded object
|
||||||
|
*/
|
||||||
|
private static function encodeDER(int $type, string $value): string
|
||||||
|
{
|
||||||
|
$tag_header = 0;
|
||||||
|
if ($type === self::ASN1_SEQUENCE) {
|
||||||
|
$tag_header |= 0x20;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type
|
||||||
|
$der = \chr($tag_header | $type);
|
||||||
|
|
||||||
|
// Length
|
||||||
|
$der .= \chr(\strlen($value));
|
||||||
|
|
||||||
|
return $der . $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encodes signature from a DER object.
|
||||||
|
*
|
||||||
|
* @param string $der binary signature in DER format
|
||||||
|
* @param int $keySize the number of bits in the key
|
||||||
|
*
|
||||||
|
* @return string the signature
|
||||||
|
*/
|
||||||
|
private static function signatureFromDER(string $der, int $keySize): string
|
||||||
|
{
|
||||||
|
// OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
|
||||||
|
list($offset, $_) = self::readDER($der);
|
||||||
|
list($offset, $r) = self::readDER($der, $offset);
|
||||||
|
list($offset, $s) = self::readDER($der, $offset);
|
||||||
|
|
||||||
|
// Convert r-value and s-value from signed two's compliment to unsigned
|
||||||
|
// big-endian integers
|
||||||
|
$r = \ltrim($r, "\x00");
|
||||||
|
$s = \ltrim($s, "\x00");
|
||||||
|
|
||||||
|
// Pad out r and s so that they are $keySize bits long
|
||||||
|
$r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
|
||||||
|
$s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
|
||||||
|
|
||||||
|
return $r . $s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads binary DER-encoded data and decodes into a single object
|
||||||
|
*
|
||||||
|
* @param string $der the binary data in DER format
|
||||||
|
* @param int $offset the offset of the data stream containing the object
|
||||||
|
* to decode
|
||||||
|
*
|
||||||
|
* @return array{int, string|null} the new offset and the decoded object
|
||||||
|
*/
|
||||||
|
private static function readDER(string $der, int $offset = 0): array
|
||||||
|
{
|
||||||
|
$pos = $offset;
|
||||||
|
$size = \strlen($der);
|
||||||
|
$constructed = (\ord($der[$pos]) >> 5) & 0x01;
|
||||||
|
$type = \ord($der[$pos++]) & 0x1f;
|
||||||
|
|
||||||
|
// Length
|
||||||
|
$len = \ord($der[$pos++]);
|
||||||
|
if ($len & 0x80) {
|
||||||
|
$n = $len & 0x1f;
|
||||||
|
$len = 0;
|
||||||
|
while ($n-- && $pos < $size) {
|
||||||
|
$len = ($len << 8) | \ord($der[$pos++]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Value
|
||||||
|
if ($type === self::ASN1_BIT_STRING) {
|
||||||
|
$pos++; // Skip the first contents octet (padding indicator)
|
||||||
|
$data = \substr($der, $pos, $len - 1);
|
||||||
|
$pos += $len - 1;
|
||||||
|
} elseif (!$constructed) {
|
||||||
|
$data = \substr($der, $pos, $len);
|
||||||
|
$pos += $len;
|
||||||
|
} else {
|
||||||
|
$data = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$pos, $data];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate HMAC key length
|
||||||
|
*
|
||||||
|
* @param string $key HMAC key material
|
||||||
|
* @param string $algorithm The algorithm
|
||||||
|
*
|
||||||
|
* @throws DomainException Provided key is too short
|
||||||
|
*/
|
||||||
|
private static function validateHmacKeyLength(string $key, string $algorithm): void
|
||||||
|
{
|
||||||
|
$keyLength = \strlen($key) * 8;
|
||||||
|
$minKeyLength = (int) \str_replace('SHA', '', $algorithm);
|
||||||
|
if ($keyLength < $minKeyLength) {
|
||||||
|
throw new DomainException('Provided key is too short');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate RSA key length
|
||||||
|
*
|
||||||
|
* @param OpenSSLAsymmetricKey $key RSA key material
|
||||||
|
* @throws DomainException Provided key is too short
|
||||||
|
*/
|
||||||
|
private static function validateRsaKeyLength(#[\SensitiveParameter] OpenSSLAsymmetricKey $key): void
|
||||||
|
{
|
||||||
|
if (!$keyDetails = openssl_pkey_get_details($key)) {
|
||||||
|
throw new DomainException('Unable to validate key');
|
||||||
|
}
|
||||||
|
if ($keyDetails['bits'] < self::RSA_KEY_MIN_LENGTH) {
|
||||||
|
throw new DomainException('Provided key is too short');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate RSA key length
|
||||||
|
*
|
||||||
|
* @param OpenSSLAsymmetricKey $key RSA key material
|
||||||
|
* @param string $algorithm The algorithm
|
||||||
|
* @throws DomainException Provided key is too short
|
||||||
|
*/
|
||||||
|
private static function validateEcKeyLength(
|
||||||
|
#[\SensitiveParameter] OpenSSLAsymmetricKey $key,
|
||||||
|
string $algorithm
|
||||||
|
): void {
|
||||||
|
if (!$keyDetails = openssl_pkey_get_details($key)) {
|
||||||
|
throw new DomainException('Unable to validate key');
|
||||||
|
}
|
||||||
|
$minKeyLength = (int) \str_replace('ES', '', $algorithm);
|
||||||
|
if ($keyDetails['bits'] < $minKeyLength) {
|
||||||
|
throw new DomainException('Provided key is too short');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial
|
||||||
|
* @return non-empty-string
|
||||||
|
*/
|
||||||
|
private static function validateEdDSAKey(#[\SensitiveParameter] $keyMaterial): string
|
||||||
|
{
|
||||||
|
if (!\function_exists('sodium_crypto_sign_verify_detached')) {
|
||||||
|
throw new DomainException('libsodium is not available');
|
||||||
|
}
|
||||||
|
if (!\is_string($keyMaterial)) {
|
||||||
|
throw new InvalidArgumentException('key must be a string when using EdDSA');
|
||||||
|
}
|
||||||
|
// The last non-empty line is used as the key.
|
||||||
|
$lines = array_filter(explode("\n", $keyMaterial));
|
||||||
|
$key = self::urlsafeB64Decode((string) end($lines));
|
||||||
|
if (\strlen($key) === 0) {
|
||||||
|
throw new DomainException('Key cannot be empty string');
|
||||||
|
}
|
||||||
|
return $key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signs a message with a PS256 algorithm
|
||||||
|
*
|
||||||
|
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key
|
||||||
|
* @param string $message
|
||||||
|
* @throws DomainException Provided key is invalid
|
||||||
|
*/
|
||||||
|
private static function signPS256(
|
||||||
|
#[\SensitiveParameter] string|OpenSSLAsymmetricKey|OpenSSLCertificate $key,
|
||||||
|
string $message
|
||||||
|
): string {
|
||||||
|
if (!class_exists('\phpseclib3\Crypt\RSA')) {
|
||||||
|
throw new DomainException('phpseclib/phpseclib is required for PS256 support');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($key instanceof OpenSSLCertificate) {
|
||||||
|
throw new DomainException('Cannot sign with an X.509 certificate. A private key is required.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($key instanceof OpenSSLAsymmetricKey) {
|
||||||
|
if (!openssl_pkey_export($key, $pem)) {
|
||||||
|
throw new DomainException('OpenSSL unable to export the AsymmetricKey');
|
||||||
|
}
|
||||||
|
$key = $pem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var \phpseclib3\Crypt\RSA\PrivateKey $rsa */
|
||||||
|
$rsa = \phpseclib3\Crypt\PublicKeyLoader::load($key);
|
||||||
|
|
||||||
|
return $rsa->withPadding(\phpseclib3\Crypt\RSA::SIGNATURE_PSS)
|
||||||
|
->withHash('sha256')
|
||||||
|
->sign($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a PS256 algorithm signature.
|
||||||
|
*
|
||||||
|
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key
|
||||||
|
* @param string $message
|
||||||
|
* @param string $signature
|
||||||
|
* @throws DomainException Provided key is invalid
|
||||||
|
*/
|
||||||
|
private static function verifyPS256(
|
||||||
|
#[\SensitiveParameter] string|OpenSSLAsymmetricKey|OpenSSLCertificate $key,
|
||||||
|
string $message,
|
||||||
|
string $signature
|
||||||
|
): bool {
|
||||||
|
if (!class_exists('\phpseclib3\Crypt\RSA')) {
|
||||||
|
throw new DomainException('phpseclib/phpseclib is required for PS256 support');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($key instanceof OpenSSLAsymmetricKey) {
|
||||||
|
$details = openssl_pkey_get_details($key);
|
||||||
|
if (!$details || !isset($details['key'])) {
|
||||||
|
throw new DomainException('OpenSSL unable to extract public key');
|
||||||
|
}
|
||||||
|
$key = $details['key'];
|
||||||
|
} elseif ($key instanceof OpenSSLCertificate) {
|
||||||
|
if (!openssl_x509_export($key, $pem)) {
|
||||||
|
throw new DomainException('OpenSSL unable to export certificate');
|
||||||
|
}
|
||||||
|
$key = $pem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var \phpseclib3\Crypt\RSA\PublicKey $rsa */
|
||||||
|
$rsa = \phpseclib3\Crypt\PublicKeyLoader::load($key);
|
||||||
|
|
||||||
|
return $rsa->withPadding(\phpseclib3\Crypt\RSA::SIGNATURE_PSS)
|
||||||
|
->withHash('sha256')
|
||||||
|
->verify($message, $signature);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
interface JWTExceptionWithPayloadInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the payload that caused this exception.
|
||||||
|
*
|
||||||
|
* @return object
|
||||||
|
*/
|
||||||
|
public function getPayload(): object;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the payload that caused this exception.
|
||||||
|
*
|
||||||
|
* @param object $payload
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setPayload(object $payload): void;
|
||||||
|
}
|
||||||
Vendored
+53
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use OpenSSLAsymmetricKey;
|
||||||
|
use OpenSSLCertificate;
|
||||||
|
use TypeError;
|
||||||
|
|
||||||
|
class Key
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial
|
||||||
|
* @param string $algorithm
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
#[\SensitiveParameter] private $keyMaterial,
|
||||||
|
private string $algorithm
|
||||||
|
) {
|
||||||
|
if (!\is_string($keyMaterial)
|
||||||
|
&& !$keyMaterial instanceof OpenSSLAsymmetricKey
|
||||||
|
&& !$keyMaterial instanceof OpenSSLCertificate
|
||||||
|
) {
|
||||||
|
throw new TypeError('Key material must be a string, OpenSSLCertificate, or OpenSSLAsymmetricKey');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($keyMaterial)) {
|
||||||
|
throw new InvalidArgumentException('Key material must not be empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($algorithm)) {
|
||||||
|
throw new InvalidArgumentException('Algorithm must not be empty');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the algorithm valid for this key
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getAlgorithm(): string
|
||||||
|
{
|
||||||
|
return $this->algorithm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string|OpenSSLAsymmetricKey|OpenSSLCertificate
|
||||||
|
*/
|
||||||
|
public function getKeyMaterial()
|
||||||
|
{
|
||||||
|
return $this->keyMaterial;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Firebase\JWT;
|
||||||
|
|
||||||
|
class SignatureInvalidException extends \UnexpectedValueException
|
||||||
|
{
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2020-2026 Graham Campbell <hello@gjcampbell.co.uk>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"name": "graham-campbell/result-type",
|
||||||
|
"description": "An Implementation Of The Result Type",
|
||||||
|
"keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"],
|
||||||
|
"license": "MIT",
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Graham Campbell",
|
||||||
|
"email": "hello@gjcampbell.co.uk",
|
||||||
|
"homepage": "https://github.com/GrahamCampbell"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"require": {
|
||||||
|
"php": "^7.2.5 || ^8.0",
|
||||||
|
"phpoption/phpoption": "^1.10"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"phpunit/phpunit": "^8.5.52 || ^9.6.34 || ^10.5.63 || ^11.5.55 || ^12.5.14"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"GrahamCampbell\\ResultType\\": "src/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload-dev": {
|
||||||
|
"psr-4": {
|
||||||
|
"GrahamCampbell\\Tests\\ResultType\\": "tests/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"preferred-install": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is part of Result Type.
|
||||||
|
*
|
||||||
|
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace GrahamCampbell\ResultType;
|
||||||
|
|
||||||
|
use PhpOption\None;
|
||||||
|
use PhpOption\Some;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template-covariant E
|
||||||
|
*
|
||||||
|
* @extends \GrahamCampbell\ResultType\Result<never,E>
|
||||||
|
*/
|
||||||
|
final class Error extends Result
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var E
|
||||||
|
*/
|
||||||
|
private $value;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal constructor for an error value.
|
||||||
|
*
|
||||||
|
* @param E $value
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private function __construct($value)
|
||||||
|
{
|
||||||
|
$this->value = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new error value.
|
||||||
|
*
|
||||||
|
* @template F
|
||||||
|
*
|
||||||
|
* @param F $value
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Error<F>
|
||||||
|
*/
|
||||||
|
public static function create($value)
|
||||||
|
{
|
||||||
|
return new self($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the success option value.
|
||||||
|
*
|
||||||
|
* @return \PhpOption\Option<never>
|
||||||
|
*/
|
||||||
|
public function success()
|
||||||
|
{
|
||||||
|
return None::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map over the success value.
|
||||||
|
*
|
||||||
|
* @template S
|
||||||
|
*
|
||||||
|
* @param callable(never):S $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Error<E>
|
||||||
|
*/
|
||||||
|
public function map(callable $f)
|
||||||
|
{
|
||||||
|
return self::create($this->value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flat map over the success value.
|
||||||
|
*
|
||||||
|
* @template S
|
||||||
|
* @template F
|
||||||
|
*
|
||||||
|
* @param callable(never):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Error<E>
|
||||||
|
*/
|
||||||
|
public function flatMap(callable $f)
|
||||||
|
{
|
||||||
|
return self::create($this->value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the error option value.
|
||||||
|
*
|
||||||
|
* @return \PhpOption\Option<E>
|
||||||
|
*/
|
||||||
|
public function error()
|
||||||
|
{
|
||||||
|
return Some::create($this->value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map over the error value.
|
||||||
|
*
|
||||||
|
* @template F
|
||||||
|
*
|
||||||
|
* @param callable(E):F $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Error<F>
|
||||||
|
*/
|
||||||
|
public function mapError(callable $f)
|
||||||
|
{
|
||||||
|
return self::create($f($this->value));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is part of Result Type.
|
||||||
|
*
|
||||||
|
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace GrahamCampbell\ResultType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template-covariant T
|
||||||
|
* @template-covariant E
|
||||||
|
*/
|
||||||
|
abstract class Result
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the success option value.
|
||||||
|
*
|
||||||
|
* @return \PhpOption\Option<T>
|
||||||
|
*/
|
||||||
|
abstract public function success();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map over the success value.
|
||||||
|
*
|
||||||
|
* @template S
|
||||||
|
*
|
||||||
|
* @param callable(T):S $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Result<S,E>
|
||||||
|
*/
|
||||||
|
abstract public function map(callable $f);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flat map over the success value.
|
||||||
|
*
|
||||||
|
* @template S
|
||||||
|
* @template F
|
||||||
|
*
|
||||||
|
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Result<S,E|F>
|
||||||
|
*/
|
||||||
|
abstract public function flatMap(callable $f);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the error option value.
|
||||||
|
*
|
||||||
|
* @return \PhpOption\Option<E>
|
||||||
|
*/
|
||||||
|
abstract public function error();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map over the error value.
|
||||||
|
*
|
||||||
|
* @template F
|
||||||
|
*
|
||||||
|
* @param callable(E):F $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Result<T,F>
|
||||||
|
*/
|
||||||
|
abstract public function mapError(callable $f);
|
||||||
|
}
|
||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is part of Result Type.
|
||||||
|
*
|
||||||
|
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||||
|
*
|
||||||
|
* For the full copyright and license information, please view the LICENSE
|
||||||
|
* file that was distributed with this source code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace GrahamCampbell\ResultType;
|
||||||
|
|
||||||
|
use PhpOption\None;
|
||||||
|
use PhpOption\Some;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template-covariant T
|
||||||
|
*
|
||||||
|
* @extends \GrahamCampbell\ResultType\Result<T,never>
|
||||||
|
*/
|
||||||
|
final class Success extends Result
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var T
|
||||||
|
*/
|
||||||
|
private $value;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal constructor for a success value.
|
||||||
|
*
|
||||||
|
* @param T $value
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private function __construct($value)
|
||||||
|
{
|
||||||
|
$this->value = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new success value.
|
||||||
|
*
|
||||||
|
* @template S
|
||||||
|
*
|
||||||
|
* @param S $value
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Success<S>
|
||||||
|
*/
|
||||||
|
public static function create($value)
|
||||||
|
{
|
||||||
|
return new self($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the success option value.
|
||||||
|
*
|
||||||
|
* @return \PhpOption\Option<T>
|
||||||
|
*/
|
||||||
|
public function success()
|
||||||
|
{
|
||||||
|
return Some::create($this->value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map over the success value.
|
||||||
|
*
|
||||||
|
* @template S
|
||||||
|
*
|
||||||
|
* @param callable(T):S $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Success<S>
|
||||||
|
*/
|
||||||
|
public function map(callable $f)
|
||||||
|
{
|
||||||
|
return self::create($f($this->value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flat map over the success value.
|
||||||
|
*
|
||||||
|
* @template S
|
||||||
|
* @template F
|
||||||
|
*
|
||||||
|
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Result<S,F>
|
||||||
|
*/
|
||||||
|
public function flatMap(callable $f)
|
||||||
|
{
|
||||||
|
return $f($this->value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the error option value.
|
||||||
|
*
|
||||||
|
* @return \PhpOption\Option<never>
|
||||||
|
*/
|
||||||
|
public function error()
|
||||||
|
{
|
||||||
|
return None::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map over the error value.
|
||||||
|
*
|
||||||
|
* @template F
|
||||||
|
*
|
||||||
|
* @param callable(never):F $f
|
||||||
|
*
|
||||||
|
* @return \GrahamCampbell\ResultType\Success<T>
|
||||||
|
*/
|
||||||
|
public function mapError(callable $f)
|
||||||
|
{
|
||||||
|
return self::create($this->value);
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+76
@@ -0,0 +1,76 @@
|
|||||||
|
# Agent Guidelines
|
||||||
|
|
||||||
|
## Code and tooling
|
||||||
|
|
||||||
|
- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer
|
||||||
|
only under a PHP 7.4.x runtime; never run either tool under any other PHP
|
||||||
|
major.minor version.
|
||||||
|
- Use fully qualified `#[\SensitiveParameter]` on concrete executable
|
||||||
|
parameters when their established role normally carries a secret,
|
||||||
|
credential-bearing aggregate, or confidential Guzzle-owned container, and
|
||||||
|
the active frame can throw or invoke throwing code.
|
||||||
|
- Repeat the attribute on every qualifying owned caller, callee, concrete trait
|
||||||
|
method, and closure parameter. Do not add it to interfaces, abstract-only
|
||||||
|
declarations, pure/no-realistic-throw helpers, assignment-only sites,
|
||||||
|
arbitrary generic payloads, or completed non-recoverable derivatives.
|
||||||
|
- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and
|
||||||
|
the parameter on the following line, expand the complete parameter list, and
|
||||||
|
never add a comma after the final parameter. Native trace redaction starts on
|
||||||
|
PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured
|
||||||
|
variables, return values, or the separate backtrace `$this`/`object`.
|
||||||
|
- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`;
|
||||||
|
never rely on the default characters.
|
||||||
|
- Handle `preg_*` engine failures: when the result is used as data, test for
|
||||||
|
`false` or `null` and throw a `\RuntimeException` including
|
||||||
|
`preg_last_error_msg()`; boolean validation guards must compare strictly, such
|
||||||
|
as `=== 1`, so an engine failure can only ever fail closed. Diagnostic
|
||||||
|
escaping is the narrow exception: use a deterministic bytewise fallback rather
|
||||||
|
than throwing, so it cannot obscure the original exception.
|
||||||
|
- Anchor validation patterns to the true end of input with the `D` modifier or
|
||||||
|
`\z`; a bare `$` accepts a trailing newline.
|
||||||
|
- Never embed raw control bytes in exception messages and other diagnostics;
|
||||||
|
escape or redact the offending value first.
|
||||||
|
- Helper classes that expose only public static methods are `final` and have a
|
||||||
|
private constructor.
|
||||||
|
- Resist native PHP serialization when a class holds live state (streams,
|
||||||
|
resources, handles, callbacks, credentials) or when magic methods such as
|
||||||
|
`__destruct()` have side effects that untrusted unserialized data could
|
||||||
|
redirect, as with the file and session write fixes in Guzzle's persisting
|
||||||
|
cookie jars. Plain data holders, such as Guzzle's in-memory cookie jar, remain
|
||||||
|
serializable.
|
||||||
|
- To resist, `__serialize()` and `__unserialize()` both throw
|
||||||
|
`\LogicException(static::class.' should never be serialized')` and its
|
||||||
|
unserialized counterpart, usually via the `@internal` `NonSerializableTrait`.
|
||||||
|
Where a `__destruct()` has such a side effect, it is enabled only by the
|
||||||
|
constructor and disabled in `__wakeup()` and `__unserialize()` before
|
||||||
|
throwing, so the protection holds even if the exception is swallowed.
|
||||||
|
- In general, numeric inputs should not accept non-finite floats. In situations
|
||||||
|
where they are accepted and we need to cast to a string, we should branch on
|
||||||
|
`\is_finite($value)`, using `(string) $value` for the finite case and
|
||||||
|
`\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise.
|
||||||
|
- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or
|
||||||
|
other locale-sensitive case functions; use the locale-independent
|
||||||
|
`GuzzleHttp\Psr7\Utils::asciiToLower()`, `asciiToUpper()`,
|
||||||
|
`caselessEquals()`, and `caselessContains()` helpers instead.
|
||||||
|
- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of
|
||||||
|
the target branch and an `UPGRADING.md` note when the behavior differs between
|
||||||
|
major versions.
|
||||||
|
|
||||||
|
## Contributor references
|
||||||
|
|
||||||
|
- Read the [exception guidelines](docs/contributing/exception-guidelines.md)
|
||||||
|
before deciding which exception a change should throw.
|
||||||
|
- Read the
|
||||||
|
[cURL connection reuse reference](docs/contributing/curl-connection-reuse.md)
|
||||||
|
before working on the cURL handlers or connection reuse and sharing behavior.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never
|
||||||
|
split a markdown link or an inline code span across a line break; a line that
|
||||||
|
cannot be broken may exceed the limit. Avoid em dashes.
|
||||||
|
- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is
|
||||||
|
deliberately word-for-word identical, including boilerplate copied verbatim
|
||||||
|
between related functions, so apply the same edit to every copy. Only
|
||||||
|
formatting and linking may differ, such as a docs link becoming a PHPDoc
|
||||||
|
`@see` tag; the wording must never drift.
|
||||||
+2403
File diff suppressed because it is too large
Load Diff
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
Vendored
+27
@@ -0,0 +1,27 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2011 Michael Dowling <mtdowling@gmail.com>
|
||||||
|
Copyright (c) 2012 Jeremy Lindblom <jeremeamia@gmail.com>
|
||||||
|
Copyright (c) 2014 Graham Campbell <hello@gjcampbell.co.uk>
|
||||||
|
Copyright (c) 2015 Márk Sági-Kazár <mark.sagikazar@gmail.com>
|
||||||
|
Copyright (c) 2015 Tobias Schultze <webmaster@tubo-world.de>
|
||||||
|
Copyright (c) 2016 Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||||
|
Copyright (c) 2016 George Mponos <gmponos@gmail.com>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
Vendored
+95
@@ -0,0 +1,95 @@
|
|||||||
|

|
||||||
|
|
||||||
|
# Guzzle, PHP HTTP Client
|
||||||
|
|
||||||
|
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
|
||||||
|
trivial to integrate with web services.
|
||||||
|
|
||||||
|
- Simple interface for building query strings, POST requests, streaming large
|
||||||
|
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
|
||||||
|
etc...
|
||||||
|
- Can send both synchronous and asynchronous requests using the same interface.
|
||||||
|
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
|
||||||
|
to utilize other PSR-7 compatible libraries with Guzzle.
|
||||||
|
- Supports PSR-18, allowing interoperability with other PSR-18 HTTP clients.
|
||||||
|
- Abstracts away the underlying HTTP transport, allowing you to write
|
||||||
|
environment and transport agnostic code; i.e., no hard dependency on cURL,
|
||||||
|
PHP streams, sockets, or non-blocking event loops.
|
||||||
|
- Middleware system allows you to augment and compose client behavior.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
The recommended way to install Guzzle is through
|
||||||
|
[Composer](https://getcomposer.org/).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require guzzlehttp/guzzle
|
||||||
|
```
|
||||||
|
|
||||||
|
## Version Guidance
|
||||||
|
|
||||||
|
| Version | Status | PHP Version |
|
||||||
|
|---------|--------------|--------------|
|
||||||
|
| 8.5 | Latest | >=7.4,<8.7 |
|
||||||
|
| 7.16 | Maintenance | >=7.2.5,<8.7 |
|
||||||
|
| 6.5 | End of Life | >=5.5,<8.0 |
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
```php
|
||||||
|
$client = new \GuzzleHttp\Client();
|
||||||
|
$response = $client->request('GET', 'https://api.example.com/users/123');
|
||||||
|
|
||||||
|
echo $response->getStatusCode(); // 200
|
||||||
|
echo $response->getHeaderLine('content-type'); // 'application/json'
|
||||||
|
echo $response->getBody(); // '{"id": 123, "name": "Ada"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
For more examples, see the [Quick Start](docs/quick-start.md).
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- [Quick Start](docs/quick-start.md)
|
||||||
|
- [Overview](docs/overview.md)
|
||||||
|
- [Request Options](docs/request-options.md)
|
||||||
|
- [Uploading Data](docs/uploading-data.md)
|
||||||
|
- [Cookies](docs/cookies.md)
|
||||||
|
- [Exceptions](docs/exceptions.md)
|
||||||
|
- [Guzzle and PSR-7](docs/guzzle-and-psr-7.md)
|
||||||
|
- [Handlers](docs/handlers.md)
|
||||||
|
- [Middleware](docs/middleware.md)
|
||||||
|
- [Testing Guzzle Clients](docs/testing-guzzle-clients.md)
|
||||||
|
- [FAQ](docs/faq.md)
|
||||||
|
- [Package Ecosystem](docs/package-ecosystem.md)
|
||||||
|
- [Upgrade Guide](UPGRADING.md)
|
||||||
|
- [Changelog](CHANGELOG.md)
|
||||||
|
|
||||||
|
We use GitHub issues only to discuss bugs and new features. For support, use
|
||||||
|
[Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle), the
|
||||||
|
[#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on
|
||||||
|
[PHP-HTTP Slack](https://slack.httplug.io/), or
|
||||||
|
[Gitter](https://gitter.im/guzzle/guzzle).
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
If you discover a security vulnerability within this package, please send an
|
||||||
|
email to security@tidelift.com. All security vulnerabilities will be promptly
|
||||||
|
addressed by the security maintainers listed in the
|
||||||
|
[Security Policy](https://github.com/guzzle/guzzle/security/policy). Please do
|
||||||
|
not disclose security-related issues publicly until a fix has been announced.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Guzzle is made available under the MIT License (MIT). Please see
|
||||||
|
[License File](LICENSE) for more information.
|
||||||
|
|
||||||
|
## For Enterprise
|
||||||
|
|
||||||
|
Available as part of the Tidelift Subscription
|
||||||
|
|
||||||
|
The maintainers of Guzzle and thousands of other packages are working with
|
||||||
|
Tidelift to deliver commercial support and maintenance for the open source
|
||||||
|
dependencies you use to build your applications. Save time, reduce risk, and
|
||||||
|
improve code health, while paying the maintainers of the exact dependencies you
|
||||||
|
use.
|
||||||
|
[Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||||
+2785
File diff suppressed because it is too large
Load Diff
+132
@@ -0,0 +1,132 @@
|
|||||||
|
{
|
||||||
|
"name": "guzzlehttp/guzzle",
|
||||||
|
"description": "Guzzle is a PHP HTTP client library",
|
||||||
|
"license": "MIT",
|
||||||
|
"keywords": [
|
||||||
|
"framework",
|
||||||
|
"http",
|
||||||
|
"rest",
|
||||||
|
"web service",
|
||||||
|
"curl",
|
||||||
|
"client",
|
||||||
|
"HTTP client",
|
||||||
|
"PSR-7",
|
||||||
|
"PSR-18"
|
||||||
|
],
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Graham Campbell",
|
||||||
|
"email": "hello@gjcampbell.co.uk",
|
||||||
|
"homepage": "https://github.com/GrahamCampbell"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Michael Dowling",
|
||||||
|
"email": "mtdowling@gmail.com",
|
||||||
|
"homepage": "https://github.com/mtdowling"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Jeremy Lindblom",
|
||||||
|
"email": "jeremeamia@gmail.com",
|
||||||
|
"homepage": "https://github.com/jeremeamia"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "George Mponos",
|
||||||
|
"email": "gmponos@gmail.com",
|
||||||
|
"homepage": "https://github.com/gmponos"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tobias Nyholm",
|
||||||
|
"email": "tobias.nyholm@gmail.com",
|
||||||
|
"homepage": "https://github.com/Nyholm"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Márk Sági-Kazár",
|
||||||
|
"email": "mark.sagikazar@gmail.com",
|
||||||
|
"homepage": "https://github.com/sagikazarmark"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tobias Schultze",
|
||||||
|
"email": "webmaster@tubo-world.de",
|
||||||
|
"homepage": "https://github.com/Tobion"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"require": {
|
||||||
|
"php": "^7.4 || ^8.0",
|
||||||
|
"ext-json": "*",
|
||||||
|
"guzzlehttp/promises": "^3.1.1",
|
||||||
|
"guzzlehttp/psr7": "^3.5.1",
|
||||||
|
"psr/http-client": "^1.0",
|
||||||
|
"psr/http-factory": "^1.0",
|
||||||
|
"symfony/deprecation-contracts": "^2.5 || ^3.0",
|
||||||
|
"symfony/polyfill-php80": "^1.25",
|
||||||
|
"symfony/polyfill-php82": "^1.27"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"ext-curl": "*",
|
||||||
|
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||||
|
"guzzle/client-integration-tests": "4.0.1",
|
||||||
|
"guzzlehttp/test-server": "^1.1",
|
||||||
|
"php-http/message-factory": "^1.1",
|
||||||
|
"phpunit/phpunit": "^9.6.34",
|
||||||
|
"psr/log": "^1.1 || ^2.0 || ^3.0"
|
||||||
|
},
|
||||||
|
"provide": {
|
||||||
|
"psr/http-client-implementation": "1.0"
|
||||||
|
},
|
||||||
|
"suggest": {
|
||||||
|
"ext-curl": "Required for CURL handler support",
|
||||||
|
"ext-intl": "Required for Internationalized Domain Name (IDN) support",
|
||||||
|
"psr/log": "Required for using the Log middleware"
|
||||||
|
},
|
||||||
|
"repositories": [
|
||||||
|
{
|
||||||
|
"type": "package",
|
||||||
|
"package": {
|
||||||
|
"name": "guzzle/client-integration-tests",
|
||||||
|
"version": "v4.0.1",
|
||||||
|
"require": {
|
||||||
|
"guzzlehttp/psr7": "^3.5.1",
|
||||||
|
"php": "^7.4 || ^8.0",
|
||||||
|
"php-http/message": "^1.0 || ^2.0",
|
||||||
|
"phpunit/phpunit": "^9.6.34",
|
||||||
|
"th3n3rd/cartesian-product": "^0.3"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"Http\\Client\\Tests\\": "src/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"bin": [
|
||||||
|
"bin/http_test_server"
|
||||||
|
],
|
||||||
|
"dist": {
|
||||||
|
"type": "zip",
|
||||||
|
"url": "https://codeload.github.com/guzzle/client-integration-tests/zip/e54cb9d94e3aa5e125dcd7d01bec22db202444ac"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"GuzzleHttp\\": "src/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload-dev": {
|
||||||
|
"psr-4": {
|
||||||
|
"GuzzleHttp\\Tests\\": "tests/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"allow-plugins": {
|
||||||
|
"bamarni/composer-bin-plugin": true
|
||||||
|
},
|
||||||
|
"preferred-install": "dist",
|
||||||
|
"sort-packages": true
|
||||||
|
},
|
||||||
|
"extra": {
|
||||||
|
"bamarni-bin": {
|
||||||
|
"bin-links": true,
|
||||||
|
"forward-command": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+515
@@ -0,0 +1,515 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Auth;
|
||||||
|
|
||||||
|
use GuzzleHttp\Psr7;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
final class DigestAuth
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array<string, array{hash: string, sess: bool, rank: int, header: string}>
|
||||||
|
*/
|
||||||
|
private const ALGORITHMS = [
|
||||||
|
'MD5' => ['hash' => 'md5', 'sess' => false, 'rank' => 10, 'header' => 'MD5'],
|
||||||
|
'MD5-SESS' => ['hash' => 'md5', 'sess' => true, 'rank' => 11, 'header' => 'MD5-sess'],
|
||||||
|
'SHA-256' => ['hash' => 'sha256', 'sess' => false, 'rank' => 20, 'header' => 'SHA-256'],
|
||||||
|
'SHA-256-SESS' => ['hash' => 'sha256', 'sess' => true, 'rank' => 21, 'header' => 'SHA-256-sess'],
|
||||||
|
'SHA-512-256' => ['hash' => 'sha512/256', 'sess' => false, 'rank' => 30, 'header' => 'SHA-512-256'],
|
||||||
|
'SHA-512-256-SESS' => ['hash' => 'sha512/256', 'sess' => true, 'rank' => 31, 'header' => 'SHA-512-256-sess'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, true>
|
||||||
|
*/
|
||||||
|
private const DIGEST_CHALLENGE_PARAMETER_NAMES = [
|
||||||
|
'realm' => true,
|
||||||
|
'domain' => true,
|
||||||
|
'nonce' => true,
|
||||||
|
'opaque' => true,
|
||||||
|
'stale' => true,
|
||||||
|
'algorithm' => true,
|
||||||
|
'qop' => true,
|
||||||
|
'charset' => true,
|
||||||
|
'userhash' => true,
|
||||||
|
];
|
||||||
|
|
||||||
|
private function __construct()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function selectChallenge(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response
|
||||||
|
): ?DigestChallenge {
|
||||||
|
$selected = null;
|
||||||
|
|
||||||
|
foreach ($response->getHeader('WWW-Authenticate') as $header) {
|
||||||
|
foreach (self::parseAuthenticateHeader($header) as $challenge) {
|
||||||
|
if ($challenge['scheme'] !== 'digest' || $challenge['invalid']) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$digest = self::createChallenge($challenge['params']);
|
||||||
|
if ($digest === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($selected === null || $digest->algorithm['rank'] > $selected->algorithm['rank']) {
|
||||||
|
$selected = $digest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function authorizationHeader(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
DigestChallenge $challenge,
|
||||||
|
string $username,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $password,
|
||||||
|
string $cnonce,
|
||||||
|
string $nc = '00000001'
|
||||||
|
): ?string {
|
||||||
|
if ($challenge->algorithm['sess'] && $challenge->qop === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$uri = $request->getRequestTarget();
|
||||||
|
if ($uri === '') {
|
||||||
|
$uri = '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ([$username, $challenge->realm, $challenge->nonce, $uri, $cnonce] as $value) {
|
||||||
|
if (!self::isHeaderSafe($value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($challenge->opaque !== null && !self::isHeaderSafe($challenge->opaque)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($challenge->qop !== null && !self::isNonceCount($nc)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$hash = $challenge->algorithm['hash'];
|
||||||
|
$ha1 = \hash($hash, $username.':'.$challenge->realm.':'.$password);
|
||||||
|
|
||||||
|
if ($challenge->algorithm['sess']) {
|
||||||
|
$ha1 = \hash($hash, $ha1.':'.$challenge->nonce.':'.$cnonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
$ha2 = \hash($hash, $request->getMethod().':'.$uri);
|
||||||
|
$response = $challenge->qop === null
|
||||||
|
? \hash($hash, $ha1.':'.$challenge->nonce.':'.$ha2)
|
||||||
|
: \hash($hash, $ha1.':'.$challenge->nonce.':'.$nc.':'.$cnonce.':'.$challenge->qop.':'.$ha2);
|
||||||
|
|
||||||
|
if ($challenge->userhash) {
|
||||||
|
$headerUsername = \hash($hash, $username.':'.$challenge->realm);
|
||||||
|
if ($headerUsername === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$headerUsername = $username;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts = [
|
||||||
|
'username='.self::quote($headerUsername),
|
||||||
|
'realm='.self::quote($challenge->realm),
|
||||||
|
'nonce='.self::quote($challenge->nonce),
|
||||||
|
'uri='.self::quote($uri),
|
||||||
|
'response='.self::quote($response),
|
||||||
|
'algorithm='.$challenge->algorithm['header'],
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($challenge->opaque !== null) {
|
||||||
|
$parts[] = 'opaque='.self::quote($challenge->opaque);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($challenge->qop !== null) {
|
||||||
|
$parts[] = 'qop='.$challenge->qop;
|
||||||
|
$parts[] = 'nc='.$nc;
|
||||||
|
$parts[] = 'cnonce='.self::quote($cnonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($challenge->userhash) {
|
||||||
|
$parts[] = 'userhash=true';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Digest '.\implode(', ', $parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<array{scheme: string, params: array<string, string>, invalid: bool}>
|
||||||
|
*/
|
||||||
|
public static function parseAuthenticateHeader(string $header): array
|
||||||
|
{
|
||||||
|
$length = \strlen($header);
|
||||||
|
$offset = 0;
|
||||||
|
$challenges = [];
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
self::skipSeparators($header, $offset, $length);
|
||||||
|
if ($offset >= $length) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$scheme = self::readToken($header, $offset, $length);
|
||||||
|
if ($scheme === null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
|
||||||
|
if (self::skipToken68Challenge($header, $offset, $length)) {
|
||||||
|
$challenges[] = [
|
||||||
|
'scheme' => Psr7\Utils::asciiToLower($scheme),
|
||||||
|
'params' => [],
|
||||||
|
'invalid' => false,
|
||||||
|
];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$params = [];
|
||||||
|
$invalid = false;
|
||||||
|
|
||||||
|
while ($offset < $length) {
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
|
||||||
|
if ($offset < $length && $header[$offset] === ',') {
|
||||||
|
if (self::commaStartsNextChallenge($header, $offset + 1, $length)) {
|
||||||
|
if (Psr7\Utils::caselessEquals($scheme, 'Digest')
|
||||||
|
&& self::commaStartsKnownDigestParameterWithoutValue($header, $offset + 1, $length)
|
||||||
|
) {
|
||||||
|
$invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
++$offset;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
++$offset;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$name = self::readToken($header, $offset, $length);
|
||||||
|
if ($name === null) {
|
||||||
|
if ($offset < $length) {
|
||||||
|
$invalid = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
if ($offset >= $length || $header[$offset] !== '=') {
|
||||||
|
$invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
++$offset;
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
|
||||||
|
$value = self::readValue($header, $offset, $length);
|
||||||
|
if ($value === null) {
|
||||||
|
$invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lowerName = Psr7\Utils::asciiToLower($name);
|
||||||
|
if (\array_key_exists($lowerName, $params)) {
|
||||||
|
$invalid = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$params[$lowerName] = $value;
|
||||||
|
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
if ($offset >= $length) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($header[$offset] !== ',') {
|
||||||
|
$invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$challenges[] = [
|
||||||
|
'scheme' => Psr7\Utils::asciiToLower($scheme),
|
||||||
|
'params' => $params,
|
||||||
|
'invalid' => $invalid,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $challenges;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, string> $params
|
||||||
|
*/
|
||||||
|
private static function createChallenge(array $params): ?DigestChallenge
|
||||||
|
{
|
||||||
|
if (!isset($params['nonce']) || $params['nonce'] === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($params['charset']) && !Psr7\Utils::caselessEquals($params['charset'], 'UTF-8')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$algorithm = self::algorithm($params['algorithm'] ?? null);
|
||||||
|
if ($algorithm === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$qop = self::selectQop($params['qop'] ?? null);
|
||||||
|
if ($qop === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($algorithm['sess'] && $qop === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$challenge = new DigestChallenge();
|
||||||
|
$challenge->algorithm = $algorithm;
|
||||||
|
$challenge->realm = $params['realm'] ?? '';
|
||||||
|
$challenge->nonce = $params['nonce'];
|
||||||
|
$challenge->opaque = $params['opaque'] ?? null;
|
||||||
|
if (isset($params['domain'])) {
|
||||||
|
$domainAreas = \preg_split('/[ \t]+/', $params['domain']);
|
||||||
|
|
||||||
|
if ($domainAreas === false) {
|
||||||
|
throw new \RuntimeException('Unable to split the Digest domain list: '.\preg_last_error_msg());
|
||||||
|
}
|
||||||
|
|
||||||
|
$challenge->domain = \array_values(\array_filter($domainAreas));
|
||||||
|
} else {
|
||||||
|
$challenge->domain = [];
|
||||||
|
}
|
||||||
|
$challenge->qop = $qop;
|
||||||
|
$challenge->stale = isset($params['stale']) && Psr7\Utils::caselessEquals($params['stale'], 'true');
|
||||||
|
$challenge->userhash = isset($params['userhash']) && Psr7\Utils::caselessEquals($params['userhash'], 'true');
|
||||||
|
|
||||||
|
return $challenge;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{name: string, hash: string, sess: bool, rank: int, header: string}|null
|
||||||
|
*/
|
||||||
|
private static function algorithm(?string $algorithm): ?array
|
||||||
|
{
|
||||||
|
$name = Psr7\Utils::asciiToUpper($algorithm ?? 'MD5');
|
||||||
|
|
||||||
|
if (!isset(self::ALGORITHMS[$name])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$mapped = self::ALGORITHMS[$name];
|
||||||
|
if (!\in_array($mapped['hash'], \hash_algos(), true)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['name' => $name] + $mapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string|false|null
|
||||||
|
*/
|
||||||
|
private static function selectQop(?string $qop)
|
||||||
|
{
|
||||||
|
if ($qop === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$tokens = \array_map(
|
||||||
|
static function (string $token): string {
|
||||||
|
return Psr7\Utils::asciiToLower(\trim($token, " \t"));
|
||||||
|
},
|
||||||
|
\explode(',', $qop)
|
||||||
|
);
|
||||||
|
|
||||||
|
return \in_array('auth', $tokens, true) ? 'auth' : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function quote(string $value): string
|
||||||
|
{
|
||||||
|
return '"'.\strtr($value, [
|
||||||
|
'\\' => '\\\\',
|
||||||
|
'"' => '\\"',
|
||||||
|
]).'"';
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isHeaderSafe(string $value): bool
|
||||||
|
{
|
||||||
|
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value) === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isNonceCount(string $nc): bool
|
||||||
|
{
|
||||||
|
// Nonce counts start at one.
|
||||||
|
return $nc !== '00000000' && \preg_match('/^[0-9a-f]{8}$/D', $nc) === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function commaStartsNextChallenge(string $header, int $offset, int $length): bool
|
||||||
|
{
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
$nextOffset = $offset;
|
||||||
|
$token = self::readToken($header, $nextOffset, $length);
|
||||||
|
if ($token === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
self::skipWhitespace($header, $nextOffset, $length);
|
||||||
|
|
||||||
|
return $nextOffset >= $length || $header[$nextOffset] !== '=';
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function commaStartsKnownDigestParameterWithoutValue(string $header, int $offset, int $length): bool
|
||||||
|
{
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
$name = self::readToken($header, $offset, $length);
|
||||||
|
if ($name === null || !isset(self::DIGEST_CHALLENGE_PARAMETER_NAMES[Psr7\Utils::asciiToLower($name)])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
self::skipWhitespace($header, $offset, $length);
|
||||||
|
|
||||||
|
return $offset >= $length || $header[$offset] !== '=';
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function skipToken68Challenge(string $header, int &$offset, int $length): bool
|
||||||
|
{
|
||||||
|
$cursor = $offset;
|
||||||
|
$hasValue = false;
|
||||||
|
while ($cursor < $length && self::isToken68Char($header[$cursor])) {
|
||||||
|
$hasValue = true;
|
||||||
|
++$cursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
while ($cursor < $length && $header[$cursor] === '=') {
|
||||||
|
++$cursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$hasValue) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$after = $cursor;
|
||||||
|
self::skipWhitespace($header, $after, $length);
|
||||||
|
|
||||||
|
if ($after < $length && $header[$after] !== ',') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$offset = $after;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function skipSeparators(string $header, int &$offset, int $length): void
|
||||||
|
{
|
||||||
|
while ($offset < $length) {
|
||||||
|
$char = $header[$offset];
|
||||||
|
if ($char !== ',' && !self::isWhitespace($char)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
++$offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function skipWhitespace(string $header, int &$offset, int $length): void
|
||||||
|
{
|
||||||
|
while ($offset < $length && self::isWhitespace($header[$offset])) {
|
||||||
|
++$offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isWhitespace(string $char): bool
|
||||||
|
{
|
||||||
|
return $char === ' ' || $char === "\t";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function readToken(string $header, int &$offset, int $length): ?string
|
||||||
|
{
|
||||||
|
$start = $offset;
|
||||||
|
while ($offset < $length && self::isTokenChar($header[$offset])) {
|
||||||
|
++$offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($offset === $start) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$token = \substr($header, $start, $offset - $start);
|
||||||
|
|
||||||
|
return $token === false ? null : $token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isTokenChar(string $char): bool
|
||||||
|
{
|
||||||
|
return \strspn($char, "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isToken68Char(string $char): bool
|
||||||
|
{
|
||||||
|
return \strspn($char, '-._~+/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function readValue(string $header, int &$offset, int $length): ?string
|
||||||
|
{
|
||||||
|
if ($offset >= $length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($header[$offset] === '"') {
|
||||||
|
return self::readQuotedString($header, $offset, $length);
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::readToken($header, $offset, $length);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function readQuotedString(string $header, int &$offset, int $length): ?string
|
||||||
|
{
|
||||||
|
++$offset;
|
||||||
|
$value = '';
|
||||||
|
$escaped = false;
|
||||||
|
|
||||||
|
while ($offset < $length) {
|
||||||
|
$char = $header[$offset++];
|
||||||
|
|
||||||
|
if ($escaped) {
|
||||||
|
$value .= $char;
|
||||||
|
$escaped = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($char === '\\') {
|
||||||
|
$escaped = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($char === '"') {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value .= $char;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Auth;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
final class DigestChallenge
|
||||||
|
{
|
||||||
|
/** @var array{name: string, hash: string, sess: bool, rank: int, header: string} */
|
||||||
|
public array $algorithm;
|
||||||
|
|
||||||
|
public string $realm = '';
|
||||||
|
|
||||||
|
public string $nonce;
|
||||||
|
|
||||||
|
public ?string $opaque = null;
|
||||||
|
|
||||||
|
/** @var list<string> */
|
||||||
|
public array $domain = [];
|
||||||
|
|
||||||
|
public ?string $qop = null;
|
||||||
|
|
||||||
|
public bool $stale = false;
|
||||||
|
|
||||||
|
public bool $userhash = false;
|
||||||
|
}
|
||||||
+846
@@ -0,0 +1,846 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp;
|
||||||
|
|
||||||
|
use GuzzleHttp\Auth\DigestAuth;
|
||||||
|
use GuzzleHttp\Auth\DigestChallenge;
|
||||||
|
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||||
|
use GuzzleHttp\Exception\ResponseException;
|
||||||
|
use GuzzleHttp\Promise as P;
|
||||||
|
use GuzzleHttp\Promise\PromiseInterface;
|
||||||
|
use GuzzleHttp\Psr7\HttpFactory;
|
||||||
|
use GuzzleHttp\Psr7\LazyOpenStream;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\StreamFactoryInterface;
|
||||||
|
use Psr\Http\Message\StreamInterface;
|
||||||
|
use Psr\Http\Message\UriInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies built-in Basic authentication and handles Digest authentication
|
||||||
|
* challenges.
|
||||||
|
*/
|
||||||
|
final class AuthMiddleware
|
||||||
|
{
|
||||||
|
use NonSerializableTrait;
|
||||||
|
|
||||||
|
private const DIGEST_MAX_RETRIES = 2;
|
||||||
|
|
||||||
|
private const CHALLENGE_CACHE_LIMIT = 32;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request option carrying nonce counts already spent during a Digest
|
||||||
|
* handshake, so stale retries advance instead of repeating a count.
|
||||||
|
*/
|
||||||
|
private const DIGEST_NONCE_COUNTS_OPTION = '__guzzle_digest_nonce_counts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Headers that describe the request payload. A probe with an empty body
|
||||||
|
* must not carry them.
|
||||||
|
*
|
||||||
|
* @var list<string>
|
||||||
|
*/
|
||||||
|
private const DIGEST_PROBE_PAYLOAD_HEADERS = [
|
||||||
|
'Transfer-Encoding',
|
||||||
|
'Expect',
|
||||||
|
'Trailer',
|
||||||
|
'Content-Range',
|
||||||
|
'Content-Encoding',
|
||||||
|
'Content-MD5',
|
||||||
|
'Digest',
|
||||||
|
'Content-Digest',
|
||||||
|
'Repr-Digest',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
private $nextHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var callable(): string
|
||||||
|
*/
|
||||||
|
private $cnonceGenerator;
|
||||||
|
|
||||||
|
private bool $reuseChallenges;
|
||||||
|
|
||||||
|
private ?string $credentialHashSecret = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, array{challenge: DigestChallenge, credentials: string, nextNc: int}>
|
||||||
|
*/
|
||||||
|
private array $digestChallenges = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $nextHandler
|
||||||
|
* @param (callable(): string)|null $cnonceGenerator
|
||||||
|
*/
|
||||||
|
public function __construct(callable $nextHandler, ?callable $cnonceGenerator = null, bool $reuseChallenges = true)
|
||||||
|
{
|
||||||
|
$this->nextHandler = $nextHandler;
|
||||||
|
$this->cnonceGenerator = $cnonceGenerator ?? static function (): string {
|
||||||
|
return \bin2hex(\random_bytes(16));
|
||||||
|
};
|
||||||
|
$this->reuseChallenges = $reuseChallenges;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
public function __invoke(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options
|
||||||
|
): PromiseInterface {
|
||||||
|
$auth = $options['auth'] ?? null;
|
||||||
|
if ($auth === null || $auth === false || $auth === [] || \is_string($auth)) {
|
||||||
|
return ($this->nextHandler)($request, $options);
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalizedAuth = self::normalizeAuth($auth);
|
||||||
|
if ($normalizedAuth === null) {
|
||||||
|
return ($this->nextHandler)($request, $options);
|
||||||
|
}
|
||||||
|
|
||||||
|
[$username, $password, $type] = $normalizedAuth;
|
||||||
|
|
||||||
|
if ($type === 'basic') {
|
||||||
|
return $this->sendBasic($request, $options, $username, $password);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->sendDigest($request, $options, $username, $password);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $auth
|
||||||
|
*
|
||||||
|
* @return array{0: string, 1: string, 2: 'basic'|'digest'}|null
|
||||||
|
*/
|
||||||
|
private static function normalizeAuth(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $auth
|
||||||
|
): ?array {
|
||||||
|
$type = 'basic';
|
||||||
|
if (\array_key_exists(2, $auth) && $auth[2] !== null) {
|
||||||
|
if (!\is_string($auth[2])) {
|
||||||
|
throw new InvalidArgumentException('auth type must be a string');
|
||||||
|
}
|
||||||
|
|
||||||
|
$type = Psr7\Utils::asciiToLower($auth[2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!\in_array($type, ['basic', 'digest'], true)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!\array_key_exists(0, $auth) || !\array_key_exists(1, $auth)) {
|
||||||
|
throw new InvalidArgumentException('auth must contain username and password strings');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!\is_string($auth[0]) || !\is_string($auth[1])) {
|
||||||
|
throw new InvalidArgumentException('auth must contain username and password strings');
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$auth[0], $auth[1], $type];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
private function sendBasic(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options,
|
||||||
|
string $username,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $password
|
||||||
|
): PromiseInterface {
|
||||||
|
if (\strpos($username, ':') !== false) {
|
||||||
|
throw new InvalidArgumentException('Basic authentication username must not contain a colon');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\preg_match('/[\x00-\x1F\x7F]/', $username.$password) !== 0) {
|
||||||
|
throw new InvalidArgumentException('Basic authentication credentials must not contain ASCII control characters');
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($options['auth']);
|
||||||
|
|
||||||
|
return ($this->nextHandler)(
|
||||||
|
$request->withHeader('Authorization', 'Basic '.\base64_encode($username.':'.$password)),
|
||||||
|
$options
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
private function sendDigest(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options,
|
||||||
|
string $username,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $password
|
||||||
|
): PromiseInterface {
|
||||||
|
$preemptive = $this->reuseChallenges
|
||||||
|
? $this->preemptiveDigestRequest($request, $username, $password)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if ($preemptive !== null) {
|
||||||
|
$preemptiveOptions = self::withTemporarySink($options);
|
||||||
|
unset($preemptiveOptions['auth']);
|
||||||
|
|
||||||
|
return ($this->nextHandler)($preemptive, $preemptiveOptions)->then(
|
||||||
|
function (
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response
|
||||||
|
) use ($request, $options, $preemptiveOptions, $username, $password) {
|
||||||
|
// Clear on 4xx/5xx other than 401 so non-conformant stale-nonce
|
||||||
|
// errors cannot poison the cache indefinitely.
|
||||||
|
$status = $response->getStatusCode();
|
||||||
|
if ($status >= 400 && $status !== 401) {
|
||||||
|
$this->clearDigestChallenge($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->handleDigestResponse($request, $options, $preemptiveOptions, $response, $username, $password, false);
|
||||||
|
},
|
||||||
|
function (
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
$reason
|
||||||
|
) use ($request, $preemptiveOptions) {
|
||||||
|
return $this->handleDigestRejection($request, $preemptiveOptions, $reason, true);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$probeOptions = self::withTemporarySink($options);
|
||||||
|
unset($probeOptions['auth']);
|
||||||
|
|
||||||
|
[$probeRequest, $bodyWithheld] = self::probeRequest($request, $options);
|
||||||
|
|
||||||
|
if ($bodyWithheld) {
|
||||||
|
// The probe has no payload, so prepare_body must not add Expect
|
||||||
|
// if a custom empty stream has unknown size.
|
||||||
|
$probeOptions[RequestOptions::EXPECT] = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ($this->nextHandler)($probeRequest, $probeOptions)->then(
|
||||||
|
function (
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response
|
||||||
|
) use ($request, $options, $probeOptions, $username, $password, $bodyWithheld) {
|
||||||
|
return $this->handleDigestResponse($request, $options, $probeOptions, $response, $username, $password, $bodyWithheld);
|
||||||
|
},
|
||||||
|
function (
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
$reason
|
||||||
|
) use ($request, $probeOptions) {
|
||||||
|
return $this->handleDigestRejection($request, $probeOptions, $reason, false);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function preemptiveDigestRequest(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
string $username,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $password
|
||||||
|
): ?RequestInterface {
|
||||||
|
try {
|
||||||
|
if ($request->getBody()->getSize() !== 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = self::digestCacheKey($request);
|
||||||
|
if ($key === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$entry = $this->digestChallenges[$key] ?? null;
|
||||||
|
if ($entry === null
|
||||||
|
|| $entry['credentials'] !== $this->digestCredentialKey($username, $password)
|
||||||
|
|| !self::challengeCoversRequest($entry['challenge'], $request)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$authorization = DigestAuth::authorizationHeader(
|
||||||
|
$request,
|
||||||
|
$entry['challenge'],
|
||||||
|
$username,
|
||||||
|
$password,
|
||||||
|
($this->cnonceGenerator)(),
|
||||||
|
\sprintf('%08x', $entry['nextNc'])
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($authorization === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
++$this->digestChallenges[$key]['nextNc'];
|
||||||
|
|
||||||
|
return $request->withHeader('Authorization', $authorization);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the unauthenticated probe request for a Digest handshake.
|
||||||
|
*
|
||||||
|
* @return array{0: RequestInterface, 1: bool}
|
||||||
|
*/
|
||||||
|
private static function probeRequest(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options
|
||||||
|
): array {
|
||||||
|
$probe = $request->withoutHeader('Authorization');
|
||||||
|
|
||||||
|
try {
|
||||||
|
$size = $probe->getBody()->getSize();
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$size = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($size === 0) {
|
||||||
|
return [$probe, false];
|
||||||
|
}
|
||||||
|
|
||||||
|
$streamFactory = self::requireStreamFactory(
|
||||||
|
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
|
||||||
|
);
|
||||||
|
|
||||||
|
$probe = $probe->withBody($streamFactory->createStream(''))
|
||||||
|
->withHeader('Content-Length', '0');
|
||||||
|
|
||||||
|
foreach (self::DIGEST_PROBE_PAYLOAD_HEADERS as $header) {
|
||||||
|
$probe = $probe->withoutHeader($header);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$probe, true];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return ResponseInterface|PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
private function handleDigestResponse(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $probeOptions,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response,
|
||||||
|
string $username,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $password,
|
||||||
|
bool $bodyWithheld
|
||||||
|
) {
|
||||||
|
$status = $response->getStatusCode();
|
||||||
|
|
||||||
|
$previousEntry = null;
|
||||||
|
if ($this->reuseChallenges && $status === 401) {
|
||||||
|
$key = self::digestCacheKey($request);
|
||||||
|
$previousEntry = $key !== null ? ($this->digestChallenges[$key] ?? null) : null;
|
||||||
|
$this->clearDigestChallenge($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($status !== 401) {
|
||||||
|
if ($this->reuseChallenges && $response->hasHeader('Authentication-Info')) {
|
||||||
|
$this->clearDigestChallenge($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
$response = self::restoreOriginalSink($request, $response, $probeOptions);
|
||||||
|
|
||||||
|
if ($bodyWithheld && $status !== 407 && !self::isRedirectLikeResponse($response)) {
|
||||||
|
throw new ResponseException(
|
||||||
|
'Digest authentication failed because the server did not issue a challenge; the request was probed without its body',
|
||||||
|
$request,
|
||||||
|
$response
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
$challenge = DigestAuth::selectChallenge($response);
|
||||||
|
if ($challenge === null) {
|
||||||
|
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
$retries = $options['__guzzle_digest_retries'] ?? 0;
|
||||||
|
if (!\is_int($retries)) {
|
||||||
|
$retries = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (($retries > 0 && !$challenge->stale) || $retries >= self::DIGEST_MAX_RETRIES) {
|
||||||
|
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
self::rewindBodyForRetry($request, $bodyWithheld);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$response = self::restoreOriginalSink($request, $response, $probeOptions);
|
||||||
|
|
||||||
|
throw new ResponseException(
|
||||||
|
'Digest authentication failed because the request body could not be rewound',
|
||||||
|
$request,
|
||||||
|
$response,
|
||||||
|
$e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$nonceCounts = self::digestNonceCountsFromOptions($options);
|
||||||
|
|
||||||
|
if ($previousEntry !== null
|
||||||
|
&& $previousEntry['credentials'] === $this->digestCredentialKey($username, $password)
|
||||||
|
) {
|
||||||
|
self::rememberDigestNonceCount($nonceCounts, $previousEntry['challenge'], $previousEntry['nextNc']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$nc = $challenge->qop === null ? 1 : ($nonceCounts[self::digestNonceCountKey($challenge)] ?? 1);
|
||||||
|
|
||||||
|
$authorization = DigestAuth::authorizationHeader(
|
||||||
|
$request,
|
||||||
|
$challenge,
|
||||||
|
$username,
|
||||||
|
$password,
|
||||||
|
($this->cnonceGenerator)(),
|
||||||
|
\sprintf('%08x', $nc)
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($authorization === null) {
|
||||||
|
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
$response->getBody()->close();
|
||||||
|
|
||||||
|
self::rememberDigestNonceCount($nonceCounts, $challenge, $nc + 1);
|
||||||
|
|
||||||
|
$retryOptions = $options;
|
||||||
|
$retryOptions['__guzzle_digest_retries'] = $retries + 1;
|
||||||
|
$retryOptions[self::DIGEST_NONCE_COUNTS_OPTION] = $nonceCounts;
|
||||||
|
$downstreamOptions = $retryOptions;
|
||||||
|
// The nonce-count map only carries handshake state into the retry
|
||||||
|
// recursion; downstream handlers must not observe it.
|
||||||
|
unset($downstreamOptions[self::DIGEST_NONCE_COUNTS_OPTION]);
|
||||||
|
// The caller's delay applies once, before the first Digest leg, not
|
||||||
|
// before each handshake retry.
|
||||||
|
unset($downstreamOptions[RequestOptions::DELAY]);
|
||||||
|
$downstreamOptions = self::withTemporarySink($downstreamOptions);
|
||||||
|
unset($downstreamOptions['auth']);
|
||||||
|
|
||||||
|
$retryRequest = $request->withHeader('Authorization', $authorization);
|
||||||
|
|
||||||
|
return ($this->nextHandler)($retryRequest, $downstreamOptions)->then(
|
||||||
|
function (
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $retryResponse
|
||||||
|
) use ($retryRequest, $retryOptions, $downstreamOptions, $username, $password, $challenge, $nc) {
|
||||||
|
if ($this->reuseChallenges && self::isCacheableDigestSuccess($retryResponse)) {
|
||||||
|
$this->storeDigestChallenge($retryRequest, $challenge, $username, $password, $nc + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->handleDigestResponse($retryRequest, $retryOptions, $downstreamOptions, $retryResponse, $username, $password, false);
|
||||||
|
},
|
||||||
|
function (
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
$reason
|
||||||
|
) use ($retryRequest, $downstreamOptions) {
|
||||||
|
return $this->handleDigestRejection($retryRequest, $downstreamOptions, $reason, false);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isCacheableDigestSuccess(ResponseInterface $response): bool
|
||||||
|
{
|
||||||
|
$status = $response->getStatusCode();
|
||||||
|
|
||||||
|
return $status >= 200 && $status < 400 && !$response->hasHeader('Authentication-Info');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function storeDigestChallenge(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
DigestChallenge $challenge,
|
||||||
|
string $username,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $password,
|
||||||
|
int $nextNc
|
||||||
|
): void {
|
||||||
|
$key = self::digestCacheKey($request);
|
||||||
|
if ($key === null || $challenge->qop === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($this->digestChallenges[$key]);
|
||||||
|
|
||||||
|
if (\count($this->digestChallenges) >= self::CHALLENGE_CACHE_LIMIT) {
|
||||||
|
\array_shift($this->digestChallenges);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->digestChallenges[$key] = [
|
||||||
|
'challenge' => $challenge,
|
||||||
|
'credentials' => $this->digestCredentialKey($username, $password),
|
||||||
|
'nextNc' => $nextNc,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function clearDigestChallenge(RequestInterface $request): void
|
||||||
|
{
|
||||||
|
$key = self::digestCacheKey($request);
|
||||||
|
if ($key !== null) {
|
||||||
|
unset($this->digestChallenges[$key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $options
|
||||||
|
*
|
||||||
|
* @return array<string, int>
|
||||||
|
*/
|
||||||
|
private static function digestNonceCountsFromOptions(array $options): array
|
||||||
|
{
|
||||||
|
$counts = $options[self::DIGEST_NONCE_COUNTS_OPTION] ?? [];
|
||||||
|
if (!\is_array($counts)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalized = [];
|
||||||
|
foreach ($counts as $key => $nextNc) {
|
||||||
|
if (\is_string($key) && \is_int($nextNc) && $nextNc > 0 && $nextNc < \PHP_INT_MAX) {
|
||||||
|
$normalized[$key] = $nextNc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function digestNonceCountKey(DigestChallenge $challenge): string
|
||||||
|
{
|
||||||
|
return \implode("\0", [
|
||||||
|
$challenge->realm,
|
||||||
|
$challenge->nonce,
|
||||||
|
$challenge->qop ?? '',
|
||||||
|
$challenge->algorithm['header'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, int> $counts
|
||||||
|
*/
|
||||||
|
private static function rememberDigestNonceCount(array &$counts, DigestChallenge $challenge, int $nextNc): void
|
||||||
|
{
|
||||||
|
if ($challenge->qop === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = self::digestNonceCountKey($challenge);
|
||||||
|
$counts[$key] = \max($counts[$key] ?? 1, $nextNc);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mixed $reason
|
||||||
|
*
|
||||||
|
* @return PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
private function handleDigestRejection(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
$reason,
|
||||||
|
bool $preemptive
|
||||||
|
): PromiseInterface {
|
||||||
|
if ($this->reuseChallenges && $reason instanceof ResponseException) {
|
||||||
|
$response = $reason->getResponse();
|
||||||
|
|
||||||
|
if ($response->getStatusCode() === 401
|
||||||
|
|| $response->hasHeader('Authentication-Info')
|
||||||
|
|| ($preemptive && $response->getStatusCode() >= 400)
|
||||||
|
) {
|
||||||
|
$this->clearDigestChallenge($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::restoreOriginalSinkOnRejection($options, $reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function digestCacheKey(RequestInterface $request): ?string
|
||||||
|
{
|
||||||
|
$uri = $request->getUri();
|
||||||
|
$scheme = Psr7\Utils::asciiToLower($uri->getScheme());
|
||||||
|
$host = HostIdentity::canonicalHost($uri->getHost());
|
||||||
|
|
||||||
|
if (($scheme !== 'http' && $scheme !== 'https') || $host === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$port = $uri->getPort() ?? ($scheme === 'https' ? 443 : 80);
|
||||||
|
|
||||||
|
return $scheme.'://'.$host.':'.$port.'|'.HostIdentity::canonicalHostHeader($request->getHeaderLine('Host'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function digestCredentialKey(
|
||||||
|
string $username,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $password
|
||||||
|
): string {
|
||||||
|
if ($this->credentialHashSecret === null) {
|
||||||
|
$this->credentialHashSecret = \random_bytes(32);
|
||||||
|
}
|
||||||
|
|
||||||
|
return \hash_hmac('sha256', $username."\0".$password, $this->credentialHashSecret);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function challengeCoversRequest(DigestChallenge $challenge, RequestInterface $request): bool
|
||||||
|
{
|
||||||
|
if ($challenge->domain === []) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$target = $request->getRequestTarget();
|
||||||
|
foreach ($challenge->domain as $space) {
|
||||||
|
$prefix = self::protectionSpacePath($space, $request);
|
||||||
|
if ($prefix !== null && \str_starts_with($target, $prefix)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function protectionSpacePath(string $space, RequestInterface $request): ?string
|
||||||
|
{
|
||||||
|
if ($space === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($space[0] === '/') {
|
||||||
|
return $space;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// A server must not be able to raise the psr7 host deprecation.
|
||||||
|
$uri = (new Psr7\ErrorScope(\E_USER_DEPRECATED))->run(static function () use ($space): Psr7\Uri {
|
||||||
|
return new Psr7\Uri($space);
|
||||||
|
});
|
||||||
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Psr7\UriComparator::isCrossOrigin($uri, self::effectiveRequestUri($request))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = $uri->getPath();
|
||||||
|
$prefix = $path === '' ? '/' : $path;
|
||||||
|
|
||||||
|
if ($uri->getQuery() !== '') {
|
||||||
|
$prefix .= '?'.$uri->getQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $prefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function effectiveRequestUri(RequestInterface $request): UriInterface
|
||||||
|
{
|
||||||
|
$uri = $request->getUri();
|
||||||
|
$host = $request->getHeaderLine('Host');
|
||||||
|
if ($host === '' || Psr7\Utils::caselessEquals($host, $uri->getHost())) {
|
||||||
|
return $uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$authority = new Psr7\Uri('//'.$host);
|
||||||
|
if ($authority->getHost() === '') {
|
||||||
|
return $uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $uri->withHost($authority->getHost())->withPort($authority->getPort());
|
||||||
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
return $uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isRedirectLikeResponse(ResponseInterface $response): bool
|
||||||
|
{
|
||||||
|
return $response->hasHeader('Location')
|
||||||
|
&& \in_array($response->getStatusCode(), [301, 302, 303, 307, 308], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function rewindBodyForRetry(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
bool $bodyWithheld
|
||||||
|
): void {
|
||||||
|
$body = $request->getBody();
|
||||||
|
|
||||||
|
if (!$bodyWithheld) {
|
||||||
|
try {
|
||||||
|
if ($body->getSize() === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
// Fall through to the standard rewind path.
|
||||||
|
}
|
||||||
|
|
||||||
|
Psr7\Message::rewindBody($request);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($body->isSeekable()) {
|
||||||
|
$body->rewind();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function withTemporarySink(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options
|
||||||
|
): array {
|
||||||
|
// The 'stream' option is deliberately not checked here: the cURL
|
||||||
|
// handlers do not support streaming and write each leg to the sink,
|
||||||
|
// so a configured sink always needs challenge-body protection.
|
||||||
|
if (!isset($options[RequestOptions::SINK])) {
|
||||||
|
return $options;
|
||||||
|
}
|
||||||
|
|
||||||
|
$streamFactory = self::requireStreamFactory(
|
||||||
|
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
|
||||||
|
);
|
||||||
|
|
||||||
|
$options['__guzzle_auth_original_sink'] = $options[RequestOptions::SINK];
|
||||||
|
$options[RequestOptions::SINK] = $streamFactory->createStreamFromResource(
|
||||||
|
Psr7\Utils::tryFopen('php://temp', 'w+')
|
||||||
|
);
|
||||||
|
|
||||||
|
return $options;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function restoreOriginalSink(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options
|
||||||
|
): ResponseInterface {
|
||||||
|
if (!\array_key_exists('__guzzle_auth_original_sink', $options)) {
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$source = $response->getBody();
|
||||||
|
if ($source->isSeekable()) {
|
||||||
|
$source->rewind();
|
||||||
|
}
|
||||||
|
|
||||||
|
$target = self::streamForOriginalSink($options['__guzzle_auth_original_sink']);
|
||||||
|
|
||||||
|
Psr7\Utils::copyToStream($source, $target);
|
||||||
|
|
||||||
|
if ($target->isSeekable()) {
|
||||||
|
$target->rewind();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $response->withBody($target);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
throw new ResponseException(
|
||||||
|
$e->getMessage() !== '' ? $e->getMessage() : 'Failed to write the response body',
|
||||||
|
$request,
|
||||||
|
$response,
|
||||||
|
$e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mixed $reason
|
||||||
|
*
|
||||||
|
* @return PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
private static function restoreOriginalSinkOnRejection(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $options,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
$reason
|
||||||
|
): PromiseInterface {
|
||||||
|
if (!$reason instanceof ResponseException || !\array_key_exists('__guzzle_auth_original_sink', $options)) {
|
||||||
|
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||||
|
return P\Create::rejectionFor($reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = self::restoreOriginalSink($reason->getRequest(), $reason->getResponse(), $options);
|
||||||
|
|
||||||
|
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||||
|
return P\Create::rejectionFor($reason->withResponse($response));
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||||
|
return P\Create::rejectionFor($e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mixed $sink
|
||||||
|
*/
|
||||||
|
private static function streamForOriginalSink($sink): StreamInterface
|
||||||
|
{
|
||||||
|
if (\is_string($sink)) {
|
||||||
|
return new LazyOpenStream($sink, 'w+');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\is_resource($sink)) {
|
||||||
|
return self::streamForResourceSink(Psr7\Utils::streamFor($sink));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$sink instanceof StreamInterface) {
|
||||||
|
throw new InvalidArgumentException(\sprintf(
|
||||||
|
'sink must be a resource, string, or %s',
|
||||||
|
StreamInterface::class
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Psr7\Utils::streamFor($sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decorates a caller-owned sink stream so that closing the response body
|
||||||
|
* detaches Guzzle's wrapper without closing the original PHP resource.
|
||||||
|
*/
|
||||||
|
private static function streamForResourceSink(StreamInterface $stream): StreamInterface
|
||||||
|
{
|
||||||
|
return Psr7\FnStream::decorate($stream, [
|
||||||
|
'close' => static function () use ($stream): void {
|
||||||
|
$stream->detach();
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mixed $factory
|
||||||
|
*/
|
||||||
|
private static function requireStreamFactory($factory): StreamFactoryInterface
|
||||||
|
{
|
||||||
|
if (!$factory instanceof StreamFactoryInterface) {
|
||||||
|
throw new InvalidArgumentException(\sprintf(
|
||||||
|
'%s must be an instance of %s',
|
||||||
|
RequestOptions::STREAM_FACTORY,
|
||||||
|
StreamFactoryInterface::class
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $factory;
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp;
|
||||||
|
|
||||||
|
use Psr\Http\Message\MessageInterface;
|
||||||
|
|
||||||
|
final class BodySummarizer implements BodySummarizerInterface
|
||||||
|
{
|
||||||
|
private ?int $truncateAt;
|
||||||
|
|
||||||
|
public function __construct(?int $truncateAt = null)
|
||||||
|
{
|
||||||
|
$this->truncateAt = $truncateAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a summarized message body.
|
||||||
|
*/
|
||||||
|
public function summarize(MessageInterface $message): ?string
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return Psr7\Message::bodySummary($message, $this->truncateAt);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp;
|
||||||
|
|
||||||
|
use Psr\Http\Message\MessageInterface;
|
||||||
|
|
||||||
|
interface BodySummarizerInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Returns a summarized message body.
|
||||||
|
*/
|
||||||
|
public function summarize(MessageInterface $message): ?string;
|
||||||
|
}
|
||||||
+1716
File diff suppressed because it is too large
Load Diff
+370
@@ -0,0 +1,370 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp;
|
||||||
|
|
||||||
|
use GuzzleHttp\Cookie\CookieJarInterface;
|
||||||
|
use GuzzleHttp\Exception\GuzzleException;
|
||||||
|
use GuzzleHttp\Promise\PromiseInterface;
|
||||||
|
use Psr\Http\Message\RequestFactoryInterface;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Psr\Http\Message\ResponseFactoryInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\StreamFactoryInterface;
|
||||||
|
use Psr\Http\Message\StreamInterface;
|
||||||
|
use Psr\Http\Message\UriFactoryInterface;
|
||||||
|
use Psr\Http\Message\UriInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client interface for sending HTTP requests.
|
||||||
|
*/
|
||||||
|
interface ClientInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The Guzzle major version.
|
||||||
|
*/
|
||||||
|
public const MAJOR_VERSION = 8;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send an HTTP request.
|
||||||
|
*
|
||||||
|
* @param RequestInterface $request Request to send
|
||||||
|
* @param array{
|
||||||
|
* base_uri?: string|UriInterface,
|
||||||
|
* allow_redirects?: bool|array{
|
||||||
|
* max?: int,
|
||||||
|
* strict?: bool,
|
||||||
|
* referer?: bool,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||||
|
* track_redirects?: bool
|
||||||
|
* },
|
||||||
|
* auth?: array{
|
||||||
|
* 0: string,
|
||||||
|
* 1: string,
|
||||||
|
* 2?: string|null
|
||||||
|
* }|string|false|null,
|
||||||
|
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||||
|
* cert?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* cert_type?: string,
|
||||||
|
* connect_timeout?: int|float,
|
||||||
|
* cookies?: false|CookieJarInterface,
|
||||||
|
* crypto_method?: int,
|
||||||
|
* crypto_method_max?: int,
|
||||||
|
* debug?: bool|resource,
|
||||||
|
* decode_content?: bool|string,
|
||||||
|
* delay?: int|float,
|
||||||
|
* expect?: bool|int,
|
||||||
|
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||||
|
* force_ip_resolve?: string,
|
||||||
|
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||||
|
* http_errors?: bool,
|
||||||
|
* idn_conversion?: bool|int|null,
|
||||||
|
* json?: mixed,
|
||||||
|
* multipart?: array<array-key, array{
|
||||||
|
* name: string|int,
|
||||||
|
* contents: mixed,
|
||||||
|
* headers?: array<array-key, string>,
|
||||||
|
* filename?: string
|
||||||
|
* }>,
|
||||||
|
* multiplex?: string,
|
||||||
|
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||||
|
* on_stats?: callable(TransferStats): mixed,
|
||||||
|
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||||
|
* progress?: callable(int, int, int, int): mixed,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* proxy?: string|array{
|
||||||
|
* http?: string|null,
|
||||||
|
* https?: string|null,
|
||||||
|
* no?: string|array<array-key, string>|null
|
||||||
|
* },
|
||||||
|
* query?: array<array-key, mixed>|string,
|
||||||
|
* read_timeout?: int|float,
|
||||||
|
* retries?: int,
|
||||||
|
* request_factory?: RequestFactoryInterface,
|
||||||
|
* response_factory?: ResponseFactoryInterface,
|
||||||
|
* sink?: resource|string|StreamInterface,
|
||||||
|
* ssl_key?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* ssl_key_type?: string,
|
||||||
|
* stream?: bool,
|
||||||
|
* stream_factory?: StreamFactoryInterface,
|
||||||
|
* stream_context?: array<array-key, mixed>,
|
||||||
|
* synchronous?: bool,
|
||||||
|
* timeout?: int|float,
|
||||||
|
* uri_factory?: UriFactoryInterface,
|
||||||
|
* verify?: bool|string,
|
||||||
|
* version?: string|int|float,
|
||||||
|
* curl?: array<int|string, mixed>,
|
||||||
|
* ...
|
||||||
|
* } $options Request options to apply to the given request and to the transfer.
|
||||||
|
*
|
||||||
|
* @throws GuzzleException
|
||||||
|
*/
|
||||||
|
public function send(RequestInterface $request, array $options = []): ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asynchronously send an HTTP request.
|
||||||
|
*
|
||||||
|
* @param RequestInterface $request Request to send
|
||||||
|
* @param array{
|
||||||
|
* base_uri?: string|UriInterface,
|
||||||
|
* allow_redirects?: bool|array{
|
||||||
|
* max?: int,
|
||||||
|
* strict?: bool,
|
||||||
|
* referer?: bool,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||||
|
* track_redirects?: bool
|
||||||
|
* },
|
||||||
|
* auth?: array{
|
||||||
|
* 0: string,
|
||||||
|
* 1: string,
|
||||||
|
* 2?: string|null
|
||||||
|
* }|string|false|null,
|
||||||
|
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||||
|
* cert?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* cert_type?: string,
|
||||||
|
* connect_timeout?: int|float,
|
||||||
|
* cookies?: false|CookieJarInterface,
|
||||||
|
* crypto_method?: int,
|
||||||
|
* crypto_method_max?: int,
|
||||||
|
* debug?: bool|resource,
|
||||||
|
* decode_content?: bool|string,
|
||||||
|
* delay?: int|float,
|
||||||
|
* expect?: bool|int,
|
||||||
|
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||||
|
* force_ip_resolve?: string,
|
||||||
|
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||||
|
* http_errors?: bool,
|
||||||
|
* idn_conversion?: bool|int|null,
|
||||||
|
* json?: mixed,
|
||||||
|
* multipart?: array<array-key, array{
|
||||||
|
* name: string|int,
|
||||||
|
* contents: mixed,
|
||||||
|
* headers?: array<array-key, string>,
|
||||||
|
* filename?: string
|
||||||
|
* }>,
|
||||||
|
* multiplex?: string,
|
||||||
|
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||||
|
* on_stats?: callable(TransferStats): mixed,
|
||||||
|
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||||
|
* progress?: callable(int, int, int, int): mixed,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* proxy?: string|array{
|
||||||
|
* http?: string|null,
|
||||||
|
* https?: string|null,
|
||||||
|
* no?: string|array<array-key, string>|null
|
||||||
|
* },
|
||||||
|
* query?: array<array-key, mixed>|string,
|
||||||
|
* read_timeout?: int|float,
|
||||||
|
* retries?: int,
|
||||||
|
* request_factory?: RequestFactoryInterface,
|
||||||
|
* response_factory?: ResponseFactoryInterface,
|
||||||
|
* sink?: resource|string|StreamInterface,
|
||||||
|
* ssl_key?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* ssl_key_type?: string,
|
||||||
|
* stream?: bool,
|
||||||
|
* stream_factory?: StreamFactoryInterface,
|
||||||
|
* stream_context?: array<array-key, mixed>,
|
||||||
|
* synchronous?: bool,
|
||||||
|
* timeout?: int|float,
|
||||||
|
* uri_factory?: UriFactoryInterface,
|
||||||
|
* verify?: bool|string,
|
||||||
|
* version?: string|int|float,
|
||||||
|
* curl?: array<int|string, mixed>,
|
||||||
|
* ...
|
||||||
|
* } $options Request options to apply to the given request and to the transfer.
|
||||||
|
*
|
||||||
|
* @return PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create and send an HTTP request.
|
||||||
|
*
|
||||||
|
* Use an absolute path to override the base path of the client, or a
|
||||||
|
* relative path to append to the base path of the client. The URL can
|
||||||
|
* contain the query string as well.
|
||||||
|
*
|
||||||
|
* @param string $method HTTP method.
|
||||||
|
* @param string|UriInterface $uri URI object or string.
|
||||||
|
* @param array{
|
||||||
|
* base_uri?: string|UriInterface,
|
||||||
|
* allow_redirects?: bool|array{
|
||||||
|
* max?: int,
|
||||||
|
* strict?: bool,
|
||||||
|
* referer?: bool,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||||
|
* track_redirects?: bool
|
||||||
|
* },
|
||||||
|
* auth?: array{
|
||||||
|
* 0: string,
|
||||||
|
* 1: string,
|
||||||
|
* 2?: string|null
|
||||||
|
* }|string|false|null,
|
||||||
|
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||||
|
* cert?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* cert_type?: string,
|
||||||
|
* connect_timeout?: int|float,
|
||||||
|
* cookies?: false|CookieJarInterface,
|
||||||
|
* crypto_method?: int,
|
||||||
|
* crypto_method_max?: int,
|
||||||
|
* debug?: bool|resource,
|
||||||
|
* decode_content?: bool|string,
|
||||||
|
* delay?: int|float,
|
||||||
|
* expect?: bool|int,
|
||||||
|
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||||
|
* force_ip_resolve?: string,
|
||||||
|
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||||
|
* http_errors?: bool,
|
||||||
|
* idn_conversion?: bool|int|null,
|
||||||
|
* json?: mixed,
|
||||||
|
* multipart?: array<array-key, array{
|
||||||
|
* name: string|int,
|
||||||
|
* contents: mixed,
|
||||||
|
* headers?: array<array-key, string>,
|
||||||
|
* filename?: string
|
||||||
|
* }>,
|
||||||
|
* multiplex?: string,
|
||||||
|
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||||
|
* on_stats?: callable(TransferStats): mixed,
|
||||||
|
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||||
|
* progress?: callable(int, int, int, int): mixed,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* proxy?: string|array{
|
||||||
|
* http?: string|null,
|
||||||
|
* https?: string|null,
|
||||||
|
* no?: string|array<array-key, string>|null
|
||||||
|
* },
|
||||||
|
* query?: array<array-key, mixed>|string,
|
||||||
|
* read_timeout?: int|float,
|
||||||
|
* retries?: int,
|
||||||
|
* request_factory?: RequestFactoryInterface,
|
||||||
|
* response_factory?: ResponseFactoryInterface,
|
||||||
|
* sink?: resource|string|StreamInterface,
|
||||||
|
* ssl_key?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* ssl_key_type?: string,
|
||||||
|
* stream?: bool,
|
||||||
|
* stream_factory?: StreamFactoryInterface,
|
||||||
|
* stream_context?: array<array-key, mixed>,
|
||||||
|
* synchronous?: bool,
|
||||||
|
* timeout?: int|float,
|
||||||
|
* uri_factory?: UriFactoryInterface,
|
||||||
|
* verify?: bool|string,
|
||||||
|
* version?: string|int|float,
|
||||||
|
* curl?: array<int|string, mixed>,
|
||||||
|
* ...
|
||||||
|
* } $options Request options to apply.
|
||||||
|
*
|
||||||
|
* @throws GuzzleException
|
||||||
|
*/
|
||||||
|
public function request(string $method, $uri, array $options = []): ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create and send an asynchronous HTTP request.
|
||||||
|
*
|
||||||
|
* Use an absolute path to override the base path of the client, or a
|
||||||
|
* relative path to append to the base path of the client. The URL can
|
||||||
|
* contain the query string as well.
|
||||||
|
*
|
||||||
|
* @param string $method HTTP method
|
||||||
|
* @param string|UriInterface $uri URI object or string.
|
||||||
|
* @param array{
|
||||||
|
* base_uri?: string|UriInterface,
|
||||||
|
* allow_redirects?: bool|array{
|
||||||
|
* max?: int,
|
||||||
|
* strict?: bool,
|
||||||
|
* referer?: bool,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||||
|
* track_redirects?: bool
|
||||||
|
* },
|
||||||
|
* auth?: array{
|
||||||
|
* 0: string,
|
||||||
|
* 1: string,
|
||||||
|
* 2?: string|null
|
||||||
|
* }|string|false|null,
|
||||||
|
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||||
|
* cert?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* cert_type?: string,
|
||||||
|
* connect_timeout?: int|float,
|
||||||
|
* cookies?: false|CookieJarInterface,
|
||||||
|
* crypto_method?: int,
|
||||||
|
* crypto_method_max?: int,
|
||||||
|
* debug?: bool|resource,
|
||||||
|
* decode_content?: bool|string,
|
||||||
|
* delay?: int|float,
|
||||||
|
* expect?: bool|int,
|
||||||
|
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||||
|
* force_ip_resolve?: string,
|
||||||
|
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||||
|
* http_errors?: bool,
|
||||||
|
* idn_conversion?: bool|int|null,
|
||||||
|
* json?: mixed,
|
||||||
|
* multipart?: array<array-key, array{
|
||||||
|
* name: string|int,
|
||||||
|
* contents: mixed,
|
||||||
|
* headers?: array<array-key, string>,
|
||||||
|
* filename?: string
|
||||||
|
* }>,
|
||||||
|
* multiplex?: string,
|
||||||
|
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||||
|
* on_stats?: callable(TransferStats): mixed,
|
||||||
|
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||||
|
* progress?: callable(int, int, int, int): mixed,
|
||||||
|
* protocols?: non-empty-array<array-key, string>,
|
||||||
|
* proxy?: string|array{
|
||||||
|
* http?: string|null,
|
||||||
|
* https?: string|null,
|
||||||
|
* no?: string|array<array-key, string>|null
|
||||||
|
* },
|
||||||
|
* query?: array<array-key, mixed>|string,
|
||||||
|
* read_timeout?: int|float,
|
||||||
|
* retries?: int,
|
||||||
|
* request_factory?: RequestFactoryInterface,
|
||||||
|
* response_factory?: ResponseFactoryInterface,
|
||||||
|
* sink?: resource|string|StreamInterface,
|
||||||
|
* ssl_key?: string|array{
|
||||||
|
* 0: string,
|
||||||
|
* 1?: string|null
|
||||||
|
* },
|
||||||
|
* ssl_key_type?: string,
|
||||||
|
* stream?: bool,
|
||||||
|
* stream_factory?: StreamFactoryInterface,
|
||||||
|
* stream_context?: array<array-key, mixed>,
|
||||||
|
* synchronous?: bool,
|
||||||
|
* timeout?: int|float,
|
||||||
|
* uri_factory?: UriFactoryInterface,
|
||||||
|
* verify?: bool|string,
|
||||||
|
* version?: string|int|float,
|
||||||
|
* curl?: array<int|string, mixed>,
|
||||||
|
* ...
|
||||||
|
* } $options Request options to apply.
|
||||||
|
*
|
||||||
|
* @return PromiseInterface<ResponseInterface, mixed>
|
||||||
|
*/
|
||||||
|
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
|
||||||
|
}
|
||||||
+1315
File diff suppressed because it is too large
Load Diff
+452
@@ -0,0 +1,452 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Cookie;
|
||||||
|
|
||||||
|
use GuzzleHttp\HostIdentity;
|
||||||
|
use GuzzleHttp\Psr7;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cookie jar that stores cookies as an array
|
||||||
|
*/
|
||||||
|
class CookieJar implements CookieJarInterface
|
||||||
|
{
|
||||||
|
private const MAX_SET_COOKIE_FIELD_LENGTH = 8190;
|
||||||
|
private const MAX_SET_COOKIE_FIELDS = 50;
|
||||||
|
private const MAX_REQUEST_COOKIES = 150;
|
||||||
|
private const MAX_COOKIE_HEADER_LENGTH = 8190;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var SetCookie[] Loaded cookie data
|
||||||
|
*/
|
||||||
|
private array $cookies = [];
|
||||||
|
|
||||||
|
private bool $strictMode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param bool $strictMode Set to true to throw exceptions when invalid
|
||||||
|
* cookies are added to the cookie jar.
|
||||||
|
* @param array $cookieArray Array of SetCookie objects or a hash of
|
||||||
|
* arrays that can be used with the SetCookie
|
||||||
|
* constructor
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
bool $strictMode = false,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $cookieArray = []
|
||||||
|
) {
|
||||||
|
$this->strictMode = $strictMode;
|
||||||
|
|
||||||
|
foreach ($cookieArray as $cookie) {
|
||||||
|
if (!$cookie instanceof SetCookie) {
|
||||||
|
$cookie = new SetCookie($cookie);
|
||||||
|
}
|
||||||
|
$this->setCookie($cookie);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new Cookie jar from an associative array and domain.
|
||||||
|
*
|
||||||
|
* @param array $cookies Cookies to create the jar from
|
||||||
|
* @param string $domain Domain to set the cookies to
|
||||||
|
*/
|
||||||
|
public static function fromArray(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $cookies,
|
||||||
|
string $domain
|
||||||
|
): self {
|
||||||
|
$cookieJar = new self();
|
||||||
|
foreach ($cookies as $name => $value) {
|
||||||
|
if (!\is_scalar($value) && !(\is_object($value) && \method_exists($value, '__toString'))) {
|
||||||
|
throw new \InvalidArgumentException('Cookie value must be scalar or stringable');
|
||||||
|
}
|
||||||
|
|
||||||
|
$cookieJar->setCookie(new SetCookie([
|
||||||
|
'Domain' => $domain,
|
||||||
|
'Name' => (string) $name,
|
||||||
|
'Value' => (string) $value,
|
||||||
|
'Discard' => true,
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cookieJar;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evaluate if this cookie should be persisted to storage
|
||||||
|
* that survives between requests.
|
||||||
|
*
|
||||||
|
* @param SetCookie $cookie Being evaluated.
|
||||||
|
* @param bool $allowSessionCookies If we should persist session cookies
|
||||||
|
*/
|
||||||
|
public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
|
||||||
|
{
|
||||||
|
if ($cookie->getExpires() || $allowSessionCookies) {
|
||||||
|
if (!$cookie->getDiscard()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds and returns the cookie based on the name
|
||||||
|
*
|
||||||
|
* @param string $name cookie name to search for
|
||||||
|
*
|
||||||
|
* @return SetCookie|null cookie that was found or null if not found
|
||||||
|
*/
|
||||||
|
public function getCookieByName(string $name): ?SetCookie
|
||||||
|
{
|
||||||
|
foreach ($this->cookies as $cookie) {
|
||||||
|
if ($cookie->getName() === $name) {
|
||||||
|
return $cookie;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return \array_map(static function (SetCookie $cookie): array {
|
||||||
|
return $cookie->toArray();
|
||||||
|
}, $this->getIterator()->getArrayCopy());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void
|
||||||
|
{
|
||||||
|
if ($domain === null) {
|
||||||
|
$this->cookies = [];
|
||||||
|
|
||||||
|
return;
|
||||||
|
} elseif ($path === null) {
|
||||||
|
$this->cookies = \array_filter(
|
||||||
|
$this->cookies,
|
||||||
|
static function (SetCookie $cookie) use ($domain): bool {
|
||||||
|
return $cookie->getDomain() === null || !$cookie->matchesDomain($domain);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} elseif ($name === null) {
|
||||||
|
$this->cookies = \array_filter(
|
||||||
|
$this->cookies,
|
||||||
|
static function (SetCookie $cookie) use ($path, $domain): bool {
|
||||||
|
return !($cookie->getDomain() !== null
|
||||||
|
&& $cookie->matchesPath($path)
|
||||||
|
&& $cookie->matchesDomain($domain));
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$this->cookies = \array_filter(
|
||||||
|
$this->cookies,
|
||||||
|
static function (SetCookie $cookie) use ($path, $domain, $name): bool {
|
||||||
|
return !($cookie->getDomain() !== null
|
||||||
|
&& $cookie->getName() === $name
|
||||||
|
&& $cookie->matchesPath($path)
|
||||||
|
&& $cookie->matchesDomain($domain));
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function clearSessionCookies(): void
|
||||||
|
{
|
||||||
|
$this->cookies = \array_filter(
|
||||||
|
$this->cookies,
|
||||||
|
static function (SetCookie $cookie): bool {
|
||||||
|
return !$cookie->getDiscard() && $cookie->getExpires();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setCookie(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
SetCookie $cookie
|
||||||
|
): bool {
|
||||||
|
// If the name string is empty (but not 0), ignore the set-cookie
|
||||||
|
// string entirely.
|
||||||
|
$name = $cookie->getName();
|
||||||
|
if (!$name && $name !== '0') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only allow cookies with set and valid domain, name, value
|
||||||
|
$result = $cookie->validate();
|
||||||
|
if ($result !== true) {
|
||||||
|
if ($this->strictMode) {
|
||||||
|
throw new \RuntimeException('Invalid cookie: '.$result);
|
||||||
|
}
|
||||||
|
$this->removeCookieIfEmpty($cookie);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$maxAge = $cookie->getMaxAge();
|
||||||
|
if (($maxAge !== null && $maxAge <= 0) || $cookie->isExpired()) {
|
||||||
|
if ($cookie->getDomain() !== null) {
|
||||||
|
$this->removeCookie($cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve conflicts with previously set cookies
|
||||||
|
$replaced = false;
|
||||||
|
foreach ($this->cookies as $i => $c) {
|
||||||
|
// Two cookies are identical, when their path, and domain are
|
||||||
|
// identical.
|
||||||
|
if ($c->getPath() !== $cookie->getPath()
|
||||||
|
|| $c->getDomain() !== $cookie->getDomain()
|
||||||
|
|| $c->getHostOnly() !== $cookie->getHostOnly()
|
||||||
|
|| $c->getName() !== $cookie->getName()
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// An expired cookie is gone, so it must not lend its position
|
||||||
|
if ($c->isExpired()) {
|
||||||
|
unset($this->cookies[$i]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A stored cookie can be mutated into a duplicate, so drop later matches
|
||||||
|
if ($replaced) {
|
||||||
|
unset($this->cookies[$i]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace the old cookie in place when its value, expiry or flags
|
||||||
|
// changed, so it keeps its position among the other cookies
|
||||||
|
if ($cookie->getValue() !== $c->getValue()
|
||||||
|
|| $cookie->getExpires() !== $c->getExpires()
|
||||||
|
|| $cookie->getDiscard() !== $c->getDiscard()
|
||||||
|
|| $cookie->getSecure() !== $c->getSecure()
|
||||||
|
|| $cookie->getHttpOnly() !== $c->getHttpOnly()
|
||||||
|
) {
|
||||||
|
$this->cookies[$i] = $cookie;
|
||||||
|
$replaced = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The cookie exists, so no need to continue
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$replaced) {
|
||||||
|
$this->cookies[] = $cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function count(): int
|
||||||
|
{
|
||||||
|
return \count($this->cookies);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return \ArrayIterator<int, SetCookie>
|
||||||
|
*/
|
||||||
|
public function getIterator(): \ArrayIterator
|
||||||
|
{
|
||||||
|
return new \ArrayIterator(\array_values($this->cookies));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function extractCookies(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response
|
||||||
|
): void {
|
||||||
|
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
|
||||||
|
$uri = $request->getUri();
|
||||||
|
$requestHost = HostIdentity::canonicalHost($uri->getHost());
|
||||||
|
$secure = $uri->getScheme() === 'https';
|
||||||
|
$accepted = 0;
|
||||||
|
|
||||||
|
foreach ($cookieHeader as $cookie) {
|
||||||
|
if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$sc = SetCookie::fromString($cookie);
|
||||||
|
$domain = $sc->getDomain();
|
||||||
|
if ($domain === null || $domain === '') {
|
||||||
|
$sc->setDomain($requestHost);
|
||||||
|
$sc->setHostOnly(true);
|
||||||
|
} else {
|
||||||
|
$sc->setHostOnly(false);
|
||||||
|
}
|
||||||
|
if (0 !== \strpos($sc->getPath(), '/')) {
|
||||||
|
$sc->setPath($this->getCookiePathFromRequest($request));
|
||||||
|
}
|
||||||
|
if (!$sc->matchesDomain($requestHost)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!$secure && ($sc->getSecure() || $this->overlaysSecureCookie($sc))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$prefixName = Psr7\Utils::asciiToLower((string) $sc->getName());
|
||||||
|
if (\str_starts_with($prefixName, '__secure-') && !$sc->getSecure()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (\str_starts_with($prefixName, '__host-') && (!$sc->getSecure() || !$sc->getHostOnly() || $sc->getPath() !== '/' || !self::hasPathAttribute($cookie))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Note: At this point `$sc->getDomain()` being a public suffix should
|
||||||
|
// be rejected, but we don't want to pull in the full PSL dependency.
|
||||||
|
if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function overlaysSecureCookie(SetCookie $cookie): bool
|
||||||
|
{
|
||||||
|
foreach ($this->cookies as $stored) {
|
||||||
|
if (self::isSecureCookieOverlay($cookie, $stored)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function isSecureCookieOverlay(SetCookie $cookie, SetCookie $stored): bool
|
||||||
|
{
|
||||||
|
if ($stored->getName() !== $cookie->getName() || !$stored->getSecure() || $stored->isExpired()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$domain = $cookie->getDomain();
|
||||||
|
$storedDomain = $stored->getDomain();
|
||||||
|
if ($domain === null || $storedDomain === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!HostIdentity::cookieDomainMatches($storedDomain, $domain) && !HostIdentity::cookieDomainMatches($domain, $storedDomain)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $stored->matchesPath($cookie->getPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors SetCookie::fromString()'s splitting because parsed cookies cannot
|
||||||
|
* distinguish an absent Path attribute from a defaulted path.
|
||||||
|
*/
|
||||||
|
private static function hasPathAttribute(string $header): bool
|
||||||
|
{
|
||||||
|
$parts = \explode(';', $header);
|
||||||
|
\array_shift($parts);
|
||||||
|
|
||||||
|
foreach ($parts as $part) {
|
||||||
|
$separator = \strpos($part, '=');
|
||||||
|
if ($separator !== false && Psr7\Utils::caselessEquals(\trim(\substr($part, 0, $separator), " \t"), 'Path')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes cookie path following RFC 6265 section 5.1.4
|
||||||
|
*
|
||||||
|
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
|
||||||
|
*/
|
||||||
|
private function getCookiePathFromRequest(RequestInterface $request): string
|
||||||
|
{
|
||||||
|
$uriPath = $request->getUri()->getPath();
|
||||||
|
if ('' === $uriPath) {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
if (0 !== \strpos($uriPath, '/')) {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
if ('/' === $uriPath) {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
$lastSlashPos = \strrpos($uriPath, '/');
|
||||||
|
if (0 === $lastSlashPos || false === $lastSlashPos) {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
return \substr($uriPath, 0, $lastSlashPos);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function withCookieHeader(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request
|
||||||
|
): RequestInterface {
|
||||||
|
$values = [];
|
||||||
|
$count = 0;
|
||||||
|
$headerLength = 8;
|
||||||
|
$uri = $request->getUri();
|
||||||
|
$scheme = $uri->getScheme();
|
||||||
|
$host = HostIdentity::canonicalHost($uri->getHost());
|
||||||
|
$path = $uri->getPath() ?: '/';
|
||||||
|
|
||||||
|
foreach ($this->cookies as $cookie) {
|
||||||
|
if ($cookie->getDomain() !== null
|
||||||
|
&& $cookie->matchesPath($path)
|
||||||
|
&& $cookie->matchesDomain($host)
|
||||||
|
&& !$cookie->isExpired()
|
||||||
|
&& (!$cookie->getSecure() || $scheme === 'https')
|
||||||
|
) {
|
||||||
|
$name = (string) $cookie->getName();
|
||||||
|
$value = (string) $cookie->getValue();
|
||||||
|
$separatorLength = $values === [] ? 0 : 2;
|
||||||
|
$valueLength = \strlen($name) + 1 + \strlen($value);
|
||||||
|
if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$values[\strlen($cookie->getPath())][] = $name.'='.$value;
|
||||||
|
$headerLength += $separatorLength + $valueLength;
|
||||||
|
if (++$count === self::MAX_REQUEST_COOKIES) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Longer paths first, then creation order, as in RFC 6265 section 5.4,
|
||||||
|
// sorted after the limits so later cookies cannot crowd out older ones
|
||||||
|
\krsort($values);
|
||||||
|
|
||||||
|
return $values
|
||||||
|
? $request->withHeader('Cookie', \implode('; ', \array_merge(...$values)))
|
||||||
|
: $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If a cookie already exists and the server asks to set it again with a
|
||||||
|
* null value, the cookie must be deleted.
|
||||||
|
*/
|
||||||
|
private function removeCookieIfEmpty(SetCookie $cookie): void
|
||||||
|
{
|
||||||
|
$cookieValue = $cookie->getValue();
|
||||||
|
if (($cookieValue === null || $cookieValue === '') && $cookie->getDomain() !== null) {
|
||||||
|
$this->removeCookie($cookie);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function removeCookie(SetCookie $cookie): void
|
||||||
|
{
|
||||||
|
$this->cookies = \array_filter(
|
||||||
|
$this->cookies,
|
||||||
|
static function (SetCookie $stored) use ($cookie): bool {
|
||||||
|
return !($stored->getName() === $cookie->getName()
|
||||||
|
&& $stored->getPath() === $cookie->getPath()
|
||||||
|
&& $stored->getDomain() === $cookie->getDomain()
|
||||||
|
&& $stored->getHostOnly() === $cookie->getHostOnly());
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Cookie;
|
||||||
|
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores HTTP cookies.
|
||||||
|
*
|
||||||
|
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
|
||||||
|
* CookieJarInterface instances automatically expire contained cookies when
|
||||||
|
* necessary. Subclasses are also responsible for storing and retrieving
|
||||||
|
* cookies from a file, database, etc.
|
||||||
|
*
|
||||||
|
* @see https://docs.python.org/2/library/cookielib.html Inspiration
|
||||||
|
*
|
||||||
|
* @extends \IteratorAggregate<SetCookie>
|
||||||
|
*/
|
||||||
|
interface CookieJarInterface extends \Countable, \IteratorAggregate
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create a request with added cookie headers.
|
||||||
|
*
|
||||||
|
* If no matching cookies are found in the cookie jar, then no Cookie
|
||||||
|
* header is added to the request and the same request is returned.
|
||||||
|
*
|
||||||
|
* @param RequestInterface $request Request object to modify.
|
||||||
|
*
|
||||||
|
* @return RequestInterface returns the modified request.
|
||||||
|
*/
|
||||||
|
public function withCookieHeader(RequestInterface $request): RequestInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract cookies from an HTTP response and store them in the CookieJar.
|
||||||
|
*
|
||||||
|
* @param RequestInterface $request Request that was sent
|
||||||
|
* @param ResponseInterface $response Response that was received
|
||||||
|
*/
|
||||||
|
public function extractCookies(RequestInterface $request, ResponseInterface $response): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets a cookie in the cookie jar.
|
||||||
|
*
|
||||||
|
* @param SetCookie $cookie Cookie to set.
|
||||||
|
*
|
||||||
|
* @return bool Returns true on success or false on failure
|
||||||
|
*/
|
||||||
|
public function setCookie(SetCookie $cookie): bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove cookies currently held in the cookie jar.
|
||||||
|
*
|
||||||
|
* Invoking this method without arguments will empty the whole cookie jar.
|
||||||
|
* If given a $domain argument only cookies belonging to that domain will
|
||||||
|
* be removed. If given a $domain and $path argument, cookies belonging to
|
||||||
|
* the specified path within that domain are removed. If given all three
|
||||||
|
* arguments, then the cookie with the specified name, path and domain is
|
||||||
|
* removed.
|
||||||
|
*
|
||||||
|
* @param string|null $domain Clears cookies matching a domain
|
||||||
|
* @param string|null $path Clears cookies matching a domain and path
|
||||||
|
* @param string|null $name Clears cookies matching a domain, path, and name
|
||||||
|
*/
|
||||||
|
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discard all sessions cookies.
|
||||||
|
*
|
||||||
|
* Removes cookies that don't have an expire field or a have a discard
|
||||||
|
* field set to true. To be called when the user agent shuts down according
|
||||||
|
* to RFC 2965.
|
||||||
|
*/
|
||||||
|
public function clearSessionCookies(): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts the cookie jar to an array.
|
||||||
|
*/
|
||||||
|
public function toArray(): array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Cookie;
|
||||||
|
|
||||||
|
use GuzzleHttp\NonSerializableTrait;
|
||||||
|
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persists non-session cookies using a JSON formatted file
|
||||||
|
*/
|
||||||
|
class FileCookieJar extends CookieJar
|
||||||
|
{
|
||||||
|
use NonSerializableTrait;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var string filename
|
||||||
|
*/
|
||||||
|
private string $filename;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var bool Control whether to persist session cookies or not.
|
||||||
|
*/
|
||||||
|
private bool $storeSessionCookies;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var bool Whether to save the cookie jar on destruction.
|
||||||
|
*
|
||||||
|
* Disabled by __wakeup() to prevent FileCookieJar from being used as a
|
||||||
|
* PHP object injection file-write gadget when an application unserializes
|
||||||
|
* attacker-controlled data.
|
||||||
|
*/
|
||||||
|
private bool $autoSave = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new FileCookieJar object
|
||||||
|
*
|
||||||
|
* @param string $cookieFile File to store the cookie data
|
||||||
|
* @param bool $storeSessionCookies Set to true to store session cookies
|
||||||
|
* in the cookie jar.
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException if the file cannot be loaded or is invalid
|
||||||
|
*/
|
||||||
|
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
|
||||||
|
{
|
||||||
|
parent::__construct();
|
||||||
|
$this->filename = $cookieFile;
|
||||||
|
$this->storeSessionCookies = $storeSessionCookies;
|
||||||
|
|
||||||
|
if (\file_exists($cookieFile)) {
|
||||||
|
$this->load($cookieFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->autoSave = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves the file when shutting down
|
||||||
|
*/
|
||||||
|
public function __destruct()
|
||||||
|
{
|
||||||
|
if ($this->autoSave) {
|
||||||
|
$this->save($this->filename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disable automatic persistence after unserialization.
|
||||||
|
*/
|
||||||
|
public function __wakeup(): void
|
||||||
|
{
|
||||||
|
$this->autoSave = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __unserialize(array $data): void
|
||||||
|
{
|
||||||
|
$this->autoSave = false;
|
||||||
|
|
||||||
|
throw new \LogicException(static::class.' should never be unserialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves the cookies to a file.
|
||||||
|
*
|
||||||
|
* @param string $filename File to save
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException if the cookie data cannot be encoded or the
|
||||||
|
* file cannot be written
|
||||||
|
*/
|
||||||
|
public function save(string $filename): void
|
||||||
|
{
|
||||||
|
$json = [];
|
||||||
|
/** @var SetCookie $cookie */
|
||||||
|
foreach ($this as $cookie) {
|
||||||
|
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||||
|
$data = $cookie->toArray();
|
||||||
|
$data['HostOnly'] = $cookie->getHostOnly();
|
||||||
|
$json[] = $data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$jsonStr = \json_encode($json, \JSON_HEX_TAG | \JSON_THROW_ON_ERROR);
|
||||||
|
} catch (\JsonException $e) {
|
||||||
|
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
|
||||||
|
throw new \RuntimeException(\sprintf('Unable to save file %s', DiagnosticValue::escape($filename)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best-effort: restrict the cookie file to the owner so persisted
|
||||||
|
// cookies are not world-readable.
|
||||||
|
@\chmod($filename, 0600);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load cookies from a JSON formatted file.
|
||||||
|
*
|
||||||
|
* Old cookies are kept unless overwritten by newly loaded ones.
|
||||||
|
* Cookie records are constructed before any are passed to setCookie().
|
||||||
|
*
|
||||||
|
* @param string $filename Cookie file to load.
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException if the file cannot be loaded or is invalid
|
||||||
|
*/
|
||||||
|
public function load(string $filename): void
|
||||||
|
{
|
||||||
|
$json = \file_get_contents($filename);
|
||||||
|
if (false === $json) {
|
||||||
|
throw new \RuntimeException(\sprintf('Unable to load file %s', DiagnosticValue::escape($filename)));
|
||||||
|
}
|
||||||
|
if ($json === '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$message = \sprintf('Invalid cookie file: %s', DiagnosticValue::escape($filename));
|
||||||
|
|
||||||
|
try {
|
||||||
|
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
|
||||||
|
} catch (\JsonException $e) {
|
||||||
|
throw new \RuntimeException($message, 0, $e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
|
||||||
|
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
|
||||||
|
throw new \RuntimeException($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
$cookies = [];
|
||||||
|
foreach ($data as $cookie) {
|
||||||
|
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
|
||||||
|
throw new \RuntimeException($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cookies[] = new SetCookie($cookie);
|
||||||
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
throw new \RuntimeException($message, 0, $e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($cookies as $cookie) {
|
||||||
|
$this->setCookie($cookie);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Cookie;
|
||||||
|
|
||||||
|
use GuzzleHttp\NonSerializableTrait;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persists cookies in the client session
|
||||||
|
*/
|
||||||
|
class SessionCookieJar extends CookieJar
|
||||||
|
{
|
||||||
|
use NonSerializableTrait;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var string session key
|
||||||
|
*/
|
||||||
|
private string $sessionKey;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var bool Control whether to persist session cookies or not.
|
||||||
|
*/
|
||||||
|
private bool $storeSessionCookies;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var bool Whether to save the cookie jar on destruction.
|
||||||
|
*
|
||||||
|
* Disabled by __wakeup() to prevent SessionCookieJar from being used as a
|
||||||
|
* PHP object injection $_SESSION-write gadget when an application
|
||||||
|
* unserializes attacker-controlled data.
|
||||||
|
*/
|
||||||
|
private bool $autoSave = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new SessionCookieJar object
|
||||||
|
*
|
||||||
|
* @param string $sessionKey Session key name to store the cookie
|
||||||
|
* data in session
|
||||||
|
* @param bool $storeSessionCookies Set to true to store session cookies
|
||||||
|
* in the cookie jar.
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException if the session contains invalid cookie data
|
||||||
|
*/
|
||||||
|
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
|
||||||
|
{
|
||||||
|
parent::__construct();
|
||||||
|
$this->sessionKey = $sessionKey;
|
||||||
|
$this->storeSessionCookies = $storeSessionCookies;
|
||||||
|
$this->load();
|
||||||
|
$this->autoSave = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves cookies to session when shutting down
|
||||||
|
*/
|
||||||
|
public function __destruct()
|
||||||
|
{
|
||||||
|
if ($this->autoSave) {
|
||||||
|
$this->save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disable automatic persistence after unserialization.
|
||||||
|
*/
|
||||||
|
public function __wakeup(): void
|
||||||
|
{
|
||||||
|
$this->autoSave = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __unserialize(array $data): void
|
||||||
|
{
|
||||||
|
$this->autoSave = false;
|
||||||
|
|
||||||
|
throw new \LogicException(static::class.' should never be unserialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save cookies to the client session.
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException if the cookie data cannot be encoded
|
||||||
|
*/
|
||||||
|
public function save(): void
|
||||||
|
{
|
||||||
|
$json = [];
|
||||||
|
/** @var SetCookie $cookie */
|
||||||
|
foreach ($this as $cookie) {
|
||||||
|
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||||
|
$data = $cookie->toArray();
|
||||||
|
$data['HostOnly'] = $cookie->getHostOnly();
|
||||||
|
$json[] = $data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$json = \json_encode($json, \JSON_THROW_ON_ERROR);
|
||||||
|
} catch (\JsonException $e) {
|
||||||
|
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
|
||||||
|
}
|
||||||
|
|
||||||
|
$_SESSION[$this->sessionKey] = $json;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load cookies from the client session.
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException if the session contains invalid cookie data
|
||||||
|
*/
|
||||||
|
protected function load(): void
|
||||||
|
{
|
||||||
|
if (!isset($_SESSION[$this->sessionKey])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$message = 'Invalid cookie data';
|
||||||
|
$json = $_SESSION[$this->sessionKey];
|
||||||
|
if (!\is_string($json)) {
|
||||||
|
throw new \RuntimeException($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
|
||||||
|
} catch (\JsonException $e) {
|
||||||
|
throw new \RuntimeException($message, 0, $e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
|
||||||
|
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
|
||||||
|
throw new \RuntimeException($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
$cookies = [];
|
||||||
|
foreach ($data as $cookie) {
|
||||||
|
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
|
||||||
|
throw new \RuntimeException($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cookies[] = new SetCookie($cookie);
|
||||||
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
throw new \RuntimeException($message, 0, $e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($cookies as $cookie) {
|
||||||
|
$this->setCookie($cookie);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+601
@@ -0,0 +1,601 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Cookie;
|
||||||
|
|
||||||
|
use GuzzleHttp\HostIdentity;
|
||||||
|
use GuzzleHttp\Psr7;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set-Cookie object
|
||||||
|
*/
|
||||||
|
class SetCookie
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
private const DEFAULTS = [
|
||||||
|
'Name' => null,
|
||||||
|
'Value' => null,
|
||||||
|
'Domain' => null,
|
||||||
|
'Path' => '/',
|
||||||
|
'Max-Age' => null,
|
||||||
|
'Expires' => null,
|
||||||
|
'Secure' => false,
|
||||||
|
'Discard' => false,
|
||||||
|
'HttpOnly' => false,
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array Cookie data
|
||||||
|
*/
|
||||||
|
private array $data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var bool Whether this cookie was set without a Domain attribute.
|
||||||
|
*/
|
||||||
|
private bool $hostOnly = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new SetCookie object from a string.
|
||||||
|
*
|
||||||
|
* @param string $cookie Set-Cookie header string
|
||||||
|
*/
|
||||||
|
public static function fromString(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
string $cookie
|
||||||
|
): self {
|
||||||
|
// Create the default return array
|
||||||
|
$data = self::DEFAULTS;
|
||||||
|
// Explode the cookie string using a series of semicolons
|
||||||
|
$pieces = \array_filter(\array_map(static function (string $piece): string {
|
||||||
|
return \trim($piece, " \t");
|
||||||
|
}, \explode(';', $cookie)));
|
||||||
|
// The name of the cookie (first kvp) must exist and include an equal sign.
|
||||||
|
if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
|
||||||
|
return new self($data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the cookie pieces into the parsed data array
|
||||||
|
foreach ($pieces as $part) {
|
||||||
|
$cookieParts = \explode('=', $part, 2);
|
||||||
|
$key = \trim($cookieParts[0], " \t");
|
||||||
|
$value = isset($cookieParts[1])
|
||||||
|
? \trim($cookieParts[1], " \t")
|
||||||
|
: true;
|
||||||
|
|
||||||
|
// Only check for non-cookies when cookies have been found
|
||||||
|
if (!isset($data['Name'])) {
|
||||||
|
$data['Name'] = $key;
|
||||||
|
$data['Value'] = $value;
|
||||||
|
} else {
|
||||||
|
foreach (\array_keys(self::DEFAULTS) as $search) {
|
||||||
|
if (Psr7\Utils::caselessEquals($search, $key)) {
|
||||||
|
if ($search === 'Max-Age') {
|
||||||
|
if (\is_string($value) && \preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
|
||||||
|
$maxAge = self::parseNumericInteger($value);
|
||||||
|
if ($maxAge !== null) {
|
||||||
|
$data[$search] = $maxAge;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
|
||||||
|
if ($value) {
|
||||||
|
$data[$search] = true;
|
||||||
|
}
|
||||||
|
} elseif (\is_string($value)) {
|
||||||
|
$data[$search] = $value;
|
||||||
|
}
|
||||||
|
continue 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$data[$key] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Max-Age takes precedence over Expires, RFC 6265 section 5.3
|
||||||
|
if ($data['Max-Age'] !== null) {
|
||||||
|
$data['Expires'] = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new self($data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $data Array of cookie data provided by a Cookie parser
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $data = []
|
||||||
|
) {
|
||||||
|
$this->data = self::DEFAULTS;
|
||||||
|
self::validateFieldTypes($data);
|
||||||
|
|
||||||
|
if (\array_key_exists('HostOnly', $data)) {
|
||||||
|
$this->setHostOnly($data['HostOnly']);
|
||||||
|
unset($data['HostOnly']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Name'])) {
|
||||||
|
$this->setName($data['Name']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Value'])) {
|
||||||
|
$this->setValue($data['Value']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Domain'])) {
|
||||||
|
$this->setDomain($data['Domain']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Path'])) {
|
||||||
|
$this->setPath($data['Path']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Max-Age'])) {
|
||||||
|
$this->setMaxAge($data['Max-Age']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Expires'])) {
|
||||||
|
$this->setExpires($data['Expires']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Secure'])) {
|
||||||
|
$this->setSecure($data['Secure']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Discard'])) {
|
||||||
|
$this->setDiscard($data['Discard']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['HttpOnly'])) {
|
||||||
|
$this->setHttpOnly($data['HttpOnly']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the remaining values that don't have extra validation logic
|
||||||
|
foreach (array_diff(array_keys($data), array_keys(self::DEFAULTS)) as $key) {
|
||||||
|
$this->data[$key] = $data[$key];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Derive Expires from Max-Age unless the data already carries one
|
||||||
|
$maxAge = $this->getMaxAge();
|
||||||
|
if ($maxAge !== null && $this->getExpires() === null) {
|
||||||
|
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __toString(): string
|
||||||
|
{
|
||||||
|
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
|
||||||
|
foreach ($this->data as $k => $v) {
|
||||||
|
if ($k === 'Domain' && $this->getHostOnly()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
|
||||||
|
if ($k === 'Expires') {
|
||||||
|
$str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
|
||||||
|
} else {
|
||||||
|
$str .= ($v === true ? $k : "{$k}={$v}").'; ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return \rtrim($str, '; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
$data = $this->data;
|
||||||
|
if ($this->getHostOnly()) {
|
||||||
|
$data['HostOnly'] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the cookie name.
|
||||||
|
*/
|
||||||
|
public function getName(): ?string
|
||||||
|
{
|
||||||
|
return $this->data['Name'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the cookie name.
|
||||||
|
*
|
||||||
|
* @param string $name Cookie name
|
||||||
|
*/
|
||||||
|
public function setName(string $name): void
|
||||||
|
{
|
||||||
|
$this->data['Name'] = $name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the cookie value.
|
||||||
|
*/
|
||||||
|
public function getValue(): ?string
|
||||||
|
{
|
||||||
|
return $this->data['Value'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the cookie value.
|
||||||
|
*
|
||||||
|
* @param string $value Cookie value
|
||||||
|
*/
|
||||||
|
public function setValue(string $value): void
|
||||||
|
{
|
||||||
|
$this->data['Value'] = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the domain.
|
||||||
|
*/
|
||||||
|
public function getDomain(): ?string
|
||||||
|
{
|
||||||
|
return $this->data['Domain'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the domain of the cookie.
|
||||||
|
*
|
||||||
|
* @param string|null $domain Domain of the cookie
|
||||||
|
*/
|
||||||
|
public function setDomain(?string $domain): void
|
||||||
|
{
|
||||||
|
$this->data['Domain'] = null === $domain ? null : self::normalizeDomain($domain);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get whether this cookie is scoped to the origin host only.
|
||||||
|
*/
|
||||||
|
public function getHostOnly(): bool
|
||||||
|
{
|
||||||
|
return $this->hostOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set whether this cookie is scoped to the origin host only.
|
||||||
|
*
|
||||||
|
* @param bool $hostOnly Set to true for host-only cookies
|
||||||
|
*/
|
||||||
|
public function setHostOnly(bool $hostOnly): void
|
||||||
|
{
|
||||||
|
$this->hostOnly = $hostOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the path.
|
||||||
|
*/
|
||||||
|
public function getPath(): string
|
||||||
|
{
|
||||||
|
return $this->data['Path'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the path of the cookie.
|
||||||
|
*
|
||||||
|
* @param string $path Path of the cookie
|
||||||
|
*/
|
||||||
|
public function setPath(string $path): void
|
||||||
|
{
|
||||||
|
$this->data['Path'] = $path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maximum lifetime of the cookie in seconds.
|
||||||
|
*/
|
||||||
|
public function getMaxAge(): ?int
|
||||||
|
{
|
||||||
|
return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the max-age of the cookie.
|
||||||
|
*
|
||||||
|
* @param int|null $maxAge Max age of the cookie in seconds
|
||||||
|
*/
|
||||||
|
public function setMaxAge(?int $maxAge): void
|
||||||
|
{
|
||||||
|
$this->data['Max-Age'] = $maxAge;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The UNIX timestamp when the cookie Expires.
|
||||||
|
*/
|
||||||
|
public function getExpires(): ?int
|
||||||
|
{
|
||||||
|
return $this->data['Expires'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the unix timestamp for which the cookie will expire.
|
||||||
|
*
|
||||||
|
* @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
|
||||||
|
*/
|
||||||
|
public function setExpires($timestamp): void
|
||||||
|
{
|
||||||
|
if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
|
||||||
|
// TODO: Move this to the parameter definition in 9.0.
|
||||||
|
throw new \TypeError(__METHOD__.'(): Argument #1 ($timestamp) must be of type int|string|null');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($timestamp === null) {
|
||||||
|
$this->data['Expires'] = null;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\is_string($timestamp)) {
|
||||||
|
if (\is_numeric($timestamp)) {
|
||||||
|
$this->data['Expires'] = self::parseNumericInteger($timestamp);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} elseif (\is_int($timestamp)) {
|
||||||
|
$this->data['Expires'] = $timestamp;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$expires = \strtotime($timestamp);
|
||||||
|
$this->data['Expires'] = $expires === false ? null : $expires;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get whether or not this is a secure cookie.
|
||||||
|
*/
|
||||||
|
public function getSecure(): bool
|
||||||
|
{
|
||||||
|
return $this->data['Secure'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set whether or not the cookie is secure.
|
||||||
|
*
|
||||||
|
* @param bool $secure Set to true or false if secure
|
||||||
|
*/
|
||||||
|
public function setSecure(bool $secure): void
|
||||||
|
{
|
||||||
|
$this->data['Secure'] = $secure;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get whether or not this is a session cookie.
|
||||||
|
*/
|
||||||
|
public function getDiscard(): bool
|
||||||
|
{
|
||||||
|
return $this->data['Discard'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set whether or not this is a session cookie.
|
||||||
|
*
|
||||||
|
* @param bool $discard Set to true or false if this is a session cookie
|
||||||
|
*/
|
||||||
|
public function setDiscard(bool $discard): void
|
||||||
|
{
|
||||||
|
$this->data['Discard'] = $discard;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get whether or not this is an HTTP only cookie.
|
||||||
|
*/
|
||||||
|
public function getHttpOnly(): bool
|
||||||
|
{
|
||||||
|
return $this->data['HttpOnly'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set whether or not this is an HTTP only cookie.
|
||||||
|
*
|
||||||
|
* @param bool $httpOnly Set to true or false if this is HTTP only
|
||||||
|
*/
|
||||||
|
public function setHttpOnly(bool $httpOnly): void
|
||||||
|
{
|
||||||
|
$this->data['HttpOnly'] = $httpOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the cookie matches a path value.
|
||||||
|
*
|
||||||
|
* A request-path path-matches a given cookie-path if at least one of
|
||||||
|
* the following conditions holds:
|
||||||
|
*
|
||||||
|
* - The cookie-path and the request-path are identical.
|
||||||
|
* - The cookie-path is a prefix of the request-path, and the last
|
||||||
|
* character of the cookie-path is %x2F ("/").
|
||||||
|
* - The cookie-path is a prefix of the request-path, and the first
|
||||||
|
* character of the request-path that is not included in the cookie-
|
||||||
|
* path is a %x2F ("/") character.
|
||||||
|
*
|
||||||
|
* @param string $requestPath Path to check against
|
||||||
|
*/
|
||||||
|
public function matchesPath(string $requestPath): bool
|
||||||
|
{
|
||||||
|
$cookiePath = $this->getPath();
|
||||||
|
|
||||||
|
// Match on exact matches or when path is the default empty "/"
|
||||||
|
if ($cookiePath === '/' || $cookiePath === $requestPath) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure that the cookie-path is a prefix of the request path.
|
||||||
|
if (0 !== \strpos($requestPath, $cookiePath)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match if the last character of the cookie-path is "/"
|
||||||
|
if (\substr($cookiePath, -1, 1) === '/') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match if the first character not included in cookie path is "/"
|
||||||
|
return \substr($requestPath, \strlen($cookiePath), 1) === '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the cookie matches a domain value.
|
||||||
|
*
|
||||||
|
* @param string $domain Domain to check against
|
||||||
|
*/
|
||||||
|
public function matchesDomain(string $domain): bool
|
||||||
|
{
|
||||||
|
$cookieDomain = $this->getDomain();
|
||||||
|
if (null === $cookieDomain || $cookieDomain === '') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->getHostOnly()) {
|
||||||
|
return HostIdentity::canonicalCookieDomain($domain) === HostIdentity::canonicalCookieDomain($cookieDomain);
|
||||||
|
}
|
||||||
|
|
||||||
|
return HostIdentity::cookieDomainMatches($domain, $cookieDomain);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the cookie is expired.
|
||||||
|
*/
|
||||||
|
public function isExpired(): bool
|
||||||
|
{
|
||||||
|
return $this->getExpires() !== null && \time() > $this->getExpires();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the cookie is valid according to RFC 6265.
|
||||||
|
*
|
||||||
|
* @return string|true Returns true if valid or an error message if invalid
|
||||||
|
*/
|
||||||
|
public function validate()
|
||||||
|
{
|
||||||
|
$name = $this->getName();
|
||||||
|
if ($name === null || $name === '') {
|
||||||
|
return 'The cookie name must not be empty';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if any of the invalid characters are present in the cookie name
|
||||||
|
if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 0) {
|
||||||
|
return 'Cookie name must not contain invalid characters: ASCII '
|
||||||
|
.'Control characters (0-31;127), space, tab and the '
|
||||||
|
.'following characters: ()<>@,;:\"/?={}';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Value must not be null. 0 and empty string are valid. Empty strings
|
||||||
|
// are technically against RFC 6265, but known to happen in the wild.
|
||||||
|
$value = $this->getValue();
|
||||||
|
if ($value === null) {
|
||||||
|
return 'The cookie value must not be empty';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Domains must not be empty, but may be omitted. "0" is not a valid
|
||||||
|
// internet domain, but may be used as server name in a private network.
|
||||||
|
$domain = $this->getDomain();
|
||||||
|
if ($domain === '' || ($domain !== null && \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.') === '')) {
|
||||||
|
return 'The cookie domain must not be empty';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->getHostOnly() && $domain === null) {
|
||||||
|
return 'Host-only cookies must have a domain';
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function normalizeDomain(string $domain): string
|
||||||
|
{
|
||||||
|
$domain = Psr7\Utils::asciiToLower($domain);
|
||||||
|
|
||||||
|
// Treat trailing-dot domains as host-only, but keep pure-dot domains invalid.
|
||||||
|
if ($domain !== '' && \substr($domain, -1) === '.' && \trim($domain, '.') !== '') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($domain !== '' && $domain !== '.' && $domain[0] === '.') {
|
||||||
|
$domain = \substr_replace($domain, '', 0, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return HostIdentity::canonicalCookieDomain($domain);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function maxAgeToExpires(int $maxAge, int $now): int
|
||||||
|
{
|
||||||
|
if ($maxAge <= 0) {
|
||||||
|
return $now - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clamp absurd Max-Age values so addition cannot promote to float
|
||||||
|
if ($maxAge > \PHP_INT_MAX - $now) {
|
||||||
|
return \PHP_INT_MAX;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $now + $maxAge;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function parseNumericInteger(string $value): ?int
|
||||||
|
{
|
||||||
|
if (!\is_numeric($value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
|
||||||
|
$negative = $value[0] === '-';
|
||||||
|
$digits = \ltrim($value, '+-');
|
||||||
|
$digits = \ltrim($digits, '0');
|
||||||
|
$digits = $digits === '' ? '0' : $digits;
|
||||||
|
$limit = $negative ? \substr((string) \PHP_INT_MIN, 1) : (string) \PHP_INT_MAX;
|
||||||
|
|
||||||
|
if (\strlen($digits) > \strlen($limit) || (\strlen($digits) === \strlen($limit) && \strcmp($digits, $limit) > 0)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) ($negative ? '-'.$digits : $digits);
|
||||||
|
}
|
||||||
|
|
||||||
|
$number = (float) $value;
|
||||||
|
if (!\is_finite($number) || $number < \PHP_INT_MIN || $number > \PHP_INT_MAX) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\PHP_INT_SIZE === 8 && ($number <= (float) \PHP_INT_MIN || $number >= (float) \PHP_INT_MAX)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) $number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mixed[] $data
|
||||||
|
*/
|
||||||
|
private static function validateFieldTypes(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
array $data
|
||||||
|
): void {
|
||||||
|
foreach (['Name', 'Value', 'Domain', 'Path'] as $field) {
|
||||||
|
if (isset($data[$field]) && !\is_string($data[$field])) {
|
||||||
|
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a string', $field));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Max-Age']) && !\is_int($data['Max-Age'])) {
|
||||||
|
throw new \InvalidArgumentException('Cookie field "Max-Age" must be an integer');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['Expires']) && !\is_int($data['Expires']) && !\is_string($data['Expires'])) {
|
||||||
|
throw new \InvalidArgumentException('Cookie field "Expires" must be an integer or string');
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (['Secure', 'Discard', 'HttpOnly'] as $field) {
|
||||||
|
if (isset($data[$field]) && !\is_bool($data[$field])) {
|
||||||
|
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a boolean', $field));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\array_key_exists('HostOnly', $data) && !\is_bool($data['HostOnly'])) {
|
||||||
|
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+33
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads configuration from the process environment.
|
||||||
|
*
|
||||||
|
* Intentionally separate from Handler\ProxyEnv, which has different
|
||||||
|
* lookup semantics.
|
||||||
|
*
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
final class Env
|
||||||
|
{
|
||||||
|
private function __construct()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function get(string $name): ?string
|
||||||
|
{
|
||||||
|
if (isset($_SERVER[$name])) {
|
||||||
|
return (string) $_SERVER[$name];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) {
|
||||||
|
return (string) $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown for HTTP responses with 4xx or 5xx status codes.
|
||||||
|
*/
|
||||||
|
class BadResponseException extends ResponseException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown for HTTP responses with 4xx status codes.
|
||||||
|
*/
|
||||||
|
class ClientException extends BadResponseException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when connection establishment fails.
|
||||||
|
*/
|
||||||
|
class ConnectException extends NetworkException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when connection establishment exceeds the time limit.
|
||||||
|
*/
|
||||||
|
class ConnectTimeoutException extends ConnectException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
use Psr\Http\Client\ClientExceptionInterface;
|
||||||
|
|
||||||
|
interface GuzzleException extends ClientExceptionInterface
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when a handler is closed before a transfer completes.
|
||||||
|
*/
|
||||||
|
class HandlerClosedException extends TransferException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when an invalid argument is supplied to Guzzle.
|
||||||
|
*/
|
||||||
|
final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
use Psr\Http\Client\NetworkExceptionInterface;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base exception for transfer failures without a response.
|
||||||
|
*/
|
||||||
|
class NetworkException extends TransferException implements NetworkExceptionInterface
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
string $message,
|
||||||
|
RequestInterface $request,
|
||||||
|
?\Throwable $previous = null
|
||||||
|
) {
|
||||||
|
parent::__construct($message, $request, 0, $previous);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when a transfer times out before response headers are
|
||||||
|
* received.
|
||||||
|
*/
|
||||||
|
class NetworkTimeoutException extends NetworkException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
use GuzzleHttp\BodySummarizer;
|
||||||
|
use GuzzleHttp\BodySummarizerInterface;
|
||||||
|
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||||
|
use Psr\Http\Client\RequestExceptionInterface;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base exception for request failures associated with a request.
|
||||||
|
*/
|
||||||
|
class RequestException extends TransferException implements RequestExceptionInterface
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
string $message,
|
||||||
|
RequestInterface $request,
|
||||||
|
int $code = 0,
|
||||||
|
?\Throwable $previous = null
|
||||||
|
) {
|
||||||
|
parent::__construct($message, $request, $code, $previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory method to create a new exception with a normalized error message
|
||||||
|
*
|
||||||
|
* @param RequestInterface $request Request sent
|
||||||
|
* @param ResponseInterface|null $response Response received, if any
|
||||||
|
* @param \Throwable|null $previous Previous exception
|
||||||
|
* @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer
|
||||||
|
*/
|
||||||
|
public static function create(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
?ResponseInterface $response = null,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
?\Throwable $previous = null,
|
||||||
|
?BodySummarizerInterface $bodySummarizer = null
|
||||||
|
): self {
|
||||||
|
if (!$response) {
|
||||||
|
return new self(
|
||||||
|
'Error completing request',
|
||||||
|
$request,
|
||||||
|
0,
|
||||||
|
$previous
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$level = (int) \floor($response->getStatusCode() / 100);
|
||||||
|
if ($level === 4) {
|
||||||
|
$label = 'Client error';
|
||||||
|
} elseif ($level === 5) {
|
||||||
|
$label = 'Server error';
|
||||||
|
} else {
|
||||||
|
$label = 'Unsuccessful request';
|
||||||
|
}
|
||||||
|
|
||||||
|
$uri = \GuzzleHttp\Psr7\UriRedactor::redactUriForMessage($request->getUri());
|
||||||
|
|
||||||
|
// Client error: `GET /` resulted in a `404 Not Found` response: <html> ... (truncated)
|
||||||
|
$message = \sprintf(
|
||||||
|
'%s: `%s %s` resulted in a `%s %s` response',
|
||||||
|
$label,
|
||||||
|
DiagnosticValue::escape($request->getMethod()),
|
||||||
|
$uri,
|
||||||
|
$response->getStatusCode(),
|
||||||
|
DiagnosticValue::escape($response->getReasonPhrase())
|
||||||
|
);
|
||||||
|
|
||||||
|
$summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response);
|
||||||
|
|
||||||
|
if ($summary !== null) {
|
||||||
|
$message .= \sprintf(': %s', DiagnosticValue::escape($summary));
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($level === 4) {
|
||||||
|
return new ClientException($message, $request, $response, $previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($level === 5) {
|
||||||
|
return new ServerException($message, $request, $response, $previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ResponseException($message, $request, $response, $previous);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when a request fails after response headers are received.
|
||||||
|
*/
|
||||||
|
class ResponseException extends RequestException
|
||||||
|
{
|
||||||
|
private ResponseInterface $response;
|
||||||
|
|
||||||
|
final public function __construct(
|
||||||
|
string $message,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
RequestInterface $request,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
?\Throwable $previous = null
|
||||||
|
) {
|
||||||
|
parent::__construct($message, $request, $response->getStatusCode(), $previous);
|
||||||
|
$this->response = $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a new exception instance with an updated response.
|
||||||
|
*
|
||||||
|
* @param \Throwable|null $previous Previous exception, or the current
|
||||||
|
* previous exception when omitted.
|
||||||
|
*
|
||||||
|
* @return static
|
||||||
|
*/
|
||||||
|
public function withResponse(
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
ResponseInterface $response,
|
||||||
|
#[\SensitiveParameter]
|
||||||
|
?\Throwable $previous = null
|
||||||
|
): self {
|
||||||
|
if ($response->getStatusCode() !== $this->response->getStatusCode()) {
|
||||||
|
throw new InvalidArgumentException('Cannot replace response with a different status code.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return new static(
|
||||||
|
$this->getMessage(),
|
||||||
|
$this->getRequest(),
|
||||||
|
$response,
|
||||||
|
$previous ?? $this->getPrevious()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the associated response.
|
||||||
|
*/
|
||||||
|
public function getResponse(): ResponseInterface
|
||||||
|
{
|
||||||
|
return $this->response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when a transfer times out after response headers are
|
||||||
|
* received.
|
||||||
|
*/
|
||||||
|
class ResponseTimeoutException extends ResponseTransferException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when a response transfer fails after response headers are
|
||||||
|
* received.
|
||||||
|
*/
|
||||||
|
class ResponseTransferException extends ResponseException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown for HTTP responses with 5xx status codes.
|
||||||
|
*/
|
||||||
|
class ServerException extends BadResponseException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception thrown when redirect middleware reaches the redirect limit.
|
||||||
|
*/
|
||||||
|
class TooManyRedirectsException extends ResponseException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Exception;
|
||||||
|
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base exception for transfer failures.
|
||||||
|
*/
|
||||||
|
class TransferException extends \RuntimeException implements GuzzleException
|
||||||
|
{
|
||||||
|
private RequestInterface $request;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
string $message,
|
||||||
|
RequestInterface $request,
|
||||||
|
int $code = 0,
|
||||||
|
?\Throwable $previous = null
|
||||||
|
) {
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
$this->request = $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the request that caused the exception.
|
||||||
|
*/
|
||||||
|
public function getRequest(): RequestInterface
|
||||||
|
{
|
||||||
|
return $this->request;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Handler;
|
||||||
|
|
||||||
|
use GuzzleHttp\NonSerializableTrait;
|
||||||
|
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||||
|
use GuzzleHttp\Psr7\StreamWrapper;
|
||||||
|
use GuzzleHttp\Psr7\Utils;
|
||||||
|
use Psr\Http\Message\StreamInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes the chunked transfer coding of a response body read from the
|
||||||
|
* unfiltered transport stream, with the framing rules libcurl applies.
|
||||||
|
*
|
||||||
|
* Each read returns the decoded bytes that are already available, waiting on
|
||||||
|
* the transport only when there are none, so the transport's idle timeout
|
||||||
|
* governs every wait. The body ends as soon as the last chunk and trailer
|
||||||
|
* section have been decoded, without another transport read. A body that ends
|
||||||
|
* early or has malformed framing fails the read once the bytes decoded before
|
||||||
|
* the fault have been returned, and every later read fails the same way.
|
||||||
|
*
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
final class ChunkedBodyStream implements StreamInterface
|
||||||
|
{
|
||||||
|
use NonSerializableTrait;
|
||||||
|
use StreamDecoratorTrait;
|
||||||
|
|
||||||
|
private const READ_SIZE = 8192;
|
||||||
|
|
||||||
|
private const MAX_SIZE_DIGITS = 17;
|
||||||
|
|
||||||
|
// libcurl's trailer line and header section limits.
|
||||||
|
private const MAX_TRAILER_LINE_LENGTH = 4093;
|
||||||
|
|
||||||
|
private const MAX_TRAILER_SECTION_LENGTH = 307200;
|
||||||
|
|
||||||
|
private const SIZE = 0;
|
||||||
|
|
||||||
|
private const SIZE_LINE = 1;
|
||||||
|
|
||||||
|
private const DATA = 2;
|
||||||
|
|
||||||
|
private const DATA_END = 3;
|
||||||
|
|
||||||
|
private const TRAILER = 4;
|
||||||
|
|
||||||
|
private const TRAILER_CR = 5;
|
||||||
|
|
||||||
|
private const FINAL_CR = 6;
|
||||||
|
|
||||||
|
private const DONE = 7;
|
||||||
|
|
||||||
|
private StreamInterface $stream;
|
||||||
|
|
||||||
|
private string $buffer = '';
|
||||||
|
|
||||||
|
private int $offset = 0;
|
||||||
|
|
||||||
|
private int $state = self::SIZE;
|
||||||
|
|
||||||
|
private string $digits = '';
|
||||||
|
|
||||||
|
private int $remaining = 0;
|
||||||
|
|
||||||
|
private string $line = '';
|
||||||
|
|
||||||
|
private int $trailerLength = 0;
|
||||||
|
|
||||||
|
private int $position = 0;
|
||||||
|
|
||||||
|
private ?\RuntimeException $failure = null;
|
||||||
|
|
||||||
|
private bool $detachable = true;
|
||||||
|
|
||||||
|
public function __construct(StreamInterface $stream)
|
||||||
|
{
|
||||||
|
$this->stream = $stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __clone()
|
||||||
|
{
|
||||||
|
// A clone shares the transport, so detaching it would break this body.
|
||||||
|
$this->detachable = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function read(int $length): string
|
||||||
|
{
|
||||||
|
if ($this->failure !== null) {
|
||||||
|
throw $this->failure;
|
||||||
|
}
|
||||||
|
if ($length < 0) {
|
||||||
|
throw new \RuntimeException('Length parameter cannot be negative');
|
||||||
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
$data = $this->decode($length);
|
||||||
|
} while ($data === '' && $length > 0 && !$this->eof() && $this->fill());
|
||||||
|
|
||||||
|
$this->position = TransferByteCounter::add(
|
||||||
|
$this->position,
|
||||||
|
\strlen($data),
|
||||||
|
'Response body exceeds the maximum integer size supported on this platform'
|
||||||
|
);
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function eof(): bool
|
||||||
|
{
|
||||||
|
return $this->state === self::DONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function getMetadata(?string $key = null)
|
||||||
|
{
|
||||||
|
// A failed body has not timed out, whatever a stale flag on the
|
||||||
|
// transport says, so callers report the failure itself.
|
||||||
|
if ($this->failure !== null && $key === 'timed_out') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$metadata = $this->stream->getMetadata($key);
|
||||||
|
if ($this->failure !== null && $key === null && \is_array($metadata)) {
|
||||||
|
$metadata['timed_out'] = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $metadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function tell(): int
|
||||||
|
{
|
||||||
|
return $this->position;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getSize(): ?int
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isSeekable(): bool
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||||
|
{
|
||||||
|
throw new \RuntimeException('Cannot seek a chunked response body');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isWritable(): bool
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function write(string $string): int
|
||||||
|
{
|
||||||
|
throw new \RuntimeException('Cannot write to a chunked response body');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function close(): void
|
||||||
|
{
|
||||||
|
$this->buffer = '';
|
||||||
|
$this->offset = 0;
|
||||||
|
$this->detachable = false;
|
||||||
|
$this->stream->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function detach()
|
||||||
|
{
|
||||||
|
if (!$this->detachable) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->state === self::DONE) {
|
||||||
|
return $this->stream->detach();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->buffer === '' && $this->failure === null) {
|
||||||
|
$resource = $this->stream->detach();
|
||||||
|
if (\is_resource($resource)) {
|
||||||
|
// Nothing has been decoded yet, so PHP's filter can take over.
|
||||||
|
\stream_filter_append($resource, 'dechunk', \STREAM_FILTER_READ);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resource;
|
||||||
|
}
|
||||||
|
|
||||||
|
// PHP's filter cannot resume part way through a chunk, so hand the
|
||||||
|
// decoder over to a resource that keeps decoding the rest of the body.
|
||||||
|
$decoder = clone $this;
|
||||||
|
$this->buffer = '';
|
||||||
|
$this->offset = 0;
|
||||||
|
$this->detachable = false;
|
||||||
|
$this->stream = Utils::streamFor('');
|
||||||
|
$this->stream->detach();
|
||||||
|
|
||||||
|
return StreamWrapper::getResource($decoder);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Appends what the transport has available to the buffer, waiting for at
|
||||||
|
* least one byte.
|
||||||
|
*/
|
||||||
|
private function fill(): bool
|
||||||
|
{
|
||||||
|
$data = $this->stream->read(self::READ_SIZE);
|
||||||
|
if ($data === '') {
|
||||||
|
if (!$this->stream->eof()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->failure = new \RuntimeException('Response body ended before the chunked body was complete');
|
||||||
|
|
||||||
|
throw $this->failure;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->buffer = \substr($this->buffer, $this->offset).$data;
|
||||||
|
$this->offset = 0;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes up to $length bytes from the buffer, and any framing after them,
|
||||||
|
* so the end of the body is noticed without another transport read.
|
||||||
|
*/
|
||||||
|
private function decode(int $length): string
|
||||||
|
{
|
||||||
|
$data = '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
while ($this->offset < \strlen($this->buffer) && $this->state !== self::DONE) {
|
||||||
|
if ($this->state === self::DATA) {
|
||||||
|
$take = \min($this->remaining, $length - \strlen($data), \strlen($this->buffer) - $this->offset);
|
||||||
|
if ($take === 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$data .= \substr($this->buffer, $this->offset, $take);
|
||||||
|
$this->offset += $take;
|
||||||
|
$this->remaining -= $take;
|
||||||
|
if ($this->remaining === 0) {
|
||||||
|
$this->state = self::DATA_END;
|
||||||
|
}
|
||||||
|
} elseif ($this->state === self::SIZE) {
|
||||||
|
$chunks = $this->digits === '' ? $this->decodeChunks($length - \strlen($data)) : null;
|
||||||
|
if ($chunks === null) {
|
||||||
|
$this->decodeSize();
|
||||||
|
} else {
|
||||||
|
$data .= $chunks;
|
||||||
|
}
|
||||||
|
} elseif ($this->state === self::SIZE_LINE) {
|
||||||
|
$this->skipSizeLine();
|
||||||
|
} elseif ($this->state === self::DATA_END) {
|
||||||
|
$this->decodeDataEnd();
|
||||||
|
} else {
|
||||||
|
$this->decodeTrailer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (\RuntimeException $e) {
|
||||||
|
$this->failure = $e;
|
||||||
|
if ($data === '') {
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes buffered chunks in bulk, up to $length bytes, and leaves the
|
||||||
|
* state machine at the first chunk that needs more care. Returns null when
|
||||||
|
* it consumes nothing.
|
||||||
|
*/
|
||||||
|
private function decodeChunks(int $length): ?string
|
||||||
|
{
|
||||||
|
$buffer = $this->buffer;
|
||||||
|
$end = \strlen($buffer);
|
||||||
|
$offset = $this->offset;
|
||||||
|
$data = '';
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
// Up to seven digits keep the size an int on every platform.
|
||||||
|
$digits = \strspn($buffer, '0123456789abcdefABCDEF', $offset, 8);
|
||||||
|
if ($digits === 0 || $digits === 8) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$lineEnd = \strpos($buffer, "\n", $offset + $digits);
|
||||||
|
if ($lineEnd === false) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$size = (int) \hexdec(\substr($buffer, $offset, $digits));
|
||||||
|
$offset = $lineEnd + 1;
|
||||||
|
if ($size === 0) {
|
||||||
|
$this->state = self::TRAILER;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if ($size > $length || $offset + $size > $end) {
|
||||||
|
$this->remaining = $size;
|
||||||
|
$this->state = self::DATA;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data .= \substr($buffer, $offset, $size);
|
||||||
|
$length -= $size;
|
||||||
|
$offset += $size;
|
||||||
|
if ($offset + 1 < $end && $buffer[$offset] === "\r" && $buffer[$offset + 1] === "\n") {
|
||||||
|
$offset += 2;
|
||||||
|
} elseif ($offset < $end && $buffer[$offset] === "\n") {
|
||||||
|
++$offset;
|
||||||
|
} else {
|
||||||
|
$this->state = self::DATA_END;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($offset === $this->offset) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->offset = $offset;
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function decodeSize(): void
|
||||||
|
{
|
||||||
|
$count = \strspn($this->buffer, '0123456789abcdefABCDEF', $this->offset);
|
||||||
|
$this->digits .= \substr($this->buffer, $this->offset, $count);
|
||||||
|
$this->offset += $count;
|
||||||
|
if (\strlen($this->digits) > self::MAX_SIZE_DIGITS) {
|
||||||
|
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||||
|
}
|
||||||
|
if ($this->offset === \strlen($this->buffer)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ($this->digits === '') {
|
||||||
|
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||||
|
}
|
||||||
|
|
||||||
|
$significant = \ltrim($this->digits, '0');
|
||||||
|
if (\strlen($significant) > 16 || (\strlen($significant) === 16 && $significant[0] > '7')) {
|
||||||
|
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||||
|
}
|
||||||
|
|
||||||
|
$size = \hexdec($this->digits);
|
||||||
|
if (!\is_int($size)) {
|
||||||
|
throw new \OverflowException('Chunk size exceeds the maximum integer size supported on this platform');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->digits = '';
|
||||||
|
$this->remaining = $size;
|
||||||
|
$this->state = self::SIZE_LINE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function skipSizeLine(): void
|
||||||
|
{
|
||||||
|
// Chunk extensions, and anything else up to the line feed, are ignored
|
||||||
|
// the way libcurl ignores them.
|
||||||
|
$end = \strpos($this->buffer, "\n", $this->offset);
|
||||||
|
if ($end === false) {
|
||||||
|
$this->offset = \strlen($this->buffer);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->offset = $end + 1;
|
||||||
|
$this->state = $this->remaining === 0 ? self::TRAILER : self::DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function decodeDataEnd(): void
|
||||||
|
{
|
||||||
|
$this->offset += \strspn($this->buffer, "\r", $this->offset);
|
||||||
|
if ($this->offset === \strlen($this->buffer)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ($this->buffer[$this->offset] !== "\n") {
|
||||||
|
throw new \RuntimeException('Invalid chunked response body: missing CRLF after chunk data');
|
||||||
|
}
|
||||||
|
|
||||||
|
++$this->offset;
|
||||||
|
$this->state = self::SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function decodeTrailer(): void
|
||||||
|
{
|
||||||
|
if ($this->state !== self::TRAILER) {
|
||||||
|
if ($this->buffer[$this->offset] !== "\n") {
|
||||||
|
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||||
|
}
|
||||||
|
|
||||||
|
++$this->offset;
|
||||||
|
$this->state = $this->state === self::FINAL_CR ? self::DONE : self::TRAILER;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$count = \strcspn($this->buffer, "\r\n", $this->offset);
|
||||||
|
$this->line .= \substr($this->buffer, $this->offset, $count);
|
||||||
|
$this->offset += $count;
|
||||||
|
$this->trailerLength += $count;
|
||||||
|
if (\strlen($this->line) > self::MAX_TRAILER_LINE_LENGTH || $this->trailerLength > self::MAX_TRAILER_SECTION_LENGTH) {
|
||||||
|
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||||
|
}
|
||||||
|
if ($this->offset === \strlen($this->buffer)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$carriageReturn = $this->buffer[$this->offset] === "\r";
|
||||||
|
++$this->offset;
|
||||||
|
if ($this->line === '') {
|
||||||
|
$this->state = $carriageReturn ? self::FINAL_CR : self::DONE;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (\strpos($this->line, "\0") !== false || \strpos($this->line, ':') === false) {
|
||||||
|
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->line = '';
|
||||||
|
if ($carriageReturn) {
|
||||||
|
$this->state = self::TRAILER_CR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace GuzzleHttp\Handler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
final class Clock
|
||||||
|
{
|
||||||
|
private function __construct()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the current monotonic clock reading in seconds.
|
||||||
|
*/
|
||||||
|
public static function now(): float
|
||||||
|
{
|
||||||
|
return \hrtime(true) / 1e9;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function sleep(int $microseconds): void
|
||||||
|
{
|
||||||
|
while ($microseconds > 0) {
|
||||||
|
$slice = \min($microseconds, 0xFFFFFFFF);
|
||||||
|
\usleep($slice);
|
||||||
|
$microseconds -= $slice;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user