96 lines
3.0 KiB
PHP
96 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Controller;
|
|
|
|
use App\Service\ProviderInterface;
|
|
use App\Service\SvgRenderer;
|
|
use Psr\Log\LoggerInterface;
|
|
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
|
use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Contracts\Cache\CacheInterface;
|
|
use Symfony\Contracts\Cache\ItemInterface;
|
|
|
|
class GraphController
|
|
{
|
|
/** @var list<string> */
|
|
private readonly array $allowedHosts;
|
|
|
|
public function __construct(
|
|
#[TaggedIterator('app.provider')]
|
|
private readonly iterable $providers,
|
|
private readonly SvgRenderer $renderer,
|
|
private readonly CacheInterface $cache,
|
|
private readonly LoggerInterface $logger,
|
|
#[Autowire(env: 'ALLOWED_HOSTS')]
|
|
string $allowedHosts = '',
|
|
) {
|
|
$this->allowedHosts = array_values(array_filter(array_map('trim', explode(',', $allowedHosts))));
|
|
}
|
|
|
|
/**
|
|
* Query parameters:
|
|
* theme string dark|light (default: dark)
|
|
*/
|
|
#[Route('/graph.svg', name: 'contribution_graph', methods: ['GET'])]
|
|
public function graph(Request $request): Response
|
|
{
|
|
if ($this->allowedHosts !== [] && !in_array($request->getHost(), $this->allowedHosts, true)) {
|
|
return new Response('Forbidden', 403);
|
|
}
|
|
|
|
$theme = $request->query->get('theme', 'dark');
|
|
$cacheKey = 'graph_' . $theme;
|
|
|
|
$svg = $this->cache->get($cacheKey, function (ItemInterface $item) use ($theme): string {
|
|
$item->expiresAfter(3600);
|
|
|
|
return $this->renderer->render($this->fetchAllContributions(), $theme);
|
|
});
|
|
|
|
return new Response($svg, 200, [
|
|
'Content-Type' => 'image/svg+xml',
|
|
'Cache-Control' => 'public, max-age=3600',
|
|
]);
|
|
}
|
|
|
|
#[Route('/health', name: 'health', methods: ['GET'])]
|
|
public function health(): Response
|
|
{
|
|
return new Response('{"status":"ok"}', 200, ['Content-Type' => 'application/json']);
|
|
}
|
|
|
|
/** @return array<string, int> */
|
|
private function fetchAllContributions(): array
|
|
{
|
|
$contributions = [];
|
|
|
|
/** @var ProviderInterface $provider */
|
|
foreach ($this->providers as $provider) {
|
|
if (!$provider->isConfigured()) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
$contributions = $this->merge($contributions, $provider->fetch());
|
|
} catch (\Throwable $e) {
|
|
$this->logger->warning(sprintf('%s fetch failed: %s', $provider::class, $e->getMessage()));
|
|
}
|
|
}
|
|
|
|
return $contributions;
|
|
}
|
|
|
|
/** @param array<string, int> $base @param array<string, int> $new @return array<string, int> */
|
|
private function merge(array $base, array $new): array
|
|
{
|
|
foreach ($new as $date => $count) {
|
|
$base[$date] = ($base[$date] ?? 0) + $count;
|
|
}
|
|
|
|
return $base;
|
|
}
|
|
}
|