alexkart / curl-builder
PSR-7 兼容的 curl 构建器。
1.0.9
2024-02-22 11:37 UTC
Requires
- php: >=7.3
- psr/http-message: ^2.0
Requires (Dev)
- nyholm/psr7: ^1.3
- phan/phan: ^5.4
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.5
README
curl-builder 是一个 curl 命令生成器,可以从 PSR-7 服务器请求自动生成 curl 命令,也可以通过指定选项和 URL 手动生成。
安装
composer require alexkart/curl-builder
示例
从 PSR-7 请求生成 curl 命令
$request = new Request('POST', 'http://example.com', [ 'Connection' => ['keep-alive'], 'Accept' => [ 'text/html', 'application/xhtml+xml', ], ], 'data'); $command = new Command(); $command->setRequest($request); $curl = $command->build(); // curl -H 'Connection: keep-alive' -H 'Accept: text/html, application/xhtml+xml' -d 'data' http://example.com
手动构建 curl 命令
$command = new Command(); $command->setUrl('http://example.com'); $command->addOption('-v'); $command->addOption('-H', 'Connection: keep-alive'); $command->addOption('-H', 'Cache-Control: max-age=0'); // curl -v -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' http://example.com
添加选项
可以使用 addOption()
逐个添加选项到命令中
$command->addOption('-L'); $command->addOption('-v'); $command->addOption('-H', 'Connection: keep-alive'); // curl -L -v -H 'Connection: keep-alive' ...
或者使用 addOptions()
一次性添加多个选项
$command->addOption('-v'); $command->addOptions([ '-L', '-d' => 'test' ]); // curl -v -L -d 'test' ...
setOptions()
可以用来覆盖之前设置过的选项
$command->setOptions(['-L', '-v']); // curl -L -v ...
addOptions()
和 setOptions()
格式
// options without arguments // the following lines will generate the same command $command->setOptions(['-L' => [null], '-v' => [null]]); $command->setOptions(['-L' => null, '-v' => null]); $command->setOptions(['-L', '-v']); // curl -L -v ... // options with arguments $command->setOptions(['-H' => 'test']); // curl -H 'test' ... $command->setOptions(['-H' => ['test1', 'test2']]); // curl -H 'test1' -H 'test2'
指定命令模板
命令的默认模板是 {name}{option}{url}
。但您可以使用 setTemplate()
方法来更改它
$command = new Command(); $command->setUrl('http://example.com'); $command->addOption('-v'); $command->addOption('-L'); $curl = $command->build(); // curl -v -L http://example.com // change order $command->setTemplate(Command::TEMPLATE_COMMAND_NAME . Command::TEMPLATE_URL . Command::TEMPLATE_OPTIONS); $curl = $command->build(); // curl http://example.com -v -L // remove options $command->setTemplate(Command::TEMPLATE_COMMAND_NAME . Command::TEMPLATE_URL); $curl = $command->build(); // curl http://example.com
引号和转义参数
默认情况下,参数使用单引号引号,如果参数中出现单引号,则会被转义
$command->addOption('-d', 'data'); // curl -d 'data' $command->addOption('-d', "data'1"); // curl -d $'data\'1'
引号字符可以更改为双引号或移除
$command->addOption('-d', 'data1'); $command->addOption('-d', 'data"2'); $command->setQuoteCharacter(Command::QUOTE_CHARACTER_DOUBLE); // curl -d "data" -d "data\"2" $command->addOption('-d', 'data'); $command->setQuoteCharacter(Command::QUOTE_CHARACTER_NONE); // curl -d data