This commit is contained in:
2025-10-13 09:04:00 +00:00
parent 7a3b2960f8
commit 4ee3212899
230 changed files with 40880 additions and 245 deletions
+1
View File
@@ -0,0 +1 @@
config.backup.php
+4 -1
View File
@@ -3,6 +3,9 @@
"workerman/workerman": "^4.2",
"kornrunner/keccak": "^1.1",
"simplito/elliptic-php": "^1.0",
"workerman/globaldata": "^1.0"
"workerman/globaldata": "^1.0",
"workerman/http-client": "^2.2",
"guzzlehttp/guzzle": "^7.10",
"catfan/medoo": "^2.2"
}
}
Generated
+771 -1
View File
@@ -4,8 +4,409 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "98dbfa81f42fcda4bf20440ae7f65a2f",
"content-hash": "87621f64196860bbad3670b0cf891224",
"packages": [
{
"name": "catfan/medoo",
"version": "v2.2.0",
"source": {
"type": "git",
"url": "https://github.com/catfan/Medoo.git",
"reference": "347515fe63339387738c5c1c93d1d6726cc9774a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/catfan/Medoo/zipball/347515fe63339387738c5c1c93d1d6726cc9774a",
"reference": "347515fe63339387738c5c1c93d1d6726cc9774a",
"shasum": ""
},
"require": {
"ext-pdo": "*",
"php": ">=7.3"
},
"require-dev": {
"phpunit/phpunit": "^9.0"
},
"suggest": {
"ext-pdo_dblib": "For MSSQL or Sybase database on Linux/UNIX platform",
"ext-pdo_mysql": "For MySQL or MariaDB database",
"ext-pdo_oci": "For Oracle database",
"ext-pdo_pqsql": "For PostgreSQL database",
"ext-pdo_sqlite": "For SQLite database",
"ext-pdo_sqlsrv": "For MSSQL database on both Window/Liunx platform"
},
"type": "framework",
"autoload": {
"psr-4": {
"Medoo\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Angel Lai",
"email": "angel@medoo.in"
}
],
"description": "The lightweight PHP database framework to accelerate development",
"homepage": "https://medoo.in",
"keywords": [
"database",
"database library",
"lightweight",
"mariadb",
"mssql",
"mysql",
"oracle",
"php framework",
"postgresql",
"sql",
"sqlite"
],
"support": {
"issues": "https://github.com/catfan/Medoo/issues",
"source": "https://github.com/catfan/Medoo"
},
"funding": [
{
"url": "https://paypal.me/AngelaonLai",
"type": "custom"
},
{
"url": "https://opencollective.com/medoo",
"type": "open_collective"
}
],
"time": "2025-03-31T07:37:23+00:00"
},
{
"name": "guzzlehttp/guzzle",
"version": "7.10.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "b51ac707cfa420b7bfd4e4d5e510ba8008e822b4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4",
"reference": "b51ac707cfa420b7bfd4e4d5e510ba8008e822b4",
"shasum": ""
},
"require": {
"ext-json": "*",
"guzzlehttp/promises": "^2.3",
"guzzlehttp/psr7": "^2.8",
"php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2 || ^3.0"
},
"provide": {
"psr/http-client-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"ext-curl": "*",
"guzzle/client-integration-tests": "3.0.2",
"php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.39 || ^9.6.20",
"psr/log": "^1.1 || ^2.0 || ^3.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"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"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"
}
],
"description": "Guzzle is a PHP HTTP client library",
"keywords": [
"client",
"curl",
"framework",
"http",
"http client",
"psr-18",
"psr-7",
"rest",
"web service"
],
"support": {
"issues": "https://github.com/guzzle/guzzle/issues",
"source": "https://github.com/guzzle/guzzle/tree/7.10.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle",
"type": "tidelift"
}
],
"time": "2025-08-23T22:36:01+00:00"
},
{
"name": "guzzlehttp/promises",
"version": "2.3.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "481557b130ef3790cf82b713667b43030dc9c957"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/481557b130ef3790cf82b713667b43030dc9c957",
"reference": "481557b130ef3790cf82b713667b43030dc9c957",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.44 || ^9.6.25"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"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": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
}
],
"description": "Guzzle promises library",
"keywords": [
"promise"
],
"support": {
"issues": "https://github.com/guzzle/promises/issues",
"source": "https://github.com/guzzle/promises/tree/2.3.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises",
"type": "tidelift"
}
],
"time": "2025-08-22T14:34:08+00:00"
},
{
"name": "guzzlehttp/psr7",
"version": "2.8.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "21dc724a0583619cd1652f673303492272778051"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/21dc724a0583619cd1652f673303492272778051",
"reference": "21dc724a0583619cd1652f673303492272778051",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.1 || ^2.0",
"ralouphie/getallheaders": "^3.0"
},
"provide": {
"psr/http-factory-implementation": "1.0",
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"http-interop/http-factory-tests": "0.9.0",
"phpunit/phpunit": "^8.5.44 || ^9.6.25"
},
"suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"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": "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"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://sagikazarmark.hu"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"psr-7",
"request",
"response",
"stream",
"uri",
"url"
],
"support": {
"issues": "https://github.com/guzzle/psr7/issues",
"source": "https://github.com/guzzle/psr7/tree/2.8.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7",
"type": "tidelift"
}
],
"time": "2025-08-23T21:21:41+00:00"
},
{
"name": "kornrunner/keccak",
"version": "1.1.0",
@@ -55,6 +456,210 @@
},
"time": "2020-12-07T15:40:44+00:00"
},
{
"name": "psr/http-client",
"version": "1.0.3",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-client.git",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90",
"shasum": ""
},
"require": {
"php": "^7.0 || ^8.0",
"psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP clients",
"homepage": "https://github.com/php-fig/http-client",
"keywords": [
"http",
"http-client",
"psr",
"psr-18"
],
"support": {
"source": "https://github.com/php-fig/http-client"
},
"time": "2023-09-23T14:17:50+00:00"
},
{
"name": "psr/http-factory",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"shasum": ""
},
"require": {
"php": ">=7.1",
"psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-factory"
},
"time": "2024-04-15T12:06:14+00:00"
},
{
"name": "psr/http-message",
"version": "2.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-message/tree/2.0"
},
"time": "2023-04-04T09:54:51+00:00"
},
{
"name": "ralouphie/getallheaders",
"version": "3.0.3",
"source": {
"type": "git",
"url": "https://github.com/ralouphie/getallheaders.git",
"reference": "120b605dfeb996808c31b6477290a714d356e822"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822",
"reference": "120b605dfeb996808c31b6477290a714d356e822",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"require-dev": {
"php-coveralls/php-coveralls": "^2.1",
"phpunit/phpunit": "^5 || ^6.5"
},
"type": "library",
"autoload": {
"files": [
"src/getallheaders.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ralph Khattar",
"email": "ralph.khattar@gmail.com"
}
],
"description": "A polyfill for getallheaders.",
"support": {
"issues": "https://github.com/ralouphie/getallheaders/issues",
"source": "https://github.com/ralouphie/getallheaders/tree/develop"
},
"time": "2019-03-08T08:55:37+00:00"
},
{
"name": "simplito/bigint-wrapper-php",
"version": "1.0.0",
@@ -202,6 +807,73 @@
},
"time": "2024-01-09T14:57:04+00:00"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.0.2",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/26954b3d62a6c5fd0ea8a2a00c0353a14978d05c",
"reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c",
"shasum": ""
},
"require": {
"php": ">=8.0.2"
},
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/contracts",
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.0-dev"
}
},
"autoload": {
"files": [
"function.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.0.2"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2022-01-02T09:55:41+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.33.0",
@@ -321,6 +993,104 @@
},
"time": "2024-12-27T12:40:16+00:00"
},
{
"name": "workerman/http-client",
"version": "v2.2.9",
"source": {
"type": "git",
"url": "https://github.com/workerman-php/http-client.git",
"reference": "d26b4b16feb8089df132ce6befce28cb7ff467b6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/workerman-php/http-client/zipball/d26b4b16feb8089df132ce6befce28cb7ff467b6",
"reference": "d26b4b16feb8089df132ce6befce28cb7ff467b6",
"shasum": ""
},
"require": {
"workerman/psr7": ">=1.4.3",
"workerman/workerman": "^4.1.0||^5.0.0||dev-master"
},
"type": "library",
"autoload": {
"psr-4": {
"Workerman\\Http\\": "./src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"homepage": "http://www.workerman.net",
"support": {
"issues": "https://github.com/workerman-php/http-client/issues",
"source": "https://github.com/workerman-php/http-client/tree/v2.2.9"
},
"time": "2025-01-19T12:22:04+00:00"
},
{
"name": "workerman/psr7",
"version": "v2.0.2",
"source": {
"type": "git",
"url": "https://github.com/walkor/psr7.git",
"reference": "5f5b65e2462cd408f738cc967a80d8c15f9b57f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/walkor/psr7/zipball/5f5b65e2462cd408f738cc967a80d8c15f9b57f3",
"reference": "5f5b65e2462cd408f738cc967a80d8c15f9b57f3",
"shasum": ""
},
"require": {
"php": ">=7.2.0",
"psr/http-message": "~2.0"
},
"provide": {
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"type": "library",
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"Workerman\\Psr7\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Tobias Schultze",
"homepage": "https://github.com/Tobion"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"request",
"response",
"stream",
"uri",
"url"
],
"support": {
"source": "https://github.com/walkor/psr7/tree/v2.0.2"
},
"time": "2025-03-06T12:00:37+00:00"
},
{
"name": "workerman/workerman",
"version": "v4.2.1",
+26 -8
View File
@@ -1,10 +1,28 @@
<?php
$options=[
'workers'=>4,
'numeric-only'=> false,
'repeat'=>4,
'logFile'=>'',
'detailInfo'=> false,
'staticSecond'=>5,
];
$options = [
'workers' => 4,
'numeric-only' => false,
'repeat' => 4,
'logFile' => '',
'detailInfo' => false,
'staticSecond' => 5,
'redis' =>
[
'ip' => '127.0.0.1',
'port' => 6379,
'password' => 'YOURPASSWARD',
],
'db' =>
[
'type' => 'mysql',
'host' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'port' => 3306,
],
'apikey' => '',
];
-2
View File
@@ -1,2 +0,0 @@
{"timestamp":"2025-10-09T11:32:29+00:00","address":"0xc3804ee34124040c543330b8bc9fed7a2301dddd","private_key":"cbb084d6de06c149220da85949db7b15a11e014ef25453b9493a48211dacefe0"}
{"timestamp":"2025-10-09T11:32:47+00:00","address":"0x24ab4348cdd5488268df22b98837c019c1977777","private_key":"94df5e54b037e71387060d278691b48bf32716386165ed0b8d61d26ca821c991"}
-219
View File
@@ -1,219 +0,0 @@
<?php
// start.php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/helper.php';
require __DIR__ . '/config.php';
require __DIR__ . '/version.php';
use Workerman\Worker;
use Elliptic\EC;
use kornrunner\Keccak;
use Workerman\Timer;
// 你应该实现这个函数:发现地址后要做的事(扫描、转账、上报等)
// 这里只给出一个示例实现:异步-safe 的日志 + 简单输出。
// 请根据你实际需要替换或扩展该函数内容。
// 注意:这个函数在各个子进程中同步执行(阻塞该进程直至返回)。
function scanwallet(string $address, string $privateKey): void {
// === 示例逻辑(请替换为真实逻辑) ===
// 1) 记录到日志文件(追加)
global $logFile;
$entry = [
'timestamp' => date('c'),
'address' => $address,
'private_key' => $privateKey,
];
// 写入日志(追加,使用文件锁)
$json = json_encode($entry, JSON_UNESCAPED_SLASHES) . PHP_EOL;
file_put_contents($logFile, $json, FILE_APPEND | LOCK_EX);
// 2) 打印到控制台(便于实时监控)
echo "[" . date('Y-m-d H:i:s') . "] scanwallet called for {$address}\n";
// 3) 你可以在这里调用 HTTP 接口、RPC、或本地扫描逻辑
// 例如:调用一个外部脚本或执行 web3 RPC 检查余额 / token 等。
// 如果操作可能耗时较长,考虑把耗时任务放到队列(Redis/Beanstalk/DB)或另起子进程处理。
// =======================================
}
// CLI 参数解析(可选)
#$options = getopt('', ['workers::', 'repeat::', 'numeric-only::', 'logfile::']);
#echo($options['repeat']);
$workerCount = isset($options['workers']) ? (int)$options['workers'] : cpu_count()*4;
$minRepeat = isset($options['repeat']) ? (int)$options['repeat'] : 4; // 默认至少 4 个相同
$requireNumeric = isset($options['numeric-only']) ? (bool)$options['numeric-only'] : false;
$logFile = isset($options['logfile']) ? $options['logfile'] : (__DIR__ . '/found.log');
$detailInfo = isset($options['detailInfo']) ? (bool)$options['detailInfo'] : false;
$staticSecond = isset($options['staticSecond']) ? (int)$options['staticSecond'] : 10;
echo "配置: 详细输出={$detailInfo}, 进程:{$workerCount}, 相同数量={$minRepeat}, 仅数字=" . ($requireNumeric ? 'true' : 'false') . ", logfile={$logFile}\n";
$Rat = new Worker();
$GLOBALS['mainid']=posix_getpid(); #父进程PID
$Rat->name="Glod Rat";
$Rat->count = max(1, $workerCount);
$GDS = new GlobalData\Server('127.0.0.1', 2207);
$Rat->onWorkerStart = function($Rat) use ($minRepeat, $requireNumeric,$detailInfo) {
global $gd;
$gd = new \GlobalData\Client('127.0.0.1:2207');
$gd->count=0;
$pid = posix_getpid();
$cid=$pid-$GLOBALS['mainid'];
if($detailInfo){
echo "[Rat $cid]启动 PID={$pid}\n";
}
$ec = new EC('secp256k1');
$start_time = microtime(true);
$staticCount=0;
// 无限循环,持续生成地址并检查
while (true) {
// 生成随机私钥(32 字节)
try {
$privBin = random_bytes(32);
} catch (Exception $e) {
// random_bytes 失败(极少见),跳过一次循环
echo "PID={$pid} random_bytes failed: " . $e->getMessage() . "\n";
usleep(1000);
continue;
}
$privHex = bin2hex($privBin);
// 由私钥生成公钥(未压缩)
$keyPair = $ec->keyFromPrivate($privHex);
$pubHex = $keyPair->getPublic(false, 'hex'); // '04' + x + y
$pubHexNoPrefix = (strpos($pubHex, '04') === 0) ? substr($pubHex, 2) : $pubHex;
// keccak256 公钥并取地址
$hash = Keccak::hash(hex2bin($pubHexNoPrefix), 256); // 返回 hex
$address = '0x' . substr($hash, -40);
$staticCount=$staticCount+1;
if (microtime(true) - $start_time >= 5) {
if($detailInfo){
echo "[Rat $cid] digged $staticCount address in past 5s \n";
}
$gd->count=$gd->count+$staticCount;
$staticCount=0;
$start_time = microtime(true);
}
// 检查末尾连续相同字符(只检查尾部连续段)
$addrRaw = strtolower(substr($address, 2)); // 纯 hex40 chars
$len = strlen($addrRaw);
$lastChar = $addrRaw[$len - 1];
$count = 1;
for ($i = $len - 2; $i >= 0; $i--) {
if ($addrRaw[$i] === $lastChar) $count++;
else break;
}
// 如果满足重复数量,并且(可选)最后字符为数字
if ($count >= $minRepeat) {
if ($requireNumeric && !ctype_digit($lastChar)) {
// 不满足数字要求,继续
} else {
// 匹配成功 —— 调用 scanwallet 并记录(但不退出,继续寻找)
try {
// 记录到控制台(便于监控)
if($detailInfo){
echo " [Rat $cid] PID={$pid} 找到匹配地址 {$address} (尾部 {$count} 个 '{$lastChar}'), 调用 scanwallet\n";
}
$gd->scount=$gd->scount+1;
// 可选:把结果也写入一个单独的结果文件(便于批处理)
$result = [
'pid' => $pid,
'private_key' => $privHex,
'address' => $address,
'repeat_char' => $lastChar,
'repeat_count' => $count,
'timestamp' => date('c'),
'count'=> $count,
'char'=> $lastChar,
];
// 调用用户实现的扫描函数(可能阻塞当前进程)
# toCache($result);
/**
// 追加到 found.log(同 scanwallet 中的 global logfile
global $logFile;
file_put_contents($logFile, json_encode($result, JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND | LOCK_EX);
*/
// 继续寻找(不要退出)
} catch (Throwable $t) {
// 避免 scanwallet 中的异常导致进程崩溃
if($detailInfo){
echo "PID={$pid} scanwallet 抛出异常: " . $t->getMessage() . "\n";
}
}
}
}
// 若想降低 CPU 占用可在这里加短暂 sleep(但会降低查找速度)
// usleep(0); // 等同于 yield
}
if($detailInfo){
echo "PID={$pid} 退出循环(理论上不应到达)\n";
}
};
$Rat->onWorkerStop = function($Rat) {
$pid = posix_getpid();
$cid=$pid-$GLOBALS['mainid'];
echo "[Rat $cid]启动 PID={$pid} 已终止\n";
};
$Static = new Worker();
$Static->name='Static Server';
$Static->onWorkerStart = function($Static)use($staticSecond,$detailInfo) {
$GLOBALS['starttime']=microtime(true);
$GLOBALS['lc']=0;
$GLOBALS['lsc']=0;
Timer::add($staticSecond, function()use($staticSecond,$detailInfo){
$gda = new \GlobalData\Client('127.0.0.1:2207');
$staticCount=$gda->count;
$avgCount=($staticCount-$GLOBALS['lc'])/$staticSecond;
$successCount=$gda->scount;
$avgsCount=($successCount-$GLOBALS['lsc']);
$totalSpeed= ($successCount / (microtime(true)-$GLOBALS['starttime'])) * 3600;
$running=formatSeconds(microtime(true)-$GLOBALS['starttime']);
if(!$detailInfo){
echo "\033[H"; // 光标回到左上角
echo "\033[J";
echo "
.88888. dP dP 888888ba dP
d8' `88 88 88 88 `8b 88
88 .d8888b. 88 .d888b88 a88aaaa8P' .d8888b. d8888P
88 YP88 88' `88 88 88' `88 88 `8b. 88' `88 88
Y8. .88 88. .88 88 88. .88 88 88 88. .88 88
`88888' `88888P' dP `88888P8 dP dP `88888P8 dP
====================================================
|| Gold Rat v".GR_VERSION." Build ".GR_BUILD." ||
||Dig out wallet address with the beautiful number||
|| As well as a CPU Benchmark tool ||
====================================================
";
}
echo "[STATIC] in last $staticSecond s:
Avg: $avgCount adds/s, Total: $staticCount adds
Succeed: $avgsCount adds, Total: $successCount adds
Total Diging Speed: $totalSpeed adds/hour
Total Runing Time: $running
====================================================
Enter Ctrl+C to Exit.
————————————————————————————————————————————————————
©Gold Rat by LayFi.de
\n";
$GLOBALS['lc']=$staticCount;
$GLOBALS['lsc']=$successCount;
});
};
Worker::runAll();
+325
View File
@@ -0,0 +1,325 @@
<?php
// start.php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/helper.php';
require __DIR__ . '/config.php';
require __DIR__ . '/version.php';
use Workerman\Worker;
use Elliptic\EC;
use kornrunner\Keccak;
use Workerman\Timer;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Medoo\Medoo;
// CLI 参数解析(可选)
#$options = getopt('', ['workers::', 'repeat::', 'numeric-only::', 'logfile::']);
#echo($options['repeat']);
$workerCount = isset($options['workers']) ? (int)$options['workers'] : cpu_count()*4;
$minRepeat = isset($options['repeat']) ? (int)$options['repeat'] : 4; // 默认至少 4 个相同
$requireNumeric = isset($options['numeric-only']) ? (bool)$options['numeric-only'] : false;
$logFile = isset($options['logfile']) ? $options['logfile'] : (__DIR__ . '/found.log');
$detailInfo = isset($options['detailInfo']) ? (bool)$options['detailInfo'] : false;
$staticSecond = isset($options['staticSecond']) ? (int)$options['staticSecond'] : 10;
$apiKey=isset($options['apikey']) ? $options['apikey'] : 'none';
echo "Configuration: VerboseOpt={$detailInfo}, Progress:{$workerCount}, SameNumbers={$minRepeat}, NumericOnly=" . ($requireNumeric ? 'true' : 'false') . "\n";
if(!isset($options['redis'])||!isset($options['redis']['ip'])||!isset($options['redis']['port'])){
exit("🚨Lack of Redis Configuration, now exit……\n");
}
if(!isset($options['db'])){
exit("🚨Lack of Database Configuration, now exit……\n");
}else{
$dbConfig=$options['db'];
}
if($apiKey=='none'){
exit("🚨Lack of EtherScan API Key, now exit……\n You can apply for an APIKey through https://etherscan.io/apidashboard \n");
}
$Rat = new Worker();
$GLOBALS['mainid']=posix_getpid(); #父进程PID
$Rat->name="Glod Rat";
$Rat->count = max(1, $workerCount);
$GDS = new GlobalData\Server('127.0.0.1', 2207);
$Rat->onWorkerStart = function($Rat) use ($minRepeat, $requireNumeric,$detailInfo,$options) {
global $gd;
$gd = new \GlobalData\Client('127.0.0.1:2207');
$gd->count=0;
$pid = posix_getpid();
$cid=$pid-$GLOBALS['mainid'];
if($detailInfo){
echo "[Rat $cid]启动 PID={$pid}\n";
}
$redis = new Redis();
$redis->connect($options['redis']['ip'], $options['redis']['port']);
if($detailInfo){
echo "[Rat $cid] Connecting Redis……\n";
}
if(isset($options['redis']['password'])&&$options['redis']['password']!=false){
if($detailInfo){
echo "[Rat $cid] Redis Authing……\n";
}
$redis->auth($options['redis']['password']);
}
if($redis->ping(1)&&$detailInfo){
echo "[Rat $cid] Redis Successfully Connected\n";
}
$ec = new EC('secp256k1');
$start_time = microtime(true);
$staticCount=0;
// 无限循环,持续生成地址并检查
while (true) {
// 生成随机私钥(32 字节)
try {
$privBin = random_bytes(32);
} catch (Exception $e) {
// random_bytes 失败(极少见),跳过一次循环
echo "\033[33m[Rat $cid] PID={$pid} random_bytes failed: " . $e->getMessage() . ",thus jumped this loop\n
This is an expected but extremely rare error. It should not affect normal operation. \n
However, if this error persists, please be vigilant.\n
This Rat will sleep for 1000 ms\033[0m\n";
usleep(1000);
continue;
}
$privHex = bin2hex($privBin);
// 由私钥生成公钥(未压缩)
$keyPair = $ec->keyFromPrivate($privHex);
$pubHex = $keyPair->getPublic(false, 'hex'); // '04' + x + y
$pubHexNoPrefix = (strpos($pubHex, '04') === 0) ? substr($pubHex, 2) : $pubHex;
// keccak256 公钥并取地址
$hash = Keccak::hash(hex2bin($pubHexNoPrefix), 256); // 返回 hex
$address = '0x' . substr($hash, -40);
$staticCount=$staticCount+1;
if (microtime(true) - $start_time >= 5) {
if($detailInfo){
echo "[Rat $cid] digged $staticCount address in past 5s \n";
}
$gd->count=$gd->count+$staticCount;
$staticCount=0;
$start_time = microtime(true);
}
// 检查末尾连续相同字符(只检查尾部连续段)
$addrRaw = strtolower(substr($address, 2)); // 纯 hex40 chars
$len = strlen($addrRaw);
$lastChar = $addrRaw[$len - 1];
$count = 1;
for ($i = $len - 2; $i >= 0; $i--) {
if ($addrRaw[$i] === $lastChar) $count++;
else break;
}
// 如果满足重复数量,并且(可选)最后字符为数字
if ($count >= $minRepeat) {
if ($requireNumeric && !ctype_digit($lastChar)) {
// 不满足数字要求,继续
} else {
// 匹配成功 —— 调用 scanwallet 并记录(但不退出,继续寻找)
try {
if($detailInfo){
echo "[Rat $cid] PID={$pid} Found Address {$address} (ended with {$count} x '{$lastChar}')\n";
}
$gd->scount=$gd->scount+1;
$result = [
'pid' => $pid,
'private_key' => $privHex,
'timestamp' => time(),
'count'=> $count,
'char'=> $lastChar,
];
$redis->sadd('goldRat_set', $address);
$redis->hset('goldRat_hash', $address, json_encode($result));
} catch (Throwable $t) {
if($detailInfo){
echo "\033[31m ❌[Rat $cid] PID={$pid} ERROR OCCURRED : " . $t->getMessage() . "\033[0m\n";
}
}
}
}
// 若想降低 CPU 占用可在这里加短暂 sleep(但会降低查找速度)
// usleep(0); // 等同于 yield
}
if($detailInfo){
echo "\033[31m ⚠[Rat $cid] PID={$pid} Unexceptedly Exited The Loop \033[0m\n";
}
};
$Rat->onWorkerStop = function($Rat) {
$pid = posix_getpid();
$cid=$pid-$GLOBALS['mainid'];
echo "[Rat $cid] PID={$pid} 已终止\n";
};
$Static = new Worker();
$Static->name='Static&Timer Service';
$Static->onWorkerStart = function($Static)use($staticSecond,$detailInfo,$apiKey) {
$GLOBALS['starttime']=microtime(true);
$GLOBALS['lc']=0;
$GLOBALS['lsc']=0;
$gda = new \GlobalData\Client('127.0.0.1:2207');
$gda->second_token=5;
$gda->minute_token=60;
$gda->lastToken='--';
$gda->lastTokenTime='will shown after 1min';
Timer::add(1, function()use($staticSecond,$detailInfo,$gda,$apiKey){
$gda->second_token= $gda->second_token+5;
});
Timer::add(60, function()use($staticSecond,$detailInfo,$gda,$apiKey){
if($detailInfo){
echo "Go to ask EtherScan for API useage";
}
$client = new Client([
'base_uri' => 'https://api.etherscan.io/v2/',
'timeout' => 10.0,
]);
$params = [
'query' => [
'module' => 'getapilimit',
'action' => 'getapilimit',
'apikey' => $apiKey
]
];
try {
$response = $client->get('api', $params);
$statusCode = $response->getStatusCode();
if ($statusCode == 200) {
$data = json_decode($response->getBody(), true);
if ($data['status'] === '1') {
$lastminute=secondsUntilUtcDayEnd()*60;
$addToken=$data['result']['creditsAvailable']/60;
$gda->lastToken=$data['result']['creditsAvailable'];
$gda->lastTokenTime=$data['result']['intervalExpiryTimespan'];
if($detailInfo){
echo "✅[Timmer]EtherScan Got the credit successfully\n";
}
} else {
if($detailInfo){
echo "❌[Timmer]EtherScan Get Credit Failed\n";
print_r($data);
}
$addToken=0;
}
}else{
if($detailInfo){
if($detailInfo){
echo "\033[31m❌[Timmer]EtherScan Http Request Failed: HTTP" . $statusCode . "\033[0m\n";
}
}
$addToken=0;
}
} catch (RequestException $e) {
echo "\033[31m❌[Timmer]EtherScan Http Request Failed: " . $e->getMessage() . "\033[0m\n";
$addToken=0;
}
$gda->minute_token= $gda->minute_token+$addToken;
});
Timer::add($staticSecond, function()use($staticSecond,$detailInfo,$gda){
$staticCount=$gda->count;
$avgCount=($staticCount-$GLOBALS['lc'])/$staticSecond;
$successCount=$gda->scount;
$creditAvailable=$gda->lastToken;
$resetCountdown=$gda->lastTokenTime;
$avgsCount=($successCount-$GLOBALS['lsc']);
$totalSpeed= ($successCount / (microtime(true)-$GLOBALS['starttime'])) * 3600;
$running=formatSeconds(microtime(true)-$GLOBALS['starttime']);
if(!$detailInfo){
echo "\033[H"; // 光标回到左上角
echo "\033[J";
echo " \033[33m
.88888. dP dP 888888ba dP
d8' `88 88 88 88 `8b 88
88 .d8888b. 88 .d888b88 a88aaaa8P' .d8888b. d8888P
88 YP88 88' `88 88 88' `88 88 `8b. 88' `88 88
Y8. .88 88. .88 88 88. .88 88 88 88. .88 88
`88888' `88888P' dP `88888P8 dP dP `88888P8 dP \033[0m
====================================================
|| Gold Rat v".GR_VERSION." Build ".GR_BUILD." ||
||Dig out wallet address with the beautiful number||
|| As well as a CPU Benchmark tool ||
====================================================
";
}
echo "[STATIC] in last $staticSecond s:
Avg: $avgCount adds/s, Total: $staticCount adds
Succeed: $avgsCount adds, Total: $successCount adds
Total Diging Speed: $totalSpeed adds/hour
Total Runing Time: $running
----------------API CREDITS INFO--------------------
EtherScan.io API
Available: $creditAvailable Credits
Reset Countdown: $resetCountdown
====================================================
Enter Ctrl+C to Exit.
————————————————————————————————————————————————————
©Gold Rat by LayFi.de
\n";
$GLOBALS['lc']=$staticCount;
$GLOBALS['lsc']=$successCount;
});
};
require __DIR__ . '/scanner.php';
require __DIR__ . '/writeToDB.php';
$Scanner=new Worker();
$Scanner->name='Scanner';
$Scanner->count=1;
$Scanner->onWorkerStart = function($Scanner)use($detailInfo,$options,$apiKey,$dbConfig){
usleep(1000);#延迟1秒启动,防止与Rat争抢redis并发
$pid = posix_getpid();
if($detailInfo){
echo "[Scanner] PID={$pid} Started\n";
}
$redis = new Redis();
$redis->connect($options['redis']['ip'], $options['redis']['port']);
if($detailInfo){
echo "[Scanner] Connecting Redis……\n";
}
if(isset($options['redis']['password'])&&$options['redis']['password']!=false){
if($detailInfo){
echo "[Scanner] Redis Authing……\n";
}
$redis->auth($options['redis']['password']);
}
if($redis->ping(1)&&$detailInfo){
echo "[Scanner] Redis Successfully Connected\n";
}
$setKey = 'goldRat_set';
$hashKey = 'goldRat_hash';
while(true){
$address = $redis->spop($setKey);
if ($address === false) {
usleep(1000); #休眠1s
}else{
$json = $redis->hget($hashKey, $address);
if($detailInfo){
echo "[Scanner] Take out and start scanning: $address\n";
}
if(scanwallet($address,$apiKey,$detailInfo)){
$active='true';
echo "\033[32m🎉[Scanner] $address found active!\033[0m\n";
writeToDB($address,$dbConfig,$json,true);
}else{
$active='false';
if($detailInfo){
echo "[Scanner] $address found nothing \n";
}
writeToDB($address,$dbConfig,$json,false);
}
$redis->hdel($hashKey, $address);
}
}
};
Worker::runAll();
+3
View File
@@ -33,4 +33,7 @@ function formatSeconds($seconds) {
if ($secs > 0 || $result === '') $result .= $secs."S";
return $result;
}
function secondsUntilUtcDayEnd(): int {
return strtotime('tomorrow 00:00:00 UTC') - 1 - time();
}
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* 项目提交前预处理脚本
* 用于安全备份并清理敏感配置字段
*/
$source = __DIR__ . '/config.php';
$backup = __DIR__ . '/config.backup.php';
// 1️⃣ 检查文件是否存在
if (!file_exists($source)) {
echo "❌ 找不到 config.php,跳过处理。\n";
exit(0);
}
// 2️⃣ 备份
copy($source, $backup);
echo "✅ 已备份到 config.backup.php\n";
// 3️⃣ 读取原配置
// 3️⃣ 读取配置
$options = [];
require $source; // 直接导入 $options
if (!isset($options) || !is_array($options)) {
echo "❌ config.php 中未定义 \$options 数组。\n";
exit(1);
}
// 4️⃣ 根据需求修改特定字段
// 举例:清空日志路径、设置默认workers、隐藏api_key
$fieldsToReset = [
'redis' => [
'ip'=>'127.0.0.1',
'port'=>6379,
'password'=>'YOURPASSWARD',
],
'db' => [
'type' => 'mysql',
'host' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'port' => 3306,
],
'apikey'=>'',
];
// 应用修改
foreach ($fieldsToReset as $key => $value) {
if (array_key_exists($key, $options)) {
$options[$key] = $value;
}
}
// 5️⃣ 写回原文件(保持 $options = [...] 格式)
$export = var_export($options, true);
// 把 array(...) 替换成 [...]
$export = preg_replace(['/\barray \(/', '/\)(\s*[,;])?/'], ['[', ']$1'], $export);
// 构造完整内容
$content = <<<PHP
<?php
\$options = $export;
PHP;
// 写入文件
file_put_contents($source, $content);
echo "✅ config.php 已清理敏感信息,可安全提交。\n";
+152
View File
@@ -0,0 +1,152 @@
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
function scanwallet($address,$apiKey,$detailInfo){
$gda = new \GlobalData\Client('127.0.0.1:2207');
$client = new Client([
'base_uri' => 'https://api.etherscan.io/v2/',
'timeout' => 3.0,
]);
// 想要遍历的链ID(参考官方链表)
$chains = [
1 => 'Ethereum',
56 => 'BNB Smart Chain',
137 => 'Polygon',
42161 => 'Arbitrum One',
8453 => 'Base',
43114 => 'Avalanche C-Chain',
42220 => 'Celo',
59144 => 'Linea',
10 => 'OP',
130 => 'Unichain',
204 => 'opBNB',
324 => 'zkSync'
];
$flag=false;
foreach ($chains as $chainId => $chainName) {
$jump=0;
if($detailInfo){
echo "🔍[Wallet Sacnner] 正在{$chainName}({$chainId})查询{$address}...\n";
}
$secondToken=$gda->second_token;
while($secondToken<1){
if($detailInfo){
echo "⏳[Wallet Sacnner] 1s QPS triggered, will sleep for one second.";
}
usleep(1000);
$secondToken=$gda->second_token;
}
$minuteToken=$gda->minute_token;
while($minuteToken<1){
if($detailInfo){
echo "⏳[Wallet Sacnner] 1min QPS triggered, will sleep for one minute.";
}
sleep(60);
$minuteToken=$gda->minute_token;
}
$params = [
'query' => [
'module' => 'account',
'action' => 'tokentx',
'address' => $address,
'startblock' => 0,
'endblock' => 99999999,
'page' => 1,
'offset' => 5,
'sort' => 'desc',
'chainid' => $chainId,
'apikey' => $apiKey
]
];
// 尝试最多5次以应对429
for ($attempt = 1; $attempt <= 5; $attempt++) {
try {
$response = $client->get('api', $params);
$statusCode = $response->getStatusCode();
if ($statusCode == 200) {
$data = json_decode($response->getBody(), true);
if ($data['status'] === '1' && count($data['result']) > 0) {
if($detailInfo){
echo "✅[Wallet Sacnner] 地址{$address}{$chainName} 上有交易记录\n";
}
return true;
} else {
if($detailInfo){
echo "❌[Wallet Sacnner] {$chainName} 无交易。\n";
}
break;
}
} elseif ($statusCode == 429) {
// 太多请求,退让(指数退避)
$delay = pow(2, $attempt);
if($detailInfo){
echo "⚠️[Wallet Sacnner]EtherScan 429 Too Many Requests{$delay} 秒后重试...\n";
}
sleep($delay);
} else {
if($detailInfo){
echo "❗[Wallet Sacnner]EtherScan HTTP错误 {$statusCode}\n";
}
break;
}
} catch (RequestException $e) {
if($detailInfo){
echo "\033[31m❌[Wallet Sacnner]EtherScan Http Request Failed: " . $e->getMessage() . "\033[0m\n";
}
sleep(pow(2, $attempt)); // 退让
} catch (ConnectException $e) {
if($detailInfo){
echo "\033[31m❌[Wallet Sacnner]EtherScan Http Request Failed: " . $e->getMessage() . "\033[0m\n";
}
sleep(pow(2, $attempt)); // 退让
}
}
}
#Additional Morph
$baselink='https://explorer-api.morphl2.io/api/v2/addresses/'.$address.'/counters';
if($detailInfo){
echo "🔍[Wallet Sacnner] 正在Morph查询{$address}...\n";
}
try {
$client = new Client([
'base_uri' => $baselink,
'timeout' => 3.0,
'http_errors' => false,
]);
$response = $client->get($baselink);
$statusCode = $response->getStatusCode();
if ($statusCode == 200) {
$data = json_decode($response->getBody(), true);
if($data['token_transfers_count']!=0){
if($detailInfo){
echo "✅[Wallet Sacnner] 地址{$address}在 Morph 上有交易记录\n";
}
return true;
} else {
if($detailInfo){
echo "❌[Wallet Sacnner] Morph 无交易。\n";
}
}
}elseif($statusCode == 404){
if($detailInfo){
echo "❌[Wallet Sacnner] Morph 无交易。\n";
}
}else{
if($detailInfo){
echo "❗[Wallet Sacnner] Morph Explorer HTTP错误 {$statusCode}\n";
}
}
} catch (RequestException $e) {
if($detailInfo){
echo "\033[31m❌[Wallet Sacnner] Morph Explorer Http Request Failed: " . $e->getMessage() . "\033[0m\n";
}
} catch (ConnectException $e) {
if($detailInfo){
echo "\033[31m❌[Wallet Sacnner] Morph Explorer Http Request Failed: " . $e->getMessage() . "\033[0m\n";
}
}
return false;
}
View File
-4
View File
@@ -1,4 +0,0 @@
<?php
function toCache($result){
}
+22
View File
@@ -0,0 +1,22 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
+4
View File
@@ -0,0 +1,4 @@
# These are supported funding model platforms
open_collective: medoo
custom: ["https://paypal.me/AngelaonLai"]
@@ -0,0 +1,26 @@
---
name: Bug report
about: Create a report to help us improve
---
**Information**
- **Version of Medoo:** [Enter the version number]
- **Version of PHP:** [Enter the version number]
- **Type of Database:** [MySQL, MSSQL, SQLite, etc.]
- **System:** [Linux|Windows|Mac]
**Describe the Problem**
A clear and concise description of what the problem is.
**Code Snippet**
The detail code you are using that causes the problem:
```php
// Write your PHP code here
```
**Expected Behavior**
A clear and concise description of what you expected to happen.
**Actual Behavior**
A clear and concise description of what actually happened.
+39
View File
@@ -0,0 +1,39 @@
name: build
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
php: ['7.3', '7.4', '8.2', '8.3']
steps:
- uses: actions/checkout@v3.3.0
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3.2.2
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
+225
View File
@@ -0,0 +1,225 @@
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
x64/
build/
[Bb]in/
[Oo]bj/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
*.pubxml
*.publishproj
# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
#############
## Windows detritus
#############
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac crap
.DS_Store
#############
## Python
#############
*.py[cod]
# Packages
*.egg
*.egg-info
dist/
build/
eggs/
parts/
var/
sdist/
develop-eggs/
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg
#php-cs-fixer
/.php_cs
#PHPUnit
/.phpunit.cache
/composer.lock
/vendor
+18
View File
@@ -0,0 +1,18 @@
<?php
$config = new PhpCsFixer\Config();
$config
->setRules([
'@PSR2' => true,
'@PSR12' => true,
'array_syntax' => ['syntax' => 'short'],
'nullable_type_declaration_for_default_null_value' => true
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__ . '/src')
->in(__DIR__ . '/tests')
)
;
return $config;
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Angel Lai
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.
+120
View File
@@ -0,0 +1,120 @@
<p align="center">
<a href="https://medoo.in" target="_blank"><img src="https://cloud.githubusercontent.com/assets/1467904/19835326/ca62bc36-9ebd-11e6-8b37-7240d76319cd.png"></a>
</p>
<p align="center">
<a href="https://github.com/catfan/Medoo/actions"><img alt="Build Status" src="https://github.com/catfan/Medoo/actions/workflows/php.yml/badge.svg"></a>
<a href="https://packagist.org/packages/catfan/medoo"><img alt="Total Downloads" src="https://poser.pugx.org/catfan/medoo/downloads"></a>
<a href="https://packagist.org/packages/catfan/medoo"><img alt="Latest Stable Version" src="https://poser.pugx.org/catfan/medoo/v/stable"></a>
<a href="https://packagist.org/packages/catfan/medoo"><img alt="License" src="https://poser.pugx.org/catfan/medoo/license"></a>
<a href="https://opencollective.com/medoo"><img alt="Backers on Open Collective" src="https://opencollective.com/Medoo/backers/badge.svg"></a>
<a href="https://opencollective.com/medoo"><img alt="Sponsors on Open Collective" src="https://opencollective.com/Medoo/sponsors/badge.svg"> </a>
</p>
> The lightweight PHP database framework to accelerate development.
## Features
* **Lightweight** - Single-file framework with minimal dependencies.
* **Easy** - Simple and intuitive API for quick integration.
* **Powerful** - Supports complex SQL queries, data mapping, and SQL injection prevention.
* **Compatible** - Works with MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, Oracle, Sybase, and more.
* **Friendly** - Integrates seamlessly with Laravel, CodeIgniter, Yii, Slim, and other PHP frameworks.
* **Free** - Licensed under MIT, free to use for any purpose.
## Requirements
- PHP 7.3 or later
- PDO extension enabled
## Get Started
### Install via composer
Add Medoo to the `composer.json` configuration file.
```bash
$ composer require catfan/medoo
```
Then update Composer
```bash
$ composer update
```
```php
// Require Composer's autoloader
require 'vendor/autoload.php';
// Import Medoo namespace
use Medoo\Medoo;
// Initialize database connection
$database = new Medoo([
'type' => 'mysql',
'host' => 'localhost',
'database' => 'name',
'username' => 'your_username',
'password' => 'your_password'
]);
// Insert data
$database->insert('account', [
'user_name' => 'foo',
'email' => 'foo@bar.com'
]);
// Retrieve data
$data = $database->select('account', [
'user_name',
'email'
], [
'user_id' => 50
]);
echo json_encode($data);
// [{
// "user_name" : "foo",
// "email" : "foo@bar.com",
// }]
```
## Contribution Guidelines
Before submitting a pull request, ensure compatibility with multiple database engines and include unit tests when possible.
### Testing & Code Style
- Run `phpunit tests` to execute unit tests.
- Use `php-cs-fixer fix` to enforce code style consistency.
### Commit Message Format
Each commit should begin with a tag indicating the type of change:
- `[fix]` for bug fixes
- `[feature]` for new features
- `[update]` for improvements
Keep contributions simple and well-documented.
## License
Medoo is released under the MIT License.
## Links
* Official website: [https://medoo.in](https://medoo.in)
* Documentation: [https://medoo.in/doc](https://medoo.in/doc)
* Twitter: [https://twitter.com/MedooPHP](https://twitter.com/MedooPHP)
* Open Collective: [https://opencollective.com/medoo](https://opencollective.com/medoo)
## Support Our Other Product
[Gear Browser - Web Browser for Geek](https://gear4.app)
[![Gear Browser](https://github.com/catfan/Medoo/assets/1467904/bc5059d4-6a2d-4bbf-90d9-a9f71bae3335)](https://gear4.app)
+43
View File
@@ -0,0 +1,43 @@
{
"name": "catfan/medoo",
"type": "framework",
"description": "The lightweight PHP database framework to accelerate development",
"keywords": ["database", "database library", "lightweight", "PHP framework", "SQL", "MySQL", "MSSQL", "SQLite", "PostgreSQL", "MariaDB", "Oracle"],
"homepage": "https://medoo.in",
"license": "MIT",
"support": {
"issues": "https://github.com/catfan/Medoo/issues",
"source": "https://github.com/catfan/Medoo"
},
"authors": [
{"name": "Angel Lai", "email": "angel@medoo.in"}
],
"require": {
"php": ">=7.3",
"ext-pdo": "*"
},
"require-dev": {
"phpunit/phpunit": "^9.0"
},
"suggest": {
"ext-pdo_mysql": "For MySQL or MariaDB database",
"ext-pdo_sqlsrv": "For MSSQL database on both Window/Liunx platform",
"ext-pdo_dblib": "For MSSQL or Sybase database on Linux/UNIX platform",
"ext-pdo_oci": "For Oracle database",
"ext-pdo_pqsql": "For PostgreSQL database",
"ext-pdo_sqlite": "For SQLite database"
},
"autoload": {
"psr-4": {
"Medoo\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Medoo\\Tests\\": "tests/"
}
},
"scripts": {
"test": "vendor/bin/phpunit tests"
}
}
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheResultFile=".phpunit.cache/test-results"
executionOrder="depends,defects"
failOnRisky="true"
failOnWarning="true"
verbose="true">
<testsuites>
<testsuite name="Medoo Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<coverage cacheDirectory=".phpunit.cache/code-coverage"
processUncoveredFiles="true">
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
</phpunit>
+2310
View File
File diff suppressed because it is too large Load Diff
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace Medoo\Tests;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class AggregateTest extends MedooTestCase
{
/**
* @covers ::count()
* @covers ::aggregate()
* @covers ::selectContext()
* @dataProvider typesProvider
*/
public function testCount($type)
{
$this->setType($type);
$this->database->count("account", [
"gender" => "female"
]);
$this->assertQuery(
<<<EOD
SELECT COUNT(*)
FROM "account"
WHERE "gender" = 'female'
EOD,
$this->database->queryString
);
}
/**
* @covers ::max()
* @covers ::aggregate()
* @covers ::selectContext()
* @dataProvider typesProvider
*/
public function testMax($type)
{
$this->setType($type);
$this->database->max("account", "age");
$this->assertQuery(
<<<EOD
SELECT MAX("age")
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::min()
* @covers ::aggregate()
* @covers ::selectContext()
* @dataProvider typesProvider
*/
public function testMin($type)
{
$this->setType($type);
$this->database->min("account", "age");
$this->assertQuery(
<<<EOD
SELECT MIN("age")
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::avg()
* @covers ::aggregate()
* @covers ::selectContext()
* @dataProvider typesProvider
*/
public function testAvg($type)
{
$this->setType($type);
$this->database->avg("account", "age");
$this->assertQuery(
<<<EOD
SELECT AVG("age")
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::sum()
* @covers ::aggregate()
* @covers ::selectContext()
* @dataProvider typesProvider
*/
public function testSum($type)
{
$this->setType($type);
$this->database->sum("account", "money");
$this->assertQuery(
<<<EOD
SELECT SUM("money")
FROM "account"
EOD,
$this->database->queryString
);
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace Medoo\Tests;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class CreateTest extends MedooTestCase
{
/**
* @covers ::create()
* @dataProvider typesProvider
*/
public function testCreate($type)
{
$this->setType($type);
$this->database->create("account", [
"id" => [
"INT",
"NOT NULL",
"AUTO_INCREMENT"
],
"email" => [
"VARCHAR(70)",
"NOT NULL",
"UNIQUE"
],
"PRIMARY KEY (<id>)"
], [
"AUTO_INCREMENT" => 200
]);
$this->assertQuery(
[
'default' => <<<EOD
CREATE TABLE IF NOT EXISTS "account"
("id" INT NOT NULL AUTO_INCREMENT,
"email" VARCHAR(70) NOT NULL UNIQUE,
PRIMARY KEY ("id"))
AUTO_INCREMENT = 200
EOD,
'mssql' => <<<EOD
CREATE TABLE [account]
([id] INT NOT NULL AUTO_INCREMENT,
[email] VARCHAR(70) NOT NULL UNIQUE,
PRIMARY KEY ([id]))
AUTO_INCREMENT = 200
EOD,
'oracle' => <<<EOD
CREATE TABLE "account"
("id" INT NOT NULL AUTO_INCREMENT,
"email" VARCHAR(70) NOT NULL UNIQUE,
PRIMARY KEY ("id"))
AUTO_INCREMENT = 200
EOD
],
$this->database->queryString
);
}
/**
* @covers ::create()
* @dataProvider typesProvider
*/
public function testCreateWithStringDefinition($type)
{
$this->setType($type);
$this->database->create("account", [
"id" => "INT NOT NULL AUTO_INCREMENT",
"email" => "VARCHAR(70) NOT NULL UNIQUE"
]);
$this->assertQuery(
[
'default' => <<<EOD
CREATE TABLE IF NOT EXISTS "account"
("id" INT NOT NULL AUTO_INCREMENT,
"email" VARCHAR(70) NOT NULL UNIQUE)
EOD,
'mssql' => <<<EOD
CREATE TABLE [account]
([id] INT NOT NULL AUTO_INCREMENT,
[email] VARCHAR(70) NOT NULL UNIQUE)
EOD,
'oracle' => <<<EOD
CREATE TABLE "account"
("id" INT NOT NULL AUTO_INCREMENT,
"email" VARCHAR(70) NOT NULL UNIQUE)
EOD
],
$this->database->queryString
);
}
/**
* @covers ::create()
* @dataProvider typesProvider
*/
public function testCreateWithSingleOption($type)
{
$this->setType($type);
$this->database->create("account", [
"id" => [
"INT",
"NOT NULL",
"AUTO_INCREMENT"
],
"email" => [
"VARCHAR(70)",
"NOT NULL",
"UNIQUE"
]
], "TABLESPACE tablespace_name");
$this->assertQuery(
[
'default' => <<<EOD
CREATE TABLE IF NOT EXISTS "account"
("id" INT NOT NULL AUTO_INCREMENT,
"email" VARCHAR(70) NOT NULL UNIQUE)
TABLESPACE tablespace_name
EOD,
'mssql' => <<<EOD
CREATE TABLE [account]
([id] INT NOT NULL AUTO_INCREMENT,
[email] VARCHAR(70) NOT NULL UNIQUE)
TABLESPACE tablespace_name
EOD,
'oracle' => <<<EOD
CREATE TABLE "account"
("id" INT NOT NULL AUTO_INCREMENT,
"email" VARCHAR(70) NOT NULL UNIQUE)
TABLESPACE tablespace_name
EOD
],
$this->database->queryString
);
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class DeleteTest extends MedooTestCase
{
/**
* @covers ::delete()
* @dataProvider typesProvider
*/
public function testDelete($type)
{
$this->setType($type);
$this->database->delete("account", [
"AND" => [
"type" => "business",
"age[<]" => 18
]
]);
$this->assertQuery(
<<<EOD
DELETE FROM "account"
WHERE ("type" = 'business' AND "age" < 18)
EOD,
$this->database->queryString
);
}
/**
* @covers ::delete()
* @dataProvider typesProvider
*/
public function testDeleteRaw($type)
{
$this->setType($type);
$whereClause = Medoo::raw("WHERE (<type> = :type AND <age> < :age)", [
':type' => 'business',
':age' => 18,
]);
$this->database->delete("account", $whereClause);
$this->assertQuery(
<<<EOD
DELETE FROM "account"
WHERE ("type" = 'business' AND "age" < 18)
EOD,
$this->database->queryString
);
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class DropTest extends MedooTestCase
{
/**
* @covers ::drop()
* @dataProvider typesProvider
*/
public function testDrop($type)
{
$this->setType($type);
$this->database->drop("account");
$this->assertQuery(
<<<EOD
DROP TABLE IF EXISTS "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::drop()
*/
public function testDropWithPrefix()
{
$database = new Medoo([
'testMode' => true,
'prefix' => 'PREFIX_'
]);
$database->type = "sqlite";
$database->drop("account");
$this->assertQuery(
<<<EOD
DROP TABLE IF EXISTS "PREFIX_account"
EOD,
$database->queryString
);
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace Medoo\Tests;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class GetTest extends MedooTestCase
{
/**
* @covers ::get()
* @dataProvider typesProvider
*/
public function testGet($type)
{
$this->setType($type);
$this->database->get("account", "email", [
"user_id" => 1234
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "email"
FROM "account"
WHERE "user_id" = 1234
LIMIT 1
EOD,
'mssql' => <<<EOD
SELECT [email]
FROM [account]
WHERE [user_id] = 1234
ORDER BY (SELECT 0)
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
'oracle' => <<<EOD
SELECT "email"
FROM "account"
WHERE "user_id" = 1234
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
], $this->database->queryString);
}
/**
* @covers ::get()
* @dataProvider typesProvider
*/
public function testGetWithColumns($type)
{
$this->setType($type);
$this->database->get("account", [
"email",
"location"
], [
"user_id" => 1234
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "email","location"
FROM "account"
WHERE "user_id" = 1234
LIMIT 1
EOD,
'mssql' => <<<EOD
SELECT [email],[location]
FROM [account]
WHERE [user_id] = 1234
ORDER BY (SELECT 0)
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
'oracle' => <<<EOD
SELECT "email","location"
FROM "account"
WHERE "user_id" = 1234
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
], $this->database->queryString);
}
/**
* @covers ::get()
* @dataProvider typesProvider
*/
public function testGetWithJoin($type)
{
$this->setType($type);
$this->database->get("post", [
"[>]account" => "user_id"
], [
"post.content",
"account.user_name"
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "post"."content","account"."user_name"
FROM "post"
LEFT JOIN "account" USING ("user_id")
LIMIT 1
EOD,
'mssql' => <<<EOD
SELECT [post].[content],[account].[user_name]
FROM [post]
LEFT JOIN [account] USING ([user_id])
ORDER BY (SELECT 0)
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
'oracle' => <<<EOD
SELECT "post"."content","account"."user_name"
FROM "post"
LEFT JOIN "account" USING ("user_id")
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
], $this->database->queryString);
}
/**
* @covers ::get()
* @dataProvider typesProvider
*/
public function testGetWithJoinAndWhere($type)
{
$this->setType($type);
$this->database->get("post", [
"[>]account" => "user_id"
], [
"post.content",
"account.user_name"
], [
'account.age[>]' => 18
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "post"."content","account"."user_name"
FROM "post"
LEFT JOIN "account" USING ("user_id")
WHERE "account"."age" > 18
LIMIT 1
EOD,
'mssql' => <<<EOD
SELECT [post].[content],[account].[user_name]
FROM [post]
LEFT JOIN [account] USING ([user_id])
WHERE [account].[age] > 18
ORDER BY (SELECT 0)
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
'oracle' => <<<EOD
SELECT "post"."content","account"."user_name"
FROM "post"
LEFT JOIN "account" USING ("user_id")
WHERE "account"."age" > 18
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
EOD,
], $this->database->queryString);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Medoo\Tests;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class HasTest extends MedooTestCase
{
/**
* @covers ::has()
* @covers ::selectContext()
* @dataProvider typesProvider
*/
public function testHas($type)
{
$this->setType($type);
$this->database->has("account", [
"user_name" => "foo"
]);
$this->assertQuery([
'default' => <<<EOD
SELECT EXISTS(SELECT 1 FROM "account" WHERE "user_name" = 'foo')
EOD,
'mssql' => <<<EOD
SELECT TOP 1 1 FROM [account] WHERE [user_name] = 'foo'
EOD
], $this->database->queryString);
}
}
+242
View File
@@ -0,0 +1,242 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class InsertTest extends MedooTestCase
{
/**
* @covers ::insert()
* @covers ::typeMap()
* @dataProvider typesProvider
*/
public function testInsert($type)
{
$this->setType($type);
$this->database->insert("account", [
"user_name" => "foo",
"email" => "foo@bar.com"
]);
$this->assertQuery(
<<<EOD
INSERT INTO "account" ("user_name", "email")
VALUES ('foo', 'foo@bar.com')
EOD,
$this->database->queryString
);
}
/**
* @covers ::insert()
* @covers ::typeMap()
* @dataProvider typesProvider
*/
public function testInsertWithArray($type)
{
$this->setType($type);
$this->database->insert("account", [
"user_name" => "foo",
"lang" => ["en", "fr"]
]);
$this->assertQuery([
'default' => <<<EOD
INSERT INTO "account" ("user_name", "lang")
VALUES ('foo', 'a:2:{i:0;s:2:"en";i:1;s:2:"fr";}')
EOD,
'mysql' => <<<EOD
INSERT INTO "account" ("user_name", "lang")
VALUES ('foo', 'a:2:{i:0;s:2:\"en\";i:1;s:2:\"fr\";}')
EOD
], $this->database->queryString);
}
/**
* @covers ::insert()
* @covers ::typeMap()
* @dataProvider typesProvider
*/
public function testInsertWithJSON($type)
{
$this->setType($type);
$this->database->insert("account", [
"user_name" => "foo",
"lang [JSON]" => ["en", "fr"]
]);
$this->assertQuery([
'default' => <<<EOD
INSERT INTO "account" ("user_name", "lang")
VALUES ('foo', '["en","fr"]')
EOD,
'mysql' => <<<EOD
INSERT INTO `account` (`user_name`, `lang`)
VALUES ('foo', '[\"en\",\"fr\"]')
EOD
], $this->database->queryString);
}
/**
* @covers ::insert()
* @dataProvider typesProvider
*/
public function testInsertWithRaw($type)
{
$this->setType($type);
$this->database->insert("account", [
"user_name" => Medoo::raw("UUID()")
]);
$this->assertQuery(
<<<EOD
INSERT INTO "account" ("user_name")
VALUES (UUID())
EOD,
$this->database->queryString
);
}
/**
* @covers ::insert()
* @covers ::typeMap()
* @dataProvider typesProvider
*/
public function testInsertWithNull($type)
{
$this->setType($type);
$this->database->insert("account", [
"location" => null
]);
$this->assertQuery(
<<<EOD
INSERT INTO "account" ("location")
VALUES (NULL)
EOD,
$this->database->queryString
);
}
/**
* @covers ::insert()
* @covers ::typeMap()
* @dataProvider typesProvider
*/
public function testInsertWithObject($type)
{
$this->setType($type);
$objectData = new Foo();
$this->database->insert("account", [
"object" => $objectData
]);
$this->assertQuery(
<<<EOD
INSERT INTO "account" ("object")
VALUES (:MeD0_mK)
EOD,
$this->database->queryString
);
}
/**
* @covers ::insert()
* @dataProvider typesProvider
*/
public function testMultiInsert($type)
{
$this->setType($type);
$this->database->insert("account", [
[
"user_name" => "foo",
"email" => "foo@bar.com"
],
[
"user_name" => "bar",
"email" => "bar@foo.com"
]
]);
$this->assertQuery(
<<<EOD
INSERT INTO "account" ("user_name", "email")
VALUES ('foo', 'foo@bar.com'), ('bar', 'bar@foo.com')
EOD,
$this->database->queryString
);
}
public function testOracleWithPrimaryKeyInsert()
{
$this->setType("oracle");
$this->database->insert("ACCOUNT", [
"NAME" => "foo",
"EMAIL" => "foo@bar.com"
], "ID");
$this->assertQuery(
<<<EOD
INSERT INTO "ACCOUNT" ("NAME", "EMAIL")
VALUES ('foo', 'foo@bar.com')
RETURNING "ID" INTO :RETURNID
EOD,
$this->database->queryString
);
}
public function testOracleWithLOBsInsert()
{
$this->setType("oracle");
$fp = fopen('README.md', 'r');
$this->database->insert("ACCOUNT", [
"NAME" => "foo",
"DATA" => $fp
]);
$this->assertQuery(
<<<EOD
INSERT INTO "ACCOUNT" ("NAME", "DATA")
VALUES ('foo', EMPTY_BLOB())
RETURNING "DATA" INTO :MeD1_mK
EOD,
$this->database->queryString
);
}
public function testOracleWithLOBsAndIdInsert()
{
$this->setType("oracle");
$fp = fopen('README.md', 'r');
$this->database->insert("ACCOUNT", [
"NAME" => "foo",
"DATA" => $fp
], "ID");
$this->assertQuery(
<<<EOD
INSERT INTO "ACCOUNT" ("NAME", "DATA")
VALUES ('foo', EMPTY_BLOB())
RETURNING "DATA", "ID" INTO :MeD1_mK, :RETURNID
EOD,
$this->database->queryString
);
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
use PHPUnit\Framework\TestCase;
class MedooTestCase extends TestCase
{
protected $database;
public $tableAliasConnector = ' AS ';
public $quotePattern = '"$1"';
public function setUp(): void
{
$this->database = new Medoo([
'testMode' => true
]);
}
public function typesProvider(): array
{
return [
'MySQL' => ['mysql'],
'MSSQL' => ['mssql'],
'SQLite' => ['sqlite'],
'PostgreSQL' => ['pgsql'],
'Oracle' => ['oracle']
];
}
public function setType($type): void
{
$this->database->setupType($type);
if ($type === 'oracle') {
$this->tableAliasConnector = ' ';
} elseif ($type === 'mysql') {
$this->quotePattern = '`$1`';
} elseif ($type === 'mssql') {
$this->quotePattern = '[$1]';
}
}
public function expectedQuery($expected): string
{
$result = preg_replace(
'/(?!\'[^\s]+\s?)"([\p{L}_][\p{L}\p{N}@$#\-_]*)"(?!\s?[^\s]+\')/u',
$this->quotePattern,
str_replace("\n", " ", $expected)
);
return str_replace(
' @AS ',
$this->tableAliasConnector,
$result
);
}
public function assertQuery($expected, $query): void
{
if (is_array($expected)) {
$this->assertEquals(
$this->expectedQuery($expected[$this->database->type] ?? $expected['default']),
$query
);
} else {
$this->assertEquals($this->expectedQuery($expected), $query);
}
}
}
class Foo
{
public $bar = "cat";
public function __wakeup()
{
$this->bar = "dog";
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class QueryTest extends MedooTestCase
{
/**
* @covers ::query()
* @covers ::isRaw()
* @covers ::buildRaw()
* @dataProvider typesProvider
*/
public function testQuery($type)
{
$this->setType($type);
$this->database->query("SELECT <account.email>,<account.nickname> FROM <account> WHERE <id> != 100");
$this->assertQuery(
<<<EOD
SELECT "account"."email","account"."nickname"
FROM "account"
WHERE "id" != 100
EOD,
$this->database->queryString
);
}
/**
* @covers ::query()
* @covers ::isRaw()
* @covers ::buildRaw()
*/
public function testQueryWithPrefix()
{
$database = new Medoo([
'testMode' => true,
'prefix' => 'PREFIX_'
]);
$database->query("SELECT <account.name> FROM <account>");
$this->assertQuery(
<<<EOD
SELECT "PREFIX_account"."name"
FROM "PREFIX_account"
EOD,
$database->queryString
);
}
/**
* @covers ::query()
* @covers ::isRaw()
* @covers ::buildRaw()
*/
public function testQueryTableWithPrefix()
{
$database = new Medoo([
'testMode' => true,
'prefix' => 'PREFIX_'
]);
$database->query("DROP TABLE IF EXISTS <account>");
$this->assertQuery(
<<<EOD
DROP TABLE IF EXISTS "PREFIX_account"
EOD,
$database->queryString
);
}
/**
* @covers ::query()
* @covers ::isRaw()
* @covers ::buildRaw()
*/
public function testQueryShowTableWithPrefix()
{
$database = new Medoo([
'testMode' => true,
'prefix' => 'PREFIX_'
]);
$database->query("SHOW TABLES LIKE <account>");
$this->assertQuery(
<<<EOD
SHOW TABLES LIKE "PREFIX_account"
EOD,
$database->queryString
);
}
/**
* @covers ::query()
* @covers ::isRaw()
* @covers ::buildRaw()
* @dataProvider typesProvider
*/
public function testPreparedStatementQuery($type)
{
$this->setType($type);
$this->database->query(
"SELECT * FROM <account> WHERE <user_name> = :user_name AND <age> = :age",
[
":user_name" => "John Smite",
":age" => 20
]
);
$this->assertQuery(
<<<EOD
SELECT *
FROM "account"
WHERE "user_name" = 'John Smite' AND "age" = 20
EOD,
$this->database->queryString
);
}
/**
* @covers ::query()
* @covers ::isRaw()
* @covers ::buildRaw()
*/
public function testQueryEscape()
{
$database = new Medoo([
'testMode' => true,
'prefix' => 'PREFIX_'
]);
$database->query("SELECT * FROM <account> WHERE <name> = '<John>'");
$this->assertQuery(
<<<EOD
SELECT *
FROM "PREFIX_account"
WHERE "name" = '<John>'
EOD,
$database->queryString
);
}
}
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
use InvalidArgumentException;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class QuoteTest extends MedooTestCase
{
/**
* @covers ::quote()
* @dataProvider typesProvider
*/
public function testQuote($type)
{
$this->setType($type);
$quotedString = $this->database->quote("Co'mpl''ex \"st'\"ring");
$expected = [
'mysql' => <<<EOD
'Co\'mpl\'\'ex \"st\'\"ring'
EOD,
'mssql' => <<<EOD
'Co''mpl''''ex "st''"ring'
EOD,
'sqlite' => <<<EOD
'Co''mpl''''ex "st''"ring'
EOD,
'pgsql' => <<<EOD
'Co''mpl''''ex "st''"ring'
EOD,
'oracle' => <<<EOD
'Co''mpl''''ex "st''"ring'
EOD
];
$this->assertEquals($expected[$type], $quotedString);
}
/**
* @covers ::columnQuote()
*/
public function testColumnQuote()
{
$this->assertEquals('"ColumnName"', $this->database->columnQuote("ColumnName"));
$this->assertEquals('"Column"."name"', $this->database->columnQuote("Column.name"));
$this->assertEquals('"Column"."Name"', $this->database->columnQuote("Column.Name"));
$this->assertEquals('"ネーム"', $this->database->columnQuote("ネーム"));
}
public function columnNamesProvider(): array
{
return [
["9ColumnName"],
["@ColumnName"],
[".ColumnName"],
["ColumnName."],
["ColumnName (alias)"]
];
}
/**
* @covers ::columnQuote()
* @dataProvider columnNamesProvider
*/
public function testIncorrectColumnQuote($column)
{
$this->expectException(InvalidArgumentException::class);
$this->database->columnQuote($column);
}
/**
* @covers ::tableQuote()
*/
public function testTableQuote()
{
$this->assertEquals('"TableName"', $this->database->tableQuote("TableName"));
$this->assertEquals('"_table"', $this->database->tableQuote("_table"));
$this->assertEquals('"アカウント"', $this->database->tableQuote("アカウント"));
}
/**
* @covers ::tableQuote()
*/
public function testPrefixTableQuote()
{
$database = new Medoo([
'testMode' => true,
'prefix' => 'PREFIX_'
]);
$this->assertEquals('"PREFIX_TableName"', $database->tableQuote("TableName"));
}
public function tableNamesProvider(): array
{
return [
["9TableName"],
["@TableName"],
[".TableName"],
["TableName."],
["Table.name"]
];
}
/**
* @covers ::tableQuote()
* @dataProvider tableNamesProvider
*/
public function testIncorrectTableQuote($table)
{
$this->expectException(InvalidArgumentException::class);
$this->database->tableQuote($table);
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
namespace Medoo\Tests;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class RandTest extends MedooTestCase
{
/**
* @covers ::rand()
* @dataProvider typesProvider
*/
public function testRand($type)
{
$this->setType($type);
$this->database->rand("account", [
"user_name"
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "user_name"
FROM "account"
ORDER BY RANDOM()
EOD,
'mysql' => <<<EOD
SELECT `user_name`
FROM `account`
ORDER BY RAND()
EOD,
'mssql' => <<<EOD
SELECT [user_name]
FROM [account]
ORDER BY NEWID()
EOD
], $this->database->queryString);
}
/**
* @covers ::rand()
* @dataProvider typesProvider
*/
public function testWhereRand($type)
{
$this->setType($type);
$this->database->rand("account", [
"user_name"
], [
"location" => "Tokyo"
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "user_name"
FROM "account"
WHERE "location" = 'Tokyo'
ORDER BY RANDOM()
EOD,
'mysql' => <<<EOD
SELECT `user_name`
FROM `account`
WHERE `location` = 'Tokyo'
ORDER BY RAND()
EOD,
'mssql' => <<<EOD
SELECT [user_name]
FROM [account]
WHERE [location] = 'Tokyo'
ORDER BY NEWID()
EOD
], $this->database->queryString);
}
/**
* @covers ::rand()
* @dataProvider typesProvider
*/
public function testWhereWithJoinRand($type)
{
$this->setType($type);
$this->database->rand("account", [
"[>]album" => "user_id"
], [
"account.user_name"
], [
"album.location" => "Tokyo"
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "account"."user_name"
FROM "account"
LEFT JOIN "album" USING ("user_id")
WHERE "album"."location" = 'Tokyo'
ORDER BY RANDOM()
EOD,
'mysql' => <<<EOD
SELECT `account`.`user_name`
FROM `account`
LEFT JOIN `album` USING (`user_id`)
WHERE `album`.`location` = 'Tokyo'
ORDER BY RAND()
EOD,
'mssql' => <<<EOD
SELECT [account].[user_name]
FROM [account]
LEFT JOIN [album] USING ([user_id])
WHERE [album].[location] = 'Tokyo'
ORDER BY NEWID()
EOD
], $this->database->queryString);
}
/**
* @covers ::rand()
* @dataProvider typesProvider
*/
public function testWithJoinRand($type)
{
$this->setType($type);
$this->database->rand("account", [
"[>]album" => "user_id"
], [
"account.user_name"
]);
$this->assertQuery([
'default' => <<<EOD
SELECT "account"."user_name"
FROM "account"
LEFT JOIN "album" USING ("user_id")
ORDER BY RANDOM()
EOD,
'mysql' => <<<EOD
SELECT `account`.`user_name`
FROM `account`
LEFT JOIN `album` USING (`user_id`)
ORDER BY RAND()
EOD,
'mssql' => <<<EOD
SELECT [account].[user_name]
FROM [account]
LEFT JOIN [album] USING ([user_id])
ORDER BY NEWID()
EOD
], $this->database->queryString);
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class RawTest extends MedooTestCase
{
/**
* @covers ::raw()
* @covers ::isRaw()
* @covers ::buildRaw()
* @dataProvider typesProvider
*/
public function testRawWithPlaceholder($type)
{
$this->setType($type);
$this->database->select('account', [
'score' => Medoo::raw('SUM(<age> + <experience>)')
]);
$this->assertQuery(
<<<EOD
SELECT SUM("age" + "experience") AS "score"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::raw()
* @covers ::isRaw()
* @covers ::buildRaw()
* @dataProvider typesProvider
*/
public function testRawWithSamePlaceholderName($type)
{
$this->setType($type);
$this->database->select('account', [
'system' => Medoo::raw("COUNT(<system> = 'window' OR <system> = 'mac')")
]);
$this->assertQuery(
<<<EOD
SELECT COUNT("system" = 'window' OR "system" = 'mac') AS "system"
FROM "account"
EOD,
$this->database->queryString
);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace Medoo\Tests;
use InvalidArgumentException;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class ReplaceTest extends MedooTestCase
{
/**
* @covers ::replace()
* @dataProvider typesProvider
*/
public function testReplace($type)
{
$this->setType($type);
$this->database->replace("account", [
"type" => [
"user" => "new_user",
"business" => "new_business"
],
"column" => [
"old_value" => "new_value"
]
], [
"user_id[>]" => 1000
]);
$this->assertQuery(
<<<EOD
UPDATE "account"
SET "type" = REPLACE("type", 'user', 'new_user'),
"type" = REPLACE("type", 'business', 'new_business'),
"column" = REPLACE("column", 'old_value', 'new_value')
WHERE "user_id" > 1000
EOD,
$this->database->queryString
);
}
/**
* @covers ::replace()
*/
public function testReplaceEmptyColumns()
{
$this->expectException(InvalidArgumentException::class);
$this->database->replace("account", [], [
"user_id[>]" => 1000
]);
}
}
+715
View File
@@ -0,0 +1,715 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
use InvalidArgumentException;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class SelectTest extends MedooTestCase
{
/**
* @covers ::select()
* @covers ::selectContext()
* @covers ::isJoin()
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectAll($type)
{
$this->setType($type);
$this->database->select("account", "*");
$this->assertQuery(
<<<EOD
SELECT * FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::select()
* @covers ::selectContext()
* @dataProvider typesProvider
*/
public function testSelectTableWithAlias($type)
{
$this->setType($type);
$this->database->select("account (user)", "name");
$this->assertQuery(
<<<EOD
SELECT "name"
FROM "account" @AS "user"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectSingleColumn($type)
{
$this->setType($type);
$this->database->select("account", "name");
$this->assertQuery(
<<<EOD
SELECT "name"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectColumns($type)
{
$this->setType($type);
$this->database->select("account", ["name", "id"]);
$this->assertQuery(
<<<EOD
SELECT "name","id"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectColumnsWithAlias($type)
{
$this->setType($type);
$this->database->select("account", ["name(nickname)", "id"]);
$this->assertQuery(
<<<EOD
SELECT "name" AS "nickname","id"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectColumnsWithType($type)
{
$this->setType($type);
$this->database->select("account", ["name[String]", "data [JSON]"]);
$this->assertQuery(
<<<EOD
SELECT "name","data"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectColumnsWithAliasAndType($type)
{
$this->setType($type);
$this->database->select("account", ["name (nickname) [String]", "data [JSON]"]);
$this->assertQuery(
<<<EOD
SELECT "name" AS "nickname","data"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectColumnsWithRaw($type)
{
$this->setType($type);
$this->database->select("account", [
"id [String]" => Medoo::raw("UUID()")
]);
$this->assertQuery(
<<<EOD
SELECT UUID() AS "id"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::select()
* @covers ::selectContext()
* @covers ::isJoin()
* @dataProvider typesProvider
*/
public function testSelectWithWhere($type)
{
$this->setType($type);
$this->database->select("account", [
"name",
"id"
], [
"ORDER" => "age"
]);
$this->assertQuery(
<<<EOD
SELECT "name","id"
FROM "account"
ORDER BY "age"
EOD,
$this->database->queryString
);
}
/**
* @covers ::select()
* @covers ::selectContext()
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithLeftJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]post" => "user_id"
], [
"account.name",
"post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title"
FROM "account"
LEFT JOIN "post"
USING ("user_id")
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithRightJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[<]post" => "user_id"
], [
"account.name",
"post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title"
FROM "account"
RIGHT JOIN "post"
USING ("user_id")
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithFullJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[<>]post" => "user_id"
], [
"account.name",
"post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title"
FROM "account"
FULL JOIN "post"
USING ("user_id")
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithInnerJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[><]post" => "user_id"
], [
"account.name",
"post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title"
FROM "account"
INNER JOIN "post"
USING ("user_id")
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithSameKeysJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]photo" => ["user_id", "avatar_id"],
], [
"account.name",
"photo.link"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","photo"."link"
FROM "account"
LEFT JOIN "photo"
USING ("user_id", "avatar_id")
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithKeyJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]post" => ["user_id" => "author_id"],
], [
"account.name",
"post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title"
FROM "account"
LEFT JOIN "post"
ON "account"."user_id" = "post"."author_id"
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithAliasJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]post (main_post)" => ["user_id" => "author_id"],
], [
"account.name",
"main_post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","main_post"."title"
FROM "account"
LEFT JOIN "post" @AS "main_post"
ON "account"."user_id" = "main_post"."author_id"
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithReferJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]post" => ["user_id" => "author_id"],
"[>]album" => ["post.author_id" => "user_id"],
], [
"account.name",
"post.title",
"album.link"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title","album"."link"
FROM "account"
LEFT JOIN "post"
ON "account"."user_id" = "post"."author_id"
LEFT JOIN "album"
ON "post"."author_id" = "album"."user_id"
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithMultipleConditionJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]album" => ["author_id" => "user_id"],
"[>]post" => [
"user_id" => "author_id",
"album.user_id" => "owner_id"
]
], [
"account.name",
"post.title",
"album.link"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title","album"."link"
FROM "account"
LEFT JOIN "album"
ON "account"."author_id" = "album"."user_id"
LEFT JOIN "post"
ON "account"."user_id" = "post"."author_id"
AND "album"."user_id" = "post"."owner_id"
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectWithAdditionalConditionJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]post" => [
"user_id" => "author_id",
"AND" => [
"post.id[>]" => 10
]
]
], [
"account.name",
"post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title"
FROM "account"
LEFT JOIN "post"
ON "account"."user_id" = "post"."author_id"
AND "post"."id" > 10
EOD,
$this->database->queryString
);
}
/**
* @covers ::isJoin()
* @covers ::buildJoin()
* @dataProvider typesProvider
*/
public function testSelectRawJoin($type)
{
$this->setType($type);
$this->database->select("account", [
"[>]post" => Medoo::raw("ON <account.user_id> = <post.author_id>")
], [
"account.name",
"post.title"
]);
$this->assertQuery(
<<<EOD
SELECT "account"."name","post"."title"
FROM "account"
LEFT JOIN "post"
ON "account"."user_id" = "post"."author_id"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectAllWithJoin($type)
{
$this->setType($type);
$this->expectException(InvalidArgumentException::class);
$this->database->select("account", [
"[>]post" => "user_id"
], [
"account.*"
]);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectWithDataMapping($type)
{
$this->setType($type);
$this->database->select("post", [
"[>]account" => ["user_id"]
], [
"post.content",
"userData" => [
"account.user_id",
"account.email",
"meta" => [
"account.location",
"account.gender"
]
]
]);
$this->assertQuery(
<<<EOD
SELECT "post"."content","account"."user_id","account"."email","account"."location","account"."gender"
FROM "post"
LEFT JOIN "account"
USING ("user_id")
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectWithIndexMapping($type)
{
$this->setType($type);
$this->database->select("account", [
"user_id" => [
"name (nickname)",
"location"
]
]);
$this->assertQuery(
<<<EOD
SELECT "user_id","name" AS "nickname","location"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectWithDistinct($type)
{
$this->setType($type);
$this->database->select("account", [
"@location",
"nickname"
]);
$this->assertQuery(
<<<EOD
SELECT DISTINCT "location","nickname"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectWithDistinctDiffOrder($type)
{
$this->setType($type);
$this->database->select("account", [
"location",
"@nickname"
]);
$this->assertQuery(
<<<EOD
SELECT DISTINCT "nickname","location"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectWithUnicodeCharacter($type)
{
$this->setType($type);
$this->database->select("considérer", [
"name (名前)",
"положение (ロケーション)"
]);
$this->assertQuery(
<<<EOD
SELECT "name" AS "名前","положение" AS "ロケーション"
FROM "considérer"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectWithHyphenCharacter($type)
{
$this->setType($type);
$this->database->select("account", [
"nick-name"
]);
$this->assertQuery(
<<<EOD
SELECT "nick-name"
FROM "account"
EOD,
$this->database->queryString
);
}
/**
* @covers ::columnMap()
* @covers ::columnPush()
* @dataProvider typesProvider
*/
public function testSelectWithSingleCharacter($type)
{
$this->setType($type);
$this->database->select("a", [
"[>]e" => ["f"]
], [
"b (c)"
]);
$this->assertQuery(
<<<EOD
SELECT "b" AS "c"
FROM "a"
LEFT JOIN "e" USING ("f")
EOD,
$this->database->queryString
);
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace Medoo\Tests;
use Medoo\Medoo;
/**
* @coversDefaultClass \Medoo\Medoo
*/
class UpdateTest extends MedooTestCase
{
/**
* @covers \Medoo\Medoo::update()
* @dataProvider typesProvider
*/
public function testUpdate($type)
{
$this->setType($type);
$objectData = new Foo();
$this->database->update("account", [
"type" => "user",
"money" => 23.2,
"age[+]" => 1,
"level[-]" => 5,
"score[*]" => 2,
"lang" => ["en", "fr"],
"lang [JSON]" => ["en", "fr"],
"is_locked" => true,
"uuid" => Medoo::raw("UUID()"),
"object" => $objectData
], [
"user_id[<]" => 1000
]);
$this->assertQuery([
'default' => <<<EOD
UPDATE "account"
SET "type" = 'user',
"money" = '23.2',
"age" = "age" + 1,
"level" = "level" - 5,
"score" = "score" * 2,
"lang" = 'a:2:{i:0;s:2:"en";i:1;s:2:"fr";}',
"lang" = '["en","fr"]',
"is_locked" = 1,
"uuid" = UUID(),
"object" = :MeD5_mK
WHERE "user_id" < 1000
EOD,
'mysql' => <<<EOD
UPDATE "account"
SET "type" = 'user',
"money" = '23.2',
"age" = "age" + 1,
"level" = "level" - 5,
"score" = "score" * 2,
"lang" = 'a:2:{i:0;s:2:\"en\";i:1;s:2:\"fr\";}',
"lang" = '[\"en\",\"fr\"]',
"is_locked" = 1,
"uuid" = UUID(),
"object" = :MeD5_mK
WHERE "user_id" < 1000
EOD,
], $this->database->queryString);
}
public function testOracleLOBsUpdate()
{
$this->setType("oracle");
$fp = fopen('README.md', 'r');
$this->database->update("ACCOUNT", [
"DATA" => $fp
], [
"ID" => 1
]);
$this->assertQuery(
<<<EOD
UPDATE "ACCOUNT"
SET "DATA" = EMPTY_BLOB()
WHERE "ID" = 1
RETURNING "DATA" INTO :MeD0_mK
EOD,
$this->database->queryString
);
}
}
File diff suppressed because it is too large Load Diff
+4
View File
@@ -6,5 +6,9 @@ $vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'f88f8987adfe3f7cf9978fa9a9d148bc' => $vendorDir . '/workerman/psr7/src/functions_include.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
);
+8
View File
@@ -7,8 +7,16 @@ $baseDir = dirname($vendorDir);
return array(
'kornrunner\\' => array($vendorDir . '/kornrunner/keccak/src'),
'Workerman\\Psr7\\' => array($vendorDir . '/workerman/psr7/src'),
'Workerman\\Http\\' => array($vendorDir . '/workerman/http-client/src'),
'Workerman\\' => array($vendorDir . '/workerman/workerman'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
'Medoo\\' => array($vendorDir . '/catfan/medoo/src'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
'GlobalData\\' => array($vendorDir . '/workerman/globaldata/src'),
'Elliptic\\' => array($vendorDir . '/simplito/elliptic-php/lib'),
'BN\\' => array($vendorDir . '/simplito/bn-php/lib'),
+51
View File
@@ -7,7 +7,11 @@ namespace Composer\Autoload;
class ComposerStaticInit54847d6030d29731b0e767d050d22a36
{
public static $files = array (
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'f88f8987adfe3f7cf9978fa9a9d148bc' => __DIR__ . '/..' . '/workerman/psr7/src/functions_include.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php',
);
public static $prefixLengthsPsr4 = array (
@@ -17,14 +21,28 @@ class ComposerStaticInit54847d6030d29731b0e767d050d22a36
),
'W' =>
array (
'Workerman\\Psr7\\' => 15,
'Workerman\\Http\\' => 15,
'Workerman\\' => 10,
),
'S' =>
array (
'Symfony\\Polyfill\\Mbstring\\' => 26,
),
'P' =>
array (
'Psr\\Http\\Message\\' => 17,
'Psr\\Http\\Client\\' => 16,
),
'M' =>
array (
'Medoo\\' => 6,
),
'G' =>
array (
'GuzzleHttp\\Psr7\\' => 16,
'GuzzleHttp\\Promise\\' => 19,
'GuzzleHttp\\' => 11,
'GlobalData\\' => 11,
),
'E' =>
@@ -43,6 +61,14 @@ class ComposerStaticInit54847d6030d29731b0e767d050d22a36
array (
0 => __DIR__ . '/..' . '/kornrunner/keccak/src',
),
'Workerman\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/workerman/psr7/src',
),
'Workerman\\Http\\' =>
array (
0 => __DIR__ . '/..' . '/workerman/http-client/src',
),
'Workerman\\' =>
array (
0 => __DIR__ . '/..' . '/workerman/workerman',
@@ -51,6 +77,31 @@ class ComposerStaticInit54847d6030d29731b0e767d050d22a36
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Http\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-client/src',
),
'Medoo\\' =>
array (
0 => __DIR__ . '/..' . '/catfan/medoo/src',
),
'GuzzleHttp\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
),
'GuzzleHttp\\Promise\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/promises/src',
),
'GuzzleHttp\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src',
),
'GlobalData\\' =>
array (
0 => __DIR__ . '/..' . '/workerman/globaldata/src',
+803
View File
@@ -1,5 +1,418 @@
{
"packages": [
{
"name": "catfan/medoo",
"version": "v2.2.0",
"version_normalized": "2.2.0.0",
"source": {
"type": "git",
"url": "https://github.com/catfan/Medoo.git",
"reference": "347515fe63339387738c5c1c93d1d6726cc9774a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/catfan/Medoo/zipball/347515fe63339387738c5c1c93d1d6726cc9774a",
"reference": "347515fe63339387738c5c1c93d1d6726cc9774a",
"shasum": ""
},
"require": {
"ext-pdo": "*",
"php": ">=7.3"
},
"require-dev": {
"phpunit/phpunit": "^9.0"
},
"suggest": {
"ext-pdo_dblib": "For MSSQL or Sybase database on Linux/UNIX platform",
"ext-pdo_mysql": "For MySQL or MariaDB database",
"ext-pdo_oci": "For Oracle database",
"ext-pdo_pqsql": "For PostgreSQL database",
"ext-pdo_sqlite": "For SQLite database",
"ext-pdo_sqlsrv": "For MSSQL database on both Window/Liunx platform"
},
"time": "2025-03-31T07:37:23+00:00",
"type": "framework",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Medoo\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Angel Lai",
"email": "angel@medoo.in"
}
],
"description": "The lightweight PHP database framework to accelerate development",
"homepage": "https://medoo.in",
"keywords": [
"database",
"database library",
"lightweight",
"mariadb",
"mssql",
"mysql",
"oracle",
"php framework",
"postgresql",
"sql",
"sqlite"
],
"support": {
"issues": "https://github.com/catfan/Medoo/issues",
"source": "https://github.com/catfan/Medoo"
},
"funding": [
{
"url": "https://paypal.me/AngelaonLai",
"type": "custom"
},
{
"url": "https://opencollective.com/medoo",
"type": "open_collective"
}
],
"install-path": "../catfan/medoo"
},
{
"name": "guzzlehttp/guzzle",
"version": "7.10.0",
"version_normalized": "7.10.0.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "b51ac707cfa420b7bfd4e4d5e510ba8008e822b4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4",
"reference": "b51ac707cfa420b7bfd4e4d5e510ba8008e822b4",
"shasum": ""
},
"require": {
"ext-json": "*",
"guzzlehttp/promises": "^2.3",
"guzzlehttp/psr7": "^2.8",
"php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2 || ^3.0"
},
"provide": {
"psr/http-client-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"ext-curl": "*",
"guzzle/client-integration-tests": "3.0.2",
"php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.39 || ^9.6.20",
"psr/log": "^1.1 || ^2.0 || ^3.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"
},
"time": "2025-08-23T22:36:01+00:00",
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"installation-source": "dist",
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"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"
}
],
"description": "Guzzle is a PHP HTTP client library",
"keywords": [
"client",
"curl",
"framework",
"http",
"http client",
"psr-18",
"psr-7",
"rest",
"web service"
],
"support": {
"issues": "https://github.com/guzzle/guzzle/issues",
"source": "https://github.com/guzzle/guzzle/tree/7.10.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle",
"type": "tidelift"
}
],
"install-path": "../guzzlehttp/guzzle"
},
{
"name": "guzzlehttp/promises",
"version": "2.3.0",
"version_normalized": "2.3.0.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "481557b130ef3790cf82b713667b43030dc9c957"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/481557b130ef3790cf82b713667b43030dc9c957",
"reference": "481557b130ef3790cf82b713667b43030dc9c957",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.44 || ^9.6.25"
},
"time": "2025-08-22T14:34:08+00:00",
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"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": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
}
],
"description": "Guzzle promises library",
"keywords": [
"promise"
],
"support": {
"issues": "https://github.com/guzzle/promises/issues",
"source": "https://github.com/guzzle/promises/tree/2.3.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises",
"type": "tidelift"
}
],
"install-path": "../guzzlehttp/promises"
},
{
"name": "guzzlehttp/psr7",
"version": "2.8.0",
"version_normalized": "2.8.0.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "21dc724a0583619cd1652f673303492272778051"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/21dc724a0583619cd1652f673303492272778051",
"reference": "21dc724a0583619cd1652f673303492272778051",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.1 || ^2.0",
"ralouphie/getallheaders": "^3.0"
},
"provide": {
"psr/http-factory-implementation": "1.0",
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"http-interop/http-factory-tests": "0.9.0",
"phpunit/phpunit": "^8.5.44 || ^9.6.25"
},
"suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
},
"time": "2025-08-23T21:21:41+00:00",
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"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": "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"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://sagikazarmark.hu"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"psr-7",
"request",
"response",
"stream",
"uri",
"url"
],
"support": {
"issues": "https://github.com/guzzle/psr7/issues",
"source": "https://github.com/guzzle/psr7/tree/2.8.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7",
"type": "tidelift"
}
],
"install-path": "../guzzlehttp/psr7"
},
{
"name": "kornrunner/keccak",
"version": "1.1.0",
@@ -52,6 +465,222 @@
},
"install-path": "../kornrunner/keccak"
},
{
"name": "psr/http-client",
"version": "1.0.3",
"version_normalized": "1.0.3.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-client.git",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90",
"shasum": ""
},
"require": {
"php": "^7.0 || ^8.0",
"psr/http-message": "^1.0 || ^2.0"
},
"time": "2023-09-23T14:17:50+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP clients",
"homepage": "https://github.com/php-fig/http-client",
"keywords": [
"http",
"http-client",
"psr",
"psr-18"
],
"support": {
"source": "https://github.com/php-fig/http-client"
},
"install-path": "../psr/http-client"
},
{
"name": "psr/http-factory",
"version": "1.1.0",
"version_normalized": "1.1.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"shasum": ""
},
"require": {
"php": ">=7.1",
"psr/http-message": "^1.0 || ^2.0"
},
"time": "2024-04-15T12:06:14+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-factory"
},
"install-path": "../psr/http-factory"
},
{
"name": "psr/http-message",
"version": "2.0",
"version_normalized": "2.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"time": "2023-04-04T09:54:51+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-message/tree/2.0"
},
"install-path": "../psr/http-message"
},
{
"name": "ralouphie/getallheaders",
"version": "3.0.3",
"version_normalized": "3.0.3.0",
"source": {
"type": "git",
"url": "https://github.com/ralouphie/getallheaders.git",
"reference": "120b605dfeb996808c31b6477290a714d356e822"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822",
"reference": "120b605dfeb996808c31b6477290a714d356e822",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"require-dev": {
"php-coveralls/php-coveralls": "^2.1",
"phpunit/phpunit": "^5 || ^6.5"
},
"time": "2019-03-08T08:55:37+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"src/getallheaders.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ralph Khattar",
"email": "ralph.khattar@gmail.com"
}
],
"description": "A polyfill for getallheaders.",
"support": {
"issues": "https://github.com/ralouphie/getallheaders/issues",
"source": "https://github.com/ralouphie/getallheaders/tree/develop"
},
"install-path": "../ralouphie/getallheaders"
},
{
"name": "simplito/bigint-wrapper-php",
"version": "1.0.0",
@@ -208,6 +837,76 @@
},
"install-path": "../simplito/elliptic-php"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.0.2",
"version_normalized": "3.0.2.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/26954b3d62a6c5fd0ea8a2a00c0353a14978d05c",
"reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c",
"shasum": ""
},
"require": {
"php": ">=8.0.2"
},
"time": "2022-01-02T09:55:41+00:00",
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/contracts",
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.0-dev"
}
},
"installation-source": "dist",
"autoload": {
"files": [
"function.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.0.2"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/deprecation-contracts"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.33.0",
@@ -333,6 +1032,110 @@
},
"install-path": "../workerman/globaldata"
},
{
"name": "workerman/http-client",
"version": "v2.2.9",
"version_normalized": "2.2.9.0",
"source": {
"type": "git",
"url": "https://github.com/workerman-php/http-client.git",
"reference": "d26b4b16feb8089df132ce6befce28cb7ff467b6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/workerman-php/http-client/zipball/d26b4b16feb8089df132ce6befce28cb7ff467b6",
"reference": "d26b4b16feb8089df132ce6befce28cb7ff467b6",
"shasum": ""
},
"require": {
"workerman/psr7": ">=1.4.3",
"workerman/workerman": "^4.1.0||^5.0.0||dev-master"
},
"time": "2025-01-19T12:22:04+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Workerman\\Http\\": "./src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"homepage": "http://www.workerman.net",
"support": {
"issues": "https://github.com/workerman-php/http-client/issues",
"source": "https://github.com/workerman-php/http-client/tree/v2.2.9"
},
"install-path": "../workerman/http-client"
},
{
"name": "workerman/psr7",
"version": "v2.0.2",
"version_normalized": "2.0.2.0",
"source": {
"type": "git",
"url": "https://github.com/walkor/psr7.git",
"reference": "5f5b65e2462cd408f738cc967a80d8c15f9b57f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/walkor/psr7/zipball/5f5b65e2462cd408f738cc967a80d8c15f9b57f3",
"reference": "5f5b65e2462cd408f738cc967a80d8c15f9b57f3",
"shasum": ""
},
"require": {
"php": ">=7.2.0",
"psr/http-message": "~2.0"
},
"provide": {
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"time": "2025-03-06T12:00:37+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"Workerman\\Psr7\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Tobias Schultze",
"homepage": "https://github.com/Tobion"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"request",
"response",
"stream",
"uri",
"url"
],
"support": {
"source": "https://github.com/walkor/psr7/tree/v2.0.2"
},
"install-path": "../workerman/psr7"
},
{
"name": "workerman/workerman",
"version": "v4.2.1",
+123 -6
View File
@@ -1,9 +1,9 @@
<?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => NULL,
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'reference' => '7a3b2960f84d779879ed473d2589221d1be820fc',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -11,14 +11,50 @@
),
'versions' => array(
'__root__' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => NULL,
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'reference' => '7a3b2960f84d779879ed473d2589221d1be820fc',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'catfan/medoo' => array(
'pretty_version' => 'v2.2.0',
'version' => '2.2.0.0',
'reference' => '347515fe63339387738c5c1c93d1d6726cc9774a',
'type' => 'framework',
'install_path' => __DIR__ . '/../catfan/medoo',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/guzzle' => array(
'pretty_version' => '7.10.0',
'version' => '7.10.0.0',
'reference' => 'b51ac707cfa420b7bfd4e4d5e510ba8008e822b4',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/guzzle',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/promises' => array(
'pretty_version' => '2.3.0',
'version' => '2.3.0.0',
'reference' => '481557b130ef3790cf82b713667b43030dc9c957',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/promises',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/psr7' => array(
'pretty_version' => '2.8.0',
'version' => '2.8.0.0',
'reference' => '21dc724a0583619cd1652f673303492272778051',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/psr7',
'aliases' => array(),
'dev_requirement' => false,
),
'kornrunner/keccak' => array(
'pretty_version' => '1.1.0',
'version' => '1.1.0.0',
@@ -28,6 +64,60 @@
'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.0',
),
),
'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 => '1.0',
),
),
'ralouphie/getallheaders' => array(
'pretty_version' => '3.0.3',
'version' => '3.0.3.0',
'reference' => '120b605dfeb996808c31b6477290a714d356e822',
'type' => 'library',
'install_path' => __DIR__ . '/../ralouphie/getallheaders',
'aliases' => array(),
'dev_requirement' => false,
),
'simplito/bigint-wrapper-php' => array(
'pretty_version' => '1.0.0',
'version' => '1.0.0.0',
@@ -55,6 +145,15 @@
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/deprecation-contracts' => array(
'pretty_version' => 'v3.0.2',
'version' => '3.0.2.0',
'reference' => '26954b3d62a6c5fd0ea8a2a00c0353a14978d05c',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/deprecation-contracts',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-mbstring' => array(
'pretty_version' => 'v1.33.0',
'version' => '1.33.0.0',
@@ -73,6 +172,24 @@
'aliases' => array(),
'dev_requirement' => false,
),
'workerman/http-client' => array(
'pretty_version' => 'v2.2.9',
'version' => '2.2.9.0',
'reference' => 'd26b4b16feb8089df132ce6befce28cb7ff467b6',
'type' => 'library',
'install_path' => __DIR__ . '/../workerman/http-client',
'aliases' => array(),
'dev_requirement' => false,
),
'workerman/psr7' => array(
'pretty_version' => 'v2.0.2',
'version' => '2.0.2.0',
'reference' => '5f5b65e2462cd408f738cc967a80d8c15f9b57f3',
'type' => 'library',
'install_path' => __DIR__ . '/../workerman/psr7',
'aliases' => array(),
'dev_requirement' => false,
),
'workerman/workerman' => array(
'pretty_version' => 'v4.2.1',
'version' => '4.2.1.0',
+2 -2
View File
@@ -4,8 +4,8 @@
$issues = array();
if (!(PHP_VERSION_ID >= 80000)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.0". You are running ' . PHP_VERSION . '.';
if (!(PHP_VERSION_ID >= 80002)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.2". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
File diff suppressed because it is too large Load Diff
+27
View File
@@ -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.
+94
View File
@@ -0,0 +1,94 @@
![Guzzle](.github/logo.png?raw=true)
# Guzzle, PHP HTTP client
[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases)
[![Build Status](https://img.shields.io/github/actions/workflow/status/guzzle/guzzle/ci.yml?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI)
[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle)
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 between 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.
```php
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
```
## Help and docs
We use GitHub issues only to discuss bugs and new features. For support please refer to:
- [Documentation](https://docs.guzzlephp.org)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle)
- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/)
- [Gitter](https://gitter.im/guzzle/guzzle)
## Installing Guzzle
The recommended way to install Guzzle is through
[Composer](https://getcomposer.org/).
```bash
composer require guzzlehttp/guzzle
```
## Version Guidance
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version |
|---------|---------------------|---------------------|--------------|---------------------|---------------------|-------|--------------|
| 3.x | EOL (2016-10-31) | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 |
| 4.x | EOL (2016-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 |
| 5.x | EOL (2019-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 |
| 6.x | EOL (2023-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 |
| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.5 |
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5
[guzzle-7-repo]: https://github.com/guzzle/guzzle
[guzzle-3-docs]: https://guzzle3.readthedocs.io/
[guzzle-5-docs]: https://docs.guzzlephp.org/en/5.3/
[guzzle-6-docs]: https://docs.guzzlephp.org/en/6.5/
[guzzle-7-docs]: https://docs.guzzlephp.org/en/latest/
## 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. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information.
## 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)
File diff suppressed because it is too large Load Diff
+131
View File
@@ -0,0 +1,131 @@
{
"name": "guzzlehttp/guzzle",
"description": "Guzzle is a PHP HTTP client library",
"keywords": [
"framework",
"http",
"rest",
"web service",
"curl",
"client",
"HTTP client",
"PSR-7",
"PSR-18"
],
"license": "MIT",
"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"
}
],
"repositories": [
{
"type": "package",
"package": {
"name": "guzzle/client-integration-tests",
"version": "v3.0.2",
"dist": {
"url": "https://codeload.github.com/guzzle/client-integration-tests/zip/2c025848417c1135031fdf9c728ee53d0a7ceaee",
"type": "zip"
},
"require": {
"php": "^7.2.5 || ^8.0",
"phpunit/phpunit": "^7.5.20 || ^8.5.8 || ^9.3.11",
"php-http/message": "^1.0 || ^2.0",
"guzzlehttp/psr7": "^1.7 || ^2.0",
"th3n3rd/cartesian-product": "^0.3"
},
"autoload": {
"psr-4": {
"Http\\Client\\Tests\\": "src/"
}
},
"bin": [
"bin/http_test_server"
]
}
}
],
"require": {
"php": "^7.2.5 || ^8.0",
"ext-json": "*",
"guzzlehttp/promises": "^2.3",
"guzzlehttp/psr7": "^2.8",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2 || ^3.0"
},
"provide": {
"psr/http-client-implementation": "1.0"
},
"require-dev": {
"ext-curl": "*",
"bamarni/composer-bin-plugin": "^1.8.2",
"guzzle/client-integration-tests": "3.0.2",
"php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.39 || ^9.6.20",
"psr/log": "^1.1 || ^2.0 || ^3.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"
},
"config": {
"allow-plugins": {
"bamarni/composer-bin-plugin": true
},
"preferred-install": "dist",
"sort-packages": true
},
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\": "tests/"
}
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"name": "guzzle",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
final class BodySummarizer implements BodySummarizerInterface
{
/**
* @var int|null
*/
private $truncateAt;
public function __construct(?int $truncateAt = null)
{
$this->truncateAt = $truncateAt;
}
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string
{
return $this->truncateAt === null
? Psr7\Message::bodySummary($message)
: Psr7\Message::bodySummary($message, $this->truncateAt);
}
}
@@ -0,0 +1,13 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
interface BodySummarizerInterface
{
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string;
}
+483
View File
@@ -0,0 +1,483 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* @final
*/
class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
{
use ClientTrait;
/**
* @var array Default request options
*/
private $config;
/**
* Clients accept an array of constructor parameters.
*
* Here's an example of creating a client using a base_uri and an array of
* default request options to apply to each request:
*
* $client = new Client([
* 'base_uri' => 'http://www.foo.com/1.0/',
* 'timeout' => 0,
* 'allow_redirects' => false,
* 'proxy' => '192.168.16.1:10'
* ]);
*
* Client configuration settings include the following options:
*
* - handler: (callable) Function that transfers HTTP requests over the
* wire. The function is called with a Psr7\Http\Message\RequestInterface
* and array of transfer options, and must return a
* GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
* Psr7\Http\Message\ResponseInterface on success.
* If no handler is provided, a default handler will be created
* that enables all of the request options below by attaching all of the
* default middleware to the handler.
* - base_uri: (string|UriInterface) Base URI of the client that is merged
* into relative URIs. Can be a string or instance of UriInterface.
* - **: any request option
*
* @param array $config Client configuration settings.
*
* @see RequestOptions for a list of available request options.
*/
public function __construct(array $config = [])
{
if (!isset($config['handler'])) {
$config['handler'] = HandlerStack::create();
} elseif (!\is_callable($config['handler'])) {
throw new InvalidArgumentException('handler must be a callable');
}
// Convert the base_uri to a UriInterface
if (isset($config['base_uri'])) {
$config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']);
}
$this->configureDefaults($config);
}
/**
* @param string $method
* @param array $args
*
* @return PromiseInterface|ResponseInterface
*
* @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0.
*/
public function __call($method, $args)
{
if (\count($args) < 1) {
throw new InvalidArgumentException('Magic request methods require a URI and optional options array');
}
$uri = $args[0];
$opts = $args[1] ?? [];
return \substr($method, -5) === 'Async'
? $this->requestAsync(\substr($method, 0, -5), $uri, $opts)
: $this->request($method, $uri, $opts);
}
/**
* Asynchronously send an HTTP request.
*
* @param array $options Request options to apply to the given
* request and to the transfer. See \GuzzleHttp\RequestOptions.
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
{
// Merge the base URI into the request URI if needed.
$options = $this->prepareDefaults($options);
return $this->transfer(
$request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
$options
);
}
/**
* Send an HTTP request.
*
* @param array $options Request options to apply to the given
* request and to the transfer. See \GuzzleHttp\RequestOptions.
*
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->sendAsync($request, $options)->wait();
}
/**
* The HttpClient PSR (PSR-18) specify this method.
*
* {@inheritDoc}
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
$options[RequestOptions::ALLOW_REDIRECTS] = false;
$options[RequestOptions::HTTP_ERRORS] = false;
return $this->sendAsync($request, $options)->wait();
}
/**
* 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply. See \GuzzleHttp\RequestOptions.
*/
public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface
{
$options = $this->prepareDefaults($options);
// Remove request modifying parameter because it can be done up-front.
$headers = $options['headers'] ?? [];
$body = $options['body'] ?? null;
$version = $options['version'] ?? '1.1';
// Merge the URI into the base URI.
$uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options);
if (\is_array($body)) {
throw $this->invalidBody();
}
$request = new Psr7\Request($method, $uri, $headers, $body, $version);
// Remove the option so that they are not doubly-applied.
unset($options['headers'], $options['body'], $options['version']);
return $this->transfer($request, $options);
}
/**
* 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 $options Request options to apply. See \GuzzleHttp\RequestOptions.
*
* @throws GuzzleException
*/
public function request(string $method, $uri = '', array $options = []): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->requestAsync($method, $uri, $options)->wait();
}
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*
* @deprecated Client::getConfig will be removed in guzzlehttp/guzzle:8.0.
*/
public function getConfig(?string $option = null)
{
return $option === null
? $this->config
: ($this->config[$option] ?? null);
}
private function buildUri(UriInterface $uri, array $config): UriInterface
{
if (isset($config['base_uri'])) {
$uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri);
}
if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) {
$idnOptions = ($config['idn_conversion'] === true) ? \IDNA_DEFAULT : $config['idn_conversion'];
$uri = Utils::idnUriConvert($uri, $idnOptions);
}
return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
}
/**
* Configures the default options for a client.
*/
private function configureDefaults(array $config): void
{
$defaults = [
'allow_redirects' => RedirectMiddleware::$defaultSettings,
'http_errors' => true,
'decode_content' => true,
'verify' => true,
'cookies' => false,
'idn_conversion' => false,
];
// Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
// We can only trust the HTTP_PROXY environment variable in a CLI
// process due to the fact that PHP has no reliable mechanism to
// get environment variables that start with "HTTP_".
if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) {
$defaults['proxy']['http'] = $proxy;
}
if ($proxy = Utils::getenv('HTTPS_PROXY')) {
$defaults['proxy']['https'] = $proxy;
}
if ($noProxy = Utils::getenv('NO_PROXY')) {
$cleanedNoProxy = \str_replace(' ', '', $noProxy);
$defaults['proxy']['no'] = \explode(',', $cleanedNoProxy);
}
$this->config = $config + $defaults;
if (!empty($config['cookies']) && $config['cookies'] === true) {
$this->config['cookies'] = new CookieJar();
}
// Add the default user-agent header.
if (!isset($this->config['headers'])) {
$this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()];
} else {
// Add the User-Agent header if one was not already set.
foreach (\array_keys($this->config['headers']) as $name) {
if (\strtolower($name) === 'user-agent') {
return;
}
}
$this->config['headers']['User-Agent'] = Utils::defaultUserAgent();
}
}
/**
* Merges default options into the array.
*
* @param array $options Options to modify by reference
*/
private function prepareDefaults(array $options): array
{
$defaults = $this->config;
if (!empty($defaults['headers'])) {
// Default headers are only added if they are not present.
$defaults['_conditional'] = $defaults['headers'];
unset($defaults['headers']);
}
// Special handling for headers is required as they are added as
// conditional headers and as headers passed to a request ctor.
if (\array_key_exists('headers', $options)) {
// Allows default headers to be unset.
if ($options['headers'] === null) {
$defaults['_conditional'] = [];
unset($options['headers']);
} elseif (!\is_array($options['headers'])) {
throw new InvalidArgumentException('headers must be an array');
}
}
// Shallow merge defaults underneath options.
$result = $options + $defaults;
// Remove null values.
foreach ($result as $k => $v) {
if ($v === null) {
unset($result[$k]);
}
}
return $result;
}
/**
* Transfers the given request and applies request options.
*
* The URI of the request is not modified and the request options are used
* as-is without merging in default options.
*
* @param array $options See \GuzzleHttp\RequestOptions.
*/
private function transfer(RequestInterface $request, array $options): PromiseInterface
{
$request = $this->applyOptions($request, $options);
/** @var HandlerStack $handler */
$handler = $options['handler'];
try {
return P\Create::promiseFor($handler($request, $options));
} catch (\Exception $e) {
return P\Create::rejectionFor($e);
}
}
/**
* Applies the array of request options to a request.
*/
private function applyOptions(RequestInterface $request, array &$options): RequestInterface
{
$modify = [
'set_headers' => [],
];
if (isset($options['headers'])) {
if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) {
throw new InvalidArgumentException('The headers array must have header name as keys.');
}
$modify['set_headers'] = $options['headers'];
unset($options['headers']);
}
if (isset($options['form_params'])) {
if (isset($options['multipart'])) {
throw new InvalidArgumentException('You cannot use '
.'form_params and multipart at the same time. Use the '
.'form_params option if you want to send application/'
.'x-www-form-urlencoded requests, and the multipart '
.'option to send multipart/form-data requests.');
}
$options['body'] = \http_build_query($options['form_params'], '', '&');
unset($options['form_params']);
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (isset($options['multipart'])) {
$options['body'] = new Psr7\MultipartStream($options['multipart']);
unset($options['multipart']);
}
if (isset($options['json'])) {
$options['body'] = Utils::jsonEncode($options['json']);
unset($options['json']);
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'application/json';
}
if (!empty($options['decode_content'])
&& $options['decode_content'] !== true
) {
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']);
$modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
}
if (isset($options['body'])) {
if (\is_array($options['body'])) {
throw $this->invalidBody();
}
$modify['body'] = Psr7\Utils::streamFor($options['body']);
unset($options['body']);
}
if (!empty($options['auth']) && \is_array($options['auth'])) {
$value = $options['auth'];
$type = isset($value[2]) ? \strtolower($value[2]) : 'basic';
switch ($type) {
case 'basic':
// Ensure that we don't have the header in different case and set the new value.
$modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']);
$modify['set_headers']['Authorization'] = 'Basic '
.\base64_encode("$value[0]:$value[1]");
break;
case 'digest':
// @todo: Do not rely on curl
$options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST;
$options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
break;
case 'ntlm':
$options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM;
$options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
break;
}
}
if (isset($options['query'])) {
$value = $options['query'];
if (\is_array($value)) {
$value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986);
}
if (!\is_string($value)) {
throw new InvalidArgumentException('query must be a string or array');
}
$modify['query'] = $value;
unset($options['query']);
}
// Ensure that sink is not an invalid value.
if (isset($options['sink'])) {
// TODO: Add more sink validation?
if (\is_bool($options['sink'])) {
throw new InvalidArgumentException('sink must not be a boolean');
}
}
if (isset($options['version'])) {
$modify['version'] = $options['version'];
}
$request = Psr7\Utils::modifyRequest($request, $modify);
if ($request->getBody() instanceof Psr7\MultipartStream) {
// Use a multipart/form-data POST if a Content-Type is not set.
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
.$request->getBody()->getBoundary();
}
// Merge in conditional headers if they are not present.
if (isset($options['_conditional'])) {
// Build up the changes so it's in a single clone of the message.
$modify = [];
foreach ($options['_conditional'] as $k => $v) {
if (!$request->hasHeader($k)) {
$modify['set_headers'][$k] = $v;
}
}
$request = Psr7\Utils::modifyRequest($request, $modify);
// Don't pass this internal value along to middleware/handlers.
unset($options['_conditional']);
}
return $request;
}
/**
* Return an InvalidArgumentException with pre-set message.
*/
private function invalidBody(): InvalidArgumentException
{
return new InvalidArgumentException('Passing in the "body" request '
.'option as an array to send a request is not supported. '
.'Please use the "form_params" request option to send a '
.'application/x-www-form-urlencoded request, or the "multipart" '
.'request option to send a multipart/form-data request.');
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
interface ClientInterface
{
/**
* The Guzzle major version.
*/
public const MAJOR_VERSION = 7;
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $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 $options Request options to apply to the given
* request and to the transfer.
*/
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 $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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*
* @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0.
*/
public function getConfig(?string $option = null);
}
+241
View File
@@ -0,0 +1,241 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
trait ClientTrait
{
/**
* 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 $options Request options to apply.
*
* @throws GuzzleException
*/
abstract public function request(string $method, $uri, array $options = []): ResponseInterface;
/**
* Create and send an HTTP GET 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|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function get($uri, array $options = []): ResponseInterface
{
return $this->request('GET', $uri, $options);
}
/**
* Create and send an HTTP HEAD 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|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function head($uri, array $options = []): ResponseInterface
{
return $this->request('HEAD', $uri, $options);
}
/**
* Create and send an HTTP PUT 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|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function put($uri, array $options = []): ResponseInterface
{
return $this->request('PUT', $uri, $options);
}
/**
* Create and send an HTTP POST 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|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function post($uri, array $options = []): ResponseInterface
{
return $this->request('POST', $uri, $options);
}
/**
* Create and send an HTTP PATCH 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|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function patch($uri, array $options = []): ResponseInterface
{
return $this->request('PATCH', $uri, $options);
}
/**
* Create and send an HTTP DELETE 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|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function delete($uri, array $options = []): ResponseInterface
{
return $this->request('DELETE', $uri, $options);
}
/**
* 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Create and send an asynchronous HTTP GET 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function getAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('GET', $uri, $options);
}
/**
* Create and send an asynchronous HTTP HEAD 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function headAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('HEAD', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PUT 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function putAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PUT', $uri, $options);
}
/**
* Create and send an asynchronous HTTP POST 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function postAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('POST', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PATCH 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function patchAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PATCH', $uri, $options);
}
/**
* Create and send an asynchronous HTTP DELETE 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. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function deleteAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('DELETE', $uri, $options);
}
}
+307
View File
@@ -0,0 +1,307 @@
<?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Cookie jar that stores cookies as an array
*/
class CookieJar implements CookieJarInterface
{
/**
* @var SetCookie[] Loaded cookie data
*/
private $cookies = [];
/**
* @var bool
*/
private $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, 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(array $cookies, string $domain): self
{
$cookieJar = new self();
foreach ($cookies as $name => $value) {
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $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() !== null && \strcasecmp($cookie->getName(), $name) === 0) {
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) {
$this->cookies = [];
return;
} elseif (!$path) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($domain): bool {
return !$cookie->matchesDomain($domain);
}
);
} elseif (!$name) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain): bool {
return !($cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
} else {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain, $name) {
return !($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(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;
}
// Resolve conflicts with previously set cookies
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->getName() != $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$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(RequestInterface $request, ResponseInterface $response): void
{
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
foreach ($cookieHeader as $cookie) {
$sc = SetCookie::fromString($cookie);
if (!$sc->getDomain()) {
$sc->setDomain($request->getUri()->getHost());
}
if (0 !== \strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
}
if (!$sc->matchesDomain($request->getUri()->getHost())) {
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.
$this->setCookie($sc);
}
}
}
/**
* 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(RequestInterface $request): RequestInterface
{
$values = [];
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
if ($cookie->matchesPath($path)
&& $cookie->matchesDomain($host)
&& !$cookie->isExpired()
&& (!$cookie->getSecure() || $scheme === 'https')
) {
$values[] = $cookie->getName().'='
.$cookie->getValue();
}
}
return $values
? $request->withHeader('Cookie', \implode('; ', $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 === '') {
$this->clear(
$cookie->getDomain(),
$cookie->getPath(),
$cookie->getName()
);
}
}
}
@@ -0,0 +1,80 @@
<?php
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;
}
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Utils;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
/**
* @var string filename
*/
private $filename;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* 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 found or created
*/
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
{
parent::__construct();
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
if (\file_exists($cookieFile)) {
$this->load($cookieFile);
}
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
$this->save($this->filename);
}
/**
* Saves the cookies to a file.
*
* @param string $filename File to save
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function save(string $filename): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
}
}
$jsonStr = Utils::jsonEncode($json);
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
*
* @param string $filename Cookie file to load.
*
* @throws \RuntimeException if the file cannot be loaded.
*/
public function load(string $filename): void
{
$json = \file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException("Unable to load file {$filename}");
}
if ($json === '') {
return;
}
$data = Utils::jsonDecode($json, true);
if (\is_array($data)) {
foreach ($data as $cookie) {
$this->setCookie(new SetCookie($cookie));
}
} elseif (\is_scalar($data) && !empty($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
}
}
@@ -0,0 +1,77 @@
<?php
namespace GuzzleHttp\Cookie;
/**
* Persists cookies in the client session
*/
class SessionCookieJar extends CookieJar
{
/**
* @var string session key
*/
private $sessionKey;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* 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.
*/
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
{
parent::__construct();
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
}
/**
* Saves cookies to session when shutting down
*/
public function __destruct()
{
$this->save();
}
/**
* Save cookies to the client session
*/
public function save(): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
}
}
$_SESSION[$this->sessionKey] = \json_encode($json);
}
/**
* Load the contents of the client session into the data array
*/
protected function load(): void
{
if (!isset($_SESSION[$this->sessionKey])) {
return;
}
$data = \json_decode($_SESSION[$this->sessionKey], true);
if (\is_array($data)) {
foreach ($data as $cookie) {
$this->setCookie(new SetCookie($cookie));
}
} elseif (\strlen($data)) {
throw new \RuntimeException('Invalid cookie data');
}
}
}
+492
View File
@@ -0,0 +1,492 @@
<?php
namespace GuzzleHttp\Cookie;
/**
* Set-Cookie object
*/
class SetCookie
{
/**
* @var array
*/
private static $defaults = [
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
];
/**
* @var array Cookie data
*/
private $data;
/**
* Create a new SetCookie object from a string.
*
* @param string $cookie Set-Cookie header string
*/
public static function fromString(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('trim', \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]);
$value = isset($cookieParts[1])
? \trim($cookieParts[1], " \n\r\t\0\x0B")
: 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 (!\strcasecmp($search, $key)) {
if ($search === 'Max-Age') {
if (is_numeric($value)) {
$data[$search] = (int) $value;
}
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
if ($value) {
$data[$search] = true;
}
} else {
$data[$search] = $value;
}
continue 2;
}
}
$data[$key] = $value;
}
}
return new self($data);
}
/**
* @param array $data Array of cookie data provided by a Cookie parser
*/
public function __construct(array $data = [])
{
$this->data = self::$defaults;
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];
}
// Extract the Expires value and turn it into a UNIX timestamp if needed
if (!$this->getExpires() && $this->getMaxAge()) {
// Calculate the Expires date
$this->setExpires(\time() + $this->getMaxAge());
} elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
$this->setExpires($expires);
}
}
public function __toString()
{
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
foreach ($this->data as $k => $v) {
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
{
return $this->data;
}
/**
* Get the cookie name.
*
* @return string
*/
public function getName()
{
return $this->data['Name'];
}
/**
* Set the cookie name.
*
* @param string $name Cookie name
*/
public function setName($name): void
{
if (!is_string($name)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Name'] = (string) $name;
}
/**
* Get the cookie value.
*
* @return string|null
*/
public function getValue()
{
return $this->data['Value'];
}
/**
* Set the cookie value.
*
* @param string $value Cookie value
*/
public function setValue($value): void
{
if (!is_string($value)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Value'] = (string) $value;
}
/**
* Get the domain.
*
* @return string|null
*/
public function getDomain()
{
return $this->data['Domain'];
}
/**
* Set the domain of the cookie.
*
* @param string|null $domain
*/
public function setDomain($domain): void
{
if (!is_string($domain) && null !== $domain) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Domain'] = null === $domain ? null : (string) $domain;
}
/**
* Get the path.
*
* @return string
*/
public function getPath()
{
return $this->data['Path'];
}
/**
* Set the path of the cookie.
*
* @param string $path Path of the cookie
*/
public function setPath($path): void
{
if (!is_string($path)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Path'] = (string) $path;
}
/**
* Maximum lifetime of the cookie in seconds.
*
* @return int|null
*/
public function getMaxAge()
{
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($maxAge): void
{
if (!is_int($maxAge) && null !== $maxAge) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge;
}
/**
* The UNIX timestamp when the cookie Expires.
*
* @return string|int|null
*/
public function getExpires()
{
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) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp));
}
/**
* Get whether or not this is a secure cookie.
*
* @return bool
*/
public function getSecure()
{
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($secure): void
{
if (!is_bool($secure)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Secure'] = (bool) $secure;
}
/**
* Get whether or not this is a session cookie.
*
* @return bool|null
*/
public function getDiscard()
{
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($discard): void
{
if (!is_bool($discard)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Discard'] = (bool) $discard;
}
/**
* Get whether or not this is an HTTP only cookie.
*
* @return bool
*/
public function getHttpOnly()
{
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($httpOnly): void
{
if (!is_bool($httpOnly)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['HttpOnly'] = (bool) $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) {
return true;
}
// Remove the leading '.' as per spec in RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
$cookieDomain = \ltrim(\strtolower($cookieDomain), '.');
$domain = \strtolower($domain);
// Domain not set or exact match.
if ('' === $cookieDomain || $domain === $cookieDomain) {
return true;
}
// Matching the subdomain according to RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
return false;
}
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain);
}
/**
* 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 bool|string Returns true if valid or an error message if invalid
*/
public function validate()
{
$name = $this->getName();
if ($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
)) {
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 can be 0. "0" is not a valid internet
// domain, but may be used as server name in a private network.
$domain = $this->getDomain();
if ($domain === null || $domain === '') {
return 'The cookie domain must not be empty';
}
return true;
}
}
@@ -0,0 +1,39 @@
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Exception when an HTTP error occurs (4xx or 5xx error)
*/
class BadResponseException extends RequestException
{
public function __construct(
string $message,
<