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

63 lines
1.6 KiB
PHP
Raw Normal View History

2024-09-13 00:43:53 +02:00
<?php
namespace Magdev\RedmineBundle\Client;
2024-09-13 01:04:38 +02:00
use Redmine\Client\Psr18Client;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\HttpFactory as GuzzleHttpFactory;
2024-09-13 02:40:08 +02:00
use Symfony\Contracts\Cache\ItemInterface;
2024-09-13 02:09:15 +02:00
use Symfony\Contracts\Cache\TagAwareCacheInterface;
2024-09-13 00:43:53 +02:00
2024-09-13 01:04:38 +02:00
final class RedmineClient
2024-09-13 00:43:53 +02:00
{
2024-09-13 01:04:38 +02:00
private ?Psr18Client $client = null;
2024-09-13 02:09:15 +02:00
private ?string $url = null;
private ?string $apiKey = null;
2024-09-13 00:43:53 +02:00
2024-09-13 01:04:38 +02:00
public function __construct(
2024-09-13 02:23:17 +02:00
private TagAwareCacheInterface $cache
2024-09-13 02:09:15 +02:00
) {}
public function setUrl(string $url): self
{
$this->url = $url;
2024-09-13 01:04:38 +02:00
}
2024-09-13 02:09:15 +02:00
public function setApiKey(string $apiKey): self
{
$this->apiKey = $apiKey;
}
2024-09-13 01:04:38 +02:00
2024-09-13 02:09:15 +02:00
public function call(string $api, string $method, array $arguments = []): mixed
2024-09-13 01:04:38 +02:00
{
2024-09-13 02:09:15 +02:00
$cacheKey = sprintf('%s_%s_%s', $api, $method, sha1(serialize($arguments)));
2024-09-13 02:42:52 +02:00
return $this->cache->get($cacheKey, function (ItemInterface $item) use ($api, $method): array {
2024-09-13 02:09:15 +02:00
$item->expiresAfter(3600);
$item->tag([$api, $method]);
2024-09-13 01:04:38 +02:00
2024-09-13 02:09:15 +02:00
$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;
2024-09-13 01:04:38 +02:00
}
2024-09-13 00:43:53 +02:00
}