germania-kg / client-location
用于存储客户端位置的PSR-15中间件
1.1.7
2022-03-30 09:55 UTC
Requires
- php: ^7.3|^8.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
- psr/log: ^1.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-log: ^2.13
- nyholm/psr7: ^1.3
- php-coveralls/php-coveralls: ^2.0
- phpspec/prophecy-phpunit: ^2.0
- phpunit/phpunit: ^9.0
- slim/psr7: ^1.2
README
Germania KG · ClientLocation
安装
$ composer require germania-kg/client-location
PSR-15 中间件
该中间件检查传入的 ServerRequest 是否具有 client-ip
属性。客户端IP地址传递给 factory callable,它返回一些位置信息。然后将客户端位置存储在 ServerRequest 的 client-location
属性中。
如果 client-ip
属性未设置或为空,则中间件不执行任何操作,并传递给 RequestHandler。
ClientIpLocationMiddleware 实现了 PSR-15 MiddlewareInterface。构造函数需要以下内容:
- 工厂可调用 接受客户端的IP地址并实际确定客户端位置。建议:使用下面的 HttpClientLocationCreator。
- PSR-3 记录器 用于错误。
- 可以添加可选的 PSR-3 错误日志级别名称。默认为
LogLevel::ERROR
<?php use Germania\ClientIpLocation\ClientIpLocationMiddleware; use Psr\Log\LogLevel; $fn = function($ip) { return "Berlin"; }; $logger = new Monolog(...); $middleware = new ClientIpLocationMiddleware($fn, $logger); $middleware = new ClientIpLocationMiddleware($fn, $logger, LogLevel::ERROR);
配置
这两个属性名称都可以重命名。这里使用默认值
$middleware->setClientIpAttributeName("client-ip") ->setClientLocationAttributeName("client-location");
HttpClientLocationCreator
HttpClientLocationCreator 是一个可调用的类,它接受客户端IP地址并返回客户端位置。其构造函数需要以下内容:
API端点应该包含一个 {{ip}}
模板变量,其中放置客户端IP地址。
<?php use Germania\ClientIpLocation\HttpClientLocationCreator; use Psr\Http\Client\ClientInterface; use Nyholm\Psr7\Factory\Psr17Factory; $api = "https://api.geocoder.test/location?ip={{ip}}"; $http_client = new \Http\Adapter\Guzzle6\Client( new \GuzzleHttp\Client ); $request_factory = new Psr17Factory; $creator = new HttpClientLocationCreator($api, $psr18_client, $request_factory);
配置
设置自定义API响应解码器
默认情况下,响应将作为关联数组进行 json_decoded。您可以指定自定义响应解码器
use Psr\Http\Message\ResponseInterface; $decoder = function(ResponseInterface $response) { return json_decode($response->getBody(), "assoc"); }; // Pass with constructor $creator = new HttpClientLocationCreator($api, $psr18_client, $request_factory, $decoder); // ...or $creator->setResponseDecoder( $decoder );
当HTTP客户端抛出异常时,设置默认位置返回
$creator->setDefaultLocation("Berlin");
设置PSR-3记录器
$logger = new Monolog(...); // Pass with constructor $creator = new HttpClientLocationCreator($api, $psr18_client, $request_factory, $decoder, $logger); // ...or $creator->setLogger( $logger );
问题
请参阅 完整问题列表。
开发
使用以下之一进行抓取和运行
$ git clone git@github.com:GermaniaKG/ClientLocation.git $ gh repo clone GermaniaKG/ClientLocation
单元测试
要么将 phpunit.xml.dist
复制到 phpunit.xml
并根据您的需要进行调整,要么保持不变。运行 PhpUnit 测试或composer脚本如下
$ composer test # or $ vendor/bin/phpunit