Files
redmine-bundle/src/Client/RedmineClient.php

63 lines
1.6 KiB
PHP

<?php
namespace Magdev\RedmineBundle\Client;
use Redmine\Client\Psr18Client;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\HttpFactory as GuzzleHttpFactory;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
final class RedmineClient
{
private ?Psr18Client $client = null;
private ?string $url = null;
private ?string $apiKey = null;
public function __construct(
private TagAwareCacheInterface $cache
) {}
public function setUrl(string $url): self
{
$this->url = $url;
}
public function setApiKey(string $apiKey): self
{
$this->apiKey = $apiKey;
}
public function call(string $api, string $method, array $arguments = []): mixed
{
$cacheKey = sprintf('%s_%s_%s', $api, $method, sha1(serialize($arguments)));
return $this->cache->get($cacheKey, function (ItemInterface $item) use ($api, $method): array {
$item->expiresAfter(3600);
$item->tag([$api, $method]);
$apiClient = $this->getClient()->getApi($api);
$value = call_user_method_array($method, $apiClient, $arguments);
return $value;
});
}
public function getClient(): ?Psr18Client
{
if (!$this->client) {
$guzzle = new GuzzleClient();
$factory = new GuzzleHttpFactory();
$this->client = new Psr18Client(
$guzzle,
$factory,
$factory,
$this->url,
$this->apiKey
);
}
return $this->client;
}
}