Skip to content

Commit

Permalink
添加自定义ScopingHttpClient降低使用复杂度 (#2766)
Browse files Browse the repository at this point in the history
  • Loading branch information
hughcube committed Dec 14, 2023
1 parent e0fba6c commit 557409d
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
61 changes: 61 additions & 0 deletions src/Kernel/HttpClient/ScopingHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

namespace EasyWeChat\Kernel\HttpClient;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\HttpClientTrait;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
use Symfony\Contracts\Service\ResetInterface;

class ScopingHttpClient implements HttpClientInterface, ResetInterface, LoggerAwareInterface
{
use HttpClientTrait;

private HttpClientInterface $client;
private array $defaultOptionsByRegexp;

public function __construct(HttpClientInterface $client, array $defaultOptionsByRegexp)
{
$this->client = $client;
$this->defaultOptionsByRegexp = $defaultOptionsByRegexp;
}

public function request(string $method, string $url, array $options = []): ResponseInterface
{
foreach ($this->defaultOptionsByRegexp as $regexp => $defaultOptions) {
if (preg_match($regexp, $url)) {
$options = self::mergeDefaultOptions($options, $defaultOptions, true);
break;
}
}

return $this->client->request($method, $url, $options);
}

public function stream(ResponseInterface|iterable $responses, float $timeout = null): ResponseStreamInterface
{
return $this->client->stream($responses, $timeout);
}

/**
* @return void
*/
public function reset()
{
if ($this->client instanceof ResetInterface) {
$this->client->reset();
}
}

public function setLogger(LoggerInterface $logger): void
{
if ($this->client instanceof LoggerAwareInterface) {
$this->client->setLogger($logger);
}
}
}
2 changes: 1 addition & 1 deletion src/Kernel/Traits/InteractWithHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use EasyWeChat\Kernel\Support\Arr;
use Psr\Log\LoggerAwareInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\ScopingHttpClient;
use EasyWeChat\Kernel\HttpClient\ScopingHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;

use function property_exists;
Expand Down

1 comment on commit 557409d

@vercel
Copy link

@vercel vercel bot commented on 557409d Dec 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

easywechat – ./

easywechat.vercel.app
easywechat-overtrue.vercel.app
easywechat-git-6x-overtrue.vercel.app

Please sign in to comment.