5 Commits
20 changed files with 581 additions and 110 deletions
+6
View File
@@ -0,0 +1,6 @@
.git
.gitea
var/
.env.local
.env.*.local
docker-compose.override.yml
+70
View File
@@ -0,0 +1,70 @@
# Builds and pushes a multi-arch Docker image to the Gitea container registry
# whenever a semver tag (v*.*.*) is pushed.
#
# One-time setup required:
# 1. Create a Gitea token with "package:write" scope.
# 2. Add it as a repository secret named GITEA_TOKEN
# (Repository → Settings → Secrets → Actions).
#
# After a successful run the image is available at:
# <your-gitea-host>/<owner>/<repo>:<version>
name: Docker Publish
on:
push:
tags:
- 'v*.*.*'
jobs:
build-push:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
# Strip the protocol from the server URL to get the registry hostname.
# e.g. https://gitea.example.com → gitea.example.com
- name: Derive registry hostname
run: |
echo "REGISTRY=$(echo '${{ gitea.server_url }}' | sed 's|https://||;s|http://||')" >> $GITHUB_ENV
# Generates OCI-compliant tags and labels from the git tag.
# v1.2.3 → image tags: 1.2.3 / 1.2 / 1
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ gitea.repository }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
# QEMU enables emulation of arm64 on the amd64 runner.
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
# BuildKit driver required for multi-platform builds and layer caching.
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Gitea registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ gitea.actor }}
password: ${{ secrets.GITEA_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
# Registry-based layer cache — survives between runs without a separate cache store.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ gitea.repository }}:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ gitea.repository }}:buildcache,mode=max
+40 -10
View File
@@ -71,7 +71,7 @@ The tests are written and failing. Now implement the minimum code to make them p
```
Tests are green. Refactor the implementation for [readability / removing duplication / naming].
Run php bin/phpunit after each change to confirm tests stay green.
Run vendor/bin/phpunit after each change to confirm tests stay green.
```
**Common anti-patterns**
@@ -84,19 +84,20 @@ Run php bin/phpunit after each change to confirm tests stay green.
| Combining Red + Green in one request | No failing baseline | Always separate the two phases |
### Running tests
Prever to use the tests in `docker compose exec graph`
```bash
# Run full suite
php bin/phpunit
vendor/bin/phpunit
# Run with human-readable output
php bin/phpunit --testdox
vendor/bin/phpunit --testdox
# Run a single test file
php bin/phpunit tests/Unit/Service/SvgRendererTest.php
vendor/bin/phpunit tests/Unit/Service/SvgRendererTest.php
# Run tests matching a filter
php bin/phpunit --filter it_renders
vendor/bin/phpunit --filter it_renders
```
### Auto-run hook
@@ -109,7 +110,7 @@ Add to `.claude/settings.json` to run PHPUnit automatically after every file edi
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "php bin/phpunit 2>&1 | tail -20"
"command": "vendor/bin/phpunit 2>&1 | tail -20"
}
]
}
@@ -118,20 +119,49 @@ Add to `.claude/settings.json` to run PHPUnit automatically after every file edi
## Docker
### Development
`docker-compose.override.yml` is picked up automatically and targets the `dev` stage (Xdebug + all deps, source mounted).
```bash
# Build and run
# Start dev container (override applied automatically)
docker compose up -d --build
# Force cache clear (clears the 1h filesystem cache)
# Shell into the container to run commands
docker compose exec graph sh
# Run tests inside the container
docker compose exec graph vendor/bin/phpunit
# Disable Xdebug for faster test runs
XDEBUG_MODE=off docker compose up -d
# Force cache clear
docker compose exec graph rm -rf var/cache/*
# View logs
docker compose logs -f graph
```
There is no `composer.lock` in the repo. If you add or change dependencies, run `composer install` locally and commit the resulting lock file — without it, Docker builds resolve versions fresh each time and may produce inconsistent results.
**Xdebug:** listens on port `9003`. Configure your IDE to accept connections from Docker. On Linux `host.docker.internal` is resolved via `extra_hosts: host-gateway` in the override file.
The Dockerfile runs `composer install --no-scripts` (skipping Symfony post-install scripts) then `composer dump-autoload --optimize --no-dev` in the final stage. If `bin/console` fails with a missing class error inside the container, the most likely cause is the absent lock file causing an incomplete dependency resolution.
### Production
Use only the base compose file to skip the dev override:
```bash
docker compose -f docker-compose.yml up -d --build
```
The `final` stage runs as a non-root `app` user and contains no Composer binary. The build pipeline is:
```
base → deps (composer install --no-dev)
→ build (copy source + dump-autoload)
→ final (copy vendor + source, chown app, USER app)
```
There is no `composer.lock` in the repo. If you add or change dependencies, run `composer install` locally and commit the resulting lock file — without it, Docker builds resolve versions fresh each time and may produce inconsistent results.
## Architecture
+29 -13
View File
@@ -1,19 +1,16 @@
FROM php:8.3-cli-alpine AS base
# Runtime dependencies
RUN apk add --no-cache \
curl \
icu-libs \
libzip \
&& docker-php-ext-install opcache
# Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /app
# ── deps stage ────────────────────────────────────────────────────────────────
# ── deps stage (prod vendor) ───────────────────────────────────────────────────
FROM base AS deps
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./
RUN composer install \
--no-dev \
@@ -22,20 +19,39 @@ RUN composer install \
--optimize-autoloader \
--prefer-dist
# ── final stage ───────────────────────────────────────────────────────────────
# ── build stage (generate optimised classmap with source present) ──────────────
FROM deps AS build
COPY . .
RUN composer dump-autoload --optimize --no-dev --no-interaction
# ── dev stage (all deps + Xdebug, source is mounted at runtime) ───────────────
FROM base AS dev
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
RUN apk add --no-cache ${PHPIZE_DEPS} linux-headers \
&& pecl install xdebug \
&& docker-php-ext-enable xdebug \
&& apk del ${PHPIZE_DEPS}
COPY docker/php/xdebug.ini /usr/local/etc/php/conf.d/docker-xdebug.ini
COPY composer.json composer.lock* ./
RUN composer install --no-scripts --no-interaction --prefer-dist
EXPOSE 8080
ENV APP_ENV=dev APP_DEBUG=1
CMD ["php", "-S", "0.0.0.0:8080", "-t", "public", "public/index.php"]
# ── final (prod) stage — no composer binary ────────────────────────────────────
FROM base AS final
COPY --from=deps /app/vendor /app/vendor
RUN addgroup -S app && adduser -S -G app app
COPY --from=build /app/vendor /app/vendor
COPY . .
RUN mkdir -p var/cache var/log \
&& chmod -R 777 var \
&& composer dump-autoload --optimize --no-dev
&& chown -R app:app /app
USER app
EXPOSE 8080
ENV APP_ENV=prod APP_DEBUG=0
ENV APP_ENV=prod \
APP_DEBUG=0
# Symfony's built-in dev server via PHP — fine for a single-purpose container
CMD ["php", "-S", "0.0.0.0:8080", "-t", "public", "public/index.php"]
+68 -11
View File
@@ -104,11 +104,14 @@ All credentials are configured via environment variables — see [Deploy](#deplo
### GitHub
**Fine-grained token (recommended):**
1. Go to **Settings → Developer settings → Personal access tokens → Fine-grained tokens**
2. Set **Resource owner** to your account
3. Under **Permissions → Account permissions**, set **Contribution activity** → Read-only
4. Generate and copy the token
**Classic token:** create a token with the `read:user` scope.
### GitLab
1. Go to **User Settings → Access Tokens**
@@ -125,6 +128,8 @@ All credentials are configured via environment variables — see [Deploy](#deplo
## Development
### Local (PHP)
```bash
# Install deps
composer install
@@ -136,24 +141,76 @@ APP_ENV=dev php -S localhost:8080 -t public
curl "http://localhost:8080/graph.svg" -o graph.svg
```
### Docker (recommended)
`docker-compose.override.yml` is picked up automatically and targets the `dev` stage (Xdebug enabled, source mounted).
```bash
# Start dev container
docker compose up -d --build
# Shell into the container
docker compose exec graph sh
# Run tests inside the container
docker compose exec graph php bin/phpunit
# Disable Xdebug for faster test runs
XDEBUG_MODE=off docker compose up -d
```
Xdebug listens on port **9003**. On Linux, `host.docker.internal` is resolved via `host-gateway`.
To run with production config only (no override):
```bash
docker compose -f docker-compose.yml up -d --build
```
---
## Testing
```bash
# Run full suite
php bin/phpunit
# Human-readable output
php bin/phpunit --testdox
# Single file
php bin/phpunit tests/Unit/Service/SvgRendererTest.php
# Filter by name
php bin/phpunit --filter it_renders
```
---
## Architecture
```
GET /graph.svg
├─ GitHubProvider → GitHub GraphQL API (contributionCalendar)
├─ GitLabProvider → GitLab REST API (/users/:id/events)
└─ GiteaProvider → Gitea REST API (/users/:user/heatmap)
merge by date (sum counts)
SvgRenderer
image/svg+xml (cached 1h)
GET /graph.svg?theme=dark|light
└─ GraphController
├─ host check (ALLOWED_HOSTS env, optional)
├─ cache lookup (filesystem, 1h TTL, key = "graph_{theme}")
│ └─ on miss:
│ ├─ GitHubProvider → GitHub GraphQL API (contributionCalendar)
│ ├─ GitLabProvider → GitLab REST API (/users/:id/events, paginated)
│ └─ GiteaProvider → Gitea REST API (/users/:user/heatmap)
│ each returns array<string, int> (Y-m-d => count)
│ failures are caught and logged; remaining providers still render
└─ merge by date (sum counts across providers)
│ └─ SvgRenderer::render()
└─ Response: image/svg+xml, Cache-Control: public max-age=3600
```
**Provider activation:** a provider only runs when its env vars are non-empty. GitHub and GitLab require `_USER` + `_TOKEN`; Gitea additionally requires `_URL`. GitLab resolves a numeric user ID from the username via a `/api/v4/users?username=` lookup before fetching events.
**SvgRenderer:** builds a 53-column × 7-row grid aligned so the last column always ends on the Saturday of the current week. Five intensity levels (0 → level 0, 13 → 1, 46 → 2, 79 → 3, 10+ → 4) mapped to GitHub's colour tokens. No external assets — the SVG is fully self-contained.
**Cache:** filesystem adapter (`var/cache/`), mounted as a Docker volume to survive container restarts. Theme is part of the cache key so dark and light are cached independently.
---
## License
+1 -3
View File
@@ -12,6 +12,7 @@
"symfony/console": "7.4.*",
"symfony/framework-bundle": "7.4.*",
"symfony/http-client": "7.4.*",
"symfony/monolog-bundle": "^4.0",
"symfony/runtime": "7.4.*",
"symfony/yaml": "7.4.*"
},
@@ -29,9 +30,6 @@
"phpunit/phpunit": "^11.5",
"symfony/phpunit-bridge": "^7.4"
},
"scripts": {
"test": "php bin/phpunit"
},
"config": {
"optimize-autoloader": true,
"sort-packages": true,
+1
View File
@@ -2,6 +2,7 @@
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
EightPoints\Bundle\GuzzleBundle\EightPointsGuzzleBundle::class => ['all' => true],
IDCI\Bundle\GraphQLClientBundle\IDCIGraphQLClientBundle::class => ['all' => true],
];
+26
View File
@@ -0,0 +1,26 @@
monolog:
channels:
- deprecation
when@dev:
monolog:
handlers:
main:
type: stream
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
channels: ['!event']
when@prod:
monolog:
handlers:
main:
type: stream
path: php://stderr
level: warning
channels: ['!event']
deprecation:
type: stream
channels: [deprecation]
path: '%kernel.logs_dir%/%kernel.environment%.deprecations.log'
level: info
+155
View File
@@ -690,6 +690,149 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
* enabled?: bool|Param, // Default: false
* },
* }
* @psalm-type MonologConfig = array{
* use_microseconds?: scalar|Param|null, // Default: true
* channels?: list<scalar|Param|null>,
* handlers?: array<string, array{ // Default: []
* type?: scalar|Param|null,
* id?: scalar|Param|null,
* enabled?: bool|Param, // Default: true
* priority?: scalar|Param|null, // Default: 0
* level?: scalar|Param|null, // Default: "DEBUG"
* bubble?: bool|Param, // Default: true
* interactive_only?: bool|Param, // Default: false
* app_name?: scalar|Param|null, // Default: null
* include_stacktraces?: bool|Param, // Default: false
* process_psr_3_messages?: array{
* enabled?: bool|Param|null, // Default: null
* date_format?: scalar|Param|null,
* remove_used_context_fields?: bool|Param,
* },
* path?: scalar|Param|null, // Default: "%kernel.logs_dir%/%kernel.environment%.log"
* file_permission?: scalar|Param|null, // Default: null
* use_locking?: bool|Param, // Default: false
* filename_format?: scalar|Param|null, // Default: "{filename}-{date}"
* date_format?: scalar|Param|null, // Default: "Y-m-d"
* ident?: scalar|Param|null, // Default: false
* logopts?: scalar|Param|null, // Default: 1
* facility?: scalar|Param|null, // Default: "user"
* max_files?: scalar|Param|null, // Default: 0
* action_level?: scalar|Param|null, // Default: "WARNING"
* activation_strategy?: scalar|Param|null, // Default: null
* stop_buffering?: bool|Param, // Default: true
* passthru_level?: scalar|Param|null, // Default: null
* excluded_http_codes?: list<array{ // Default: []
* code?: scalar|Param|null,
* urls?: list<scalar|Param|null>,
* }>,
* accepted_levels?: list<scalar|Param|null>,
* min_level?: scalar|Param|null, // Default: "DEBUG"
* max_level?: scalar|Param|null, // Default: "EMERGENCY"
* buffer_size?: scalar|Param|null, // Default: 0
* flush_on_overflow?: bool|Param, // Default: false
* handler?: scalar|Param|null,
* url?: scalar|Param|null,
* exchange?: scalar|Param|null,
* exchange_name?: scalar|Param|null, // Default: "log"
* channel?: scalar|Param|null, // Default: null
* bot_name?: scalar|Param|null, // Default: "Monolog"
* use_attachment?: scalar|Param|null, // Default: true
* use_short_attachment?: scalar|Param|null, // Default: false
* include_extra?: scalar|Param|null, // Default: false
* icon_emoji?: scalar|Param|null, // Default: null
* webhook_url?: scalar|Param|null,
* exclude_fields?: list<scalar|Param|null>,
* token?: scalar|Param|null,
* region?: scalar|Param|null,
* source?: scalar|Param|null,
* use_ssl?: bool|Param, // Default: true
* user?: mixed,
* title?: scalar|Param|null, // Default: null
* host?: scalar|Param|null, // Default: null
* port?: scalar|Param|null, // Default: 514
* config?: list<scalar|Param|null>,
* members?: list<scalar|Param|null>,
* connection_string?: scalar|Param|null,
* timeout?: scalar|Param|null,
* time?: scalar|Param|null, // Default: 60
* deduplication_level?: scalar|Param|null, // Default: 400
* store?: scalar|Param|null, // Default: null
* connection_timeout?: scalar|Param|null,
* persistent?: bool|Param,
* message_type?: scalar|Param|null, // Default: 0
* parse_mode?: scalar|Param|null, // Default: null
* disable_webpage_preview?: bool|Param|null, // Default: null
* disable_notification?: bool|Param|null, // Default: null
* split_long_messages?: bool|Param, // Default: false
* delay_between_messages?: bool|Param, // Default: false
* topic?: int|Param, // Default: null
* factor?: int|Param, // Default: 1
* tags?: string|list<scalar|Param|null>,
* console_formatter_options?: mixed, // Default: []
* formatter?: scalar|Param|null,
* nested?: bool|Param, // Default: false
* publisher?: string|array{
* id?: scalar|Param|null,
* hostname?: scalar|Param|null,
* port?: scalar|Param|null, // Default: 12201
* chunk_size?: scalar|Param|null, // Default: 1420
* encoder?: "json"|"compressed_json"|Param,
* },
* mongodb?: string|array{
* id?: scalar|Param|null, // ID of a MongoDB\Client service
* uri?: scalar|Param|null,
* username?: scalar|Param|null,
* password?: scalar|Param|null,
* database?: scalar|Param|null, // Default: "monolog"
* collection?: scalar|Param|null, // Default: "logs"
* },
* elasticsearch?: string|array{
* id?: scalar|Param|null,
* hosts?: list<scalar|Param|null>,
* host?: scalar|Param|null,
* port?: scalar|Param|null, // Default: 9200
* transport?: scalar|Param|null, // Default: "Http"
* user?: scalar|Param|null, // Default: null
* password?: scalar|Param|null, // Default: null
* },
* index?: scalar|Param|null, // Default: "monolog"
* document_type?: scalar|Param|null, // Default: "logs"
* ignore_error?: scalar|Param|null, // Default: false
* redis?: string|array{
* id?: scalar|Param|null,
* host?: scalar|Param|null,
* password?: scalar|Param|null, // Default: null
* port?: scalar|Param|null, // Default: 6379
* database?: scalar|Param|null, // Default: 0
* key_name?: scalar|Param|null, // Default: "monolog_redis"
* },
* predis?: string|array{
* id?: scalar|Param|null,
* host?: scalar|Param|null,
* },
* from_email?: scalar|Param|null,
* to_email?: string|list<scalar|Param|null>,
* subject?: scalar|Param|null,
* content_type?: scalar|Param|null, // Default: null
* headers?: list<scalar|Param|null>,
* mailer?: scalar|Param|null, // Default: null
* email_prototype?: string|array{
* id?: scalar|Param|null,
* method?: scalar|Param|null, // Default: null
* },
* verbosity_levels?: array{
* VERBOSITY_QUIET?: scalar|Param|null, // Default: "ERROR"
* VERBOSITY_NORMAL?: scalar|Param|null, // Default: "WARNING"
* VERBOSITY_VERBOSE?: scalar|Param|null, // Default: "NOTICE"
* VERBOSITY_VERY_VERBOSE?: scalar|Param|null, // Default: "INFO"
* VERBOSITY_DEBUG?: scalar|Param|null, // Default: "DEBUG"
* },
* channels?: string|array{
* type?: scalar|Param|null,
* elements?: list<scalar|Param|null>,
* },
* }>,
* }
* @psalm-type EightPointsGuzzleConfig = array{
* clients?: array<string, array{ // Default: []
* class?: scalar|Param|null, // Default: "%eight_points_guzzle.http_client.class%"
@@ -745,6 +888,7 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
* parameters?: ParametersConfig,
* services?: ServicesConfig,
* framework?: FrameworkConfig,
* monolog?: MonologConfig,
* eight_points_guzzle?: EightPointsGuzzleConfig,
* idci_graphql_client?: IdciGraphqlClientConfig,
* "when@dev"?: array{
@@ -752,6 +896,16 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
* parameters?: ParametersConfig,
* services?: ServicesConfig,
* framework?: FrameworkConfig,
* monolog?: MonologConfig,
* eight_points_guzzle?: EightPointsGuzzleConfig,
* idci_graphql_client?: IdciGraphqlClientConfig,
* },
* "when@prod"?: array{
* imports?: ImportsConfig,
* parameters?: ParametersConfig,
* services?: ServicesConfig,
* framework?: FrameworkConfig,
* monolog?: MonologConfig,
* eight_points_guzzle?: EightPointsGuzzleConfig,
* idci_graphql_client?: IdciGraphqlClientConfig,
* },
@@ -838,6 +992,7 @@ namespace Symfony\Component\Routing\Loader\Configurator;
* }
* @psalm-type RoutesConfig = array{
* "when@dev"?: array<string, RouteConfig|ImportConfig|AliasConfig>,
* "when@prod"?: array<string, RouteConfig|ImportConfig|AliasConfig>,
* ...<string, RouteConfig|ImportConfig|AliasConfig>
* }
*/
+31
View File
@@ -0,0 +1,31 @@
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/'
exclude:
- '../src/Kernel.php'
_instanceof:
App\Service\ProviderInterface:
tags: ['app.provider']
App\Service\GitHubProvider:
arguments:
$username: '%env(GITHUB_USER)%'
$token: '%env(GITHUB_TOKEN)%'
App\Service\GitLabProvider:
arguments:
$username: '%env(GITLAB_USER)%'
$token: '%env(GITLAB_TOKEN)%'
$baseUrl: '%env(GITLAB_URL)%'
App\Service\GiteaProvider:
arguments:
$username: '%env(GITEA_USER)%'
$token: '%env(GITEA_TOKEN)%'
$baseUrl: '%env(GITEA_URL)%'
+19
View File
@@ -0,0 +1,19 @@
# Local development overrides — picked up automatically by `docker compose up`.
# To run with production config only: docker compose -f docker-compose.yml up
services:
graph:
build:
target: dev
volumes:
- .:/app
- /app/vendor # keeps vendor from the dev image, not your local dir
environment:
APP_ENV: dev
APP_DEBUG: "1"
XDEBUG_MODE: "${XDEBUG_MODE:-debug}"
XDEBUG_CONFIG: "client_host=host.docker.internal"
# Makes host.docker.internal resolve correctly on Linux
extra_hosts:
- "host.docker.internal:host-gateway"
ports:
- "9003:9003"
+3 -1
View File
@@ -1,6 +1,8 @@
services:
graph:
build: .
build:
context: .
target: final
container_name: git-contribution-graph
restart: unless-stopped
ports:
+8
View File
@@ -0,0 +1,8 @@
[xdebug]
; Mode is controlled by the XDEBUG_MODE env var in docker-compose.override.yml.
; Set XDEBUG_MODE=off in your shell to skip Xdebug for faster test runs.
xdebug.mode=off
xdebug.client_port=9003
xdebug.client_host=host.docker.internal
xdebug.start_with_request=yes
xdebug.log=/tmp/xdebug.log
View File
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
+32 -54
View File
@@ -2,12 +2,12 @@
namespace App\Controller;
use App\Service\GiteaProvider;
use App\Service\GitHubProvider;
use App\Service\GitLabProvider;
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\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -20,30 +20,13 @@ class GraphController
private readonly array $allowedHosts;
public function __construct(
private readonly GitHubProvider $github,
private readonly GitLabProvider $gitlab,
private readonly GiteaProvider $gitea,
#[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 = '',
#[Autowire(env: 'GITHUB_USER')]
private readonly string $githubUser = '',
#[Autowire(env: 'GITHUB_TOKEN')]
private readonly string $githubToken = '',
#[Autowire(env: 'GITLAB_USER')]
private readonly string $gitlabUser = '',
#[Autowire(env: 'GITLAB_TOKEN')]
private readonly string $gitlabToken = '',
#[Autowire(env: 'GITLAB_URL')]
private readonly string $gitlabUrl = '',
#[Autowire(env: 'GITEA_USER')]
private readonly string $giteaUser = '',
#[Autowire(env: 'GITEA_TOKEN')]
private readonly string $giteaToken = '',
#[Autowire(env: 'GITEA_URL')]
private readonly string $giteaUrl = '',
) {
$this->allowedHosts = array_values(array_filter(array_map('trim', explode(',', $allowedHosts))));
}
@@ -56,78 +39,73 @@ class GraphController
public function graph(Request $request): Response
{
if ($this->allowedHosts !== [] && !in_array($request->getHost(), $this->allowedHosts, true)) {
$this->logger->warning('GraphController: rejected request from disallowed host', ['host' => $request->getHost()]);
return new Response('Forbidden', 403);
}
$theme = $request->query->get('theme', 'dark');
$theme = $request->query->get('theme', 'dark');
$cacheKey = 'graph_' . $theme;
$svg = $this->cache->get($cacheKey, function (ItemInterface $item) use ($theme): string {
$cacheMiss = false;
$svg = $this->cache->get($cacheKey, function (ItemInterface $item) use ($theme, &$cacheMiss): string {
$cacheMiss = true;
$item->expiresAfter(3600);
$contributions = $this->fetchAllContributions();
return $this->renderer->render($contributions, $theme);
return $this->renderer->render($this->fetchAllContributions(), $theme);
});
$this->logger->debug('GraphController: cache ' . ($cacheMiss ? 'miss' : 'hit'), ['theme' => $theme]);
return new Response($svg, 200, [
'Content-Type' => 'image/svg+xml',
'Cache-Control' => 'public, max-age=3600',
]);
}
#[Route('/', name: 'index', methods: ['GET'])]
public function index(Request $request): RedirectResponse
{
$query = $request->query->all();
$url = '/graph.svg' . ($query ? '?' . http_build_query($query) : '');
return new RedirectResponse($url, 302);
}
#[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 = [];
if ($this->githubUser !== '' && $this->githubToken !== '') {
try {
$contributions = $this->merge($contributions, $this->github->fetch($this->githubUser, $this->githubToken));
} catch (\Throwable $e) {
$this->logger->warning('GitHub fetch failed: ' . $e->getMessage());
/** @var ProviderInterface $provider */
foreach ($this->providers as $provider) {
if (!$provider->isConfigured()) {
continue;
}
}
if ($this->gitlabUser !== '' && $this->gitlabToken !== '') {
try {
$contributions = $this->merge($contributions, $this->gitlab->fetch(
$this->gitlabUser,
$this->gitlabToken,
$this->gitlabUrl !== '' ? $this->gitlabUrl : 'https://gitlab.com'
));
$contributions = $this->merge($contributions, $provider->fetch());
} catch (\Throwable $e) {
$this->logger->warning('GitLab fetch failed: ' . $e->getMessage());
}
}
if ($this->giteaUser !== '' && $this->giteaToken !== '' && $this->giteaUrl !== '') {
try {
$contributions = $this->merge($contributions, $this->gitea->fetch(
$this->giteaUser,
$this->giteaToken,
rtrim($this->giteaUrl, '/')
));
} catch (\Throwable $e) {
$this->logger->warning('Gitea fetch failed: ' . $e->getMessage());
$this->logger->warning(sprintf('%s fetch failed: %s', $provider::class, $e->getMessage()), ['exception' => $e]);
}
}
return $contributions;
}
/** Sum contributions by date from two maps. */
/** @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;
}
}
+21 -4
View File
@@ -4,6 +4,7 @@ namespace App\Service;
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClient;
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClientRegistryInterface;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
@@ -11,20 +12,30 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
*
* Required token scopes: read:user
*/
class GitHubProvider
class GitHubProvider implements ProviderInterface
{
private const GRAPHQL_URL = 'https://api.github.com/graphql';
public function __construct(
private readonly HttpClientInterface $client,
private readonly GraphQLApiClientRegistryInterface $registry,
private readonly string $username,
private readonly string $token,
private readonly LoggerInterface $logger,
) {}
public function isConfigured(): bool
{
return $this->username !== '' && $this->token !== '';
}
/**
* @return array<string, int> date (Y-m-d) => contribution count
*/
public function fetch(string $username, string $token): array
public function fetch(): array
{
$this->logger->debug('GitHubProvider: fetching contributions', ['user' => $this->username]);
$from = (new \DateTimeImmutable('-365 days'))->format('Y-m-d\T00:00:00\Z');
$to = (new \DateTimeImmutable())->format('Y-m-d\T23:59:59\Z');
@@ -32,7 +43,7 @@ class GitHubProvider
$graphqlClient = $this->registry->get('github');
$query = $graphqlClient->buildQuery(
['user' => ['login' => $username]],
['user' => ['login' => $this->username]],
[
'contributionsCollection' => [
'_parameters' => ['from' => $from, 'to' => $to],
@@ -49,7 +60,7 @@ class GitHubProvider
// transport sends form_params, so we use Symfony HttpClient here instead.
$response = $this->client->request('POST', self::GRAPHQL_URL, [
'headers' => [
'Authorization' => "Bearer $token",
'Authorization' => "Bearer {$this->token}",
'Content-Type' => 'application/json',
],
'json' => ['query' => $query],
@@ -72,6 +83,12 @@ class GitHubProvider
}
}
$this->logger->info('GitHubProvider: fetched contributions', [
'user' => $this->username,
'days' => count($result),
'total' => array_sum($result),
]);
return $result;
}
}
+29 -8
View File
@@ -2,6 +2,7 @@
namespace App\Service;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
@@ -10,26 +11,39 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
* Required token scopes: read_user, read_api
* Works with both gitlab.com and self-hosted instances.
*/
class GitLabProvider
class GitLabProvider implements ProviderInterface
{
public function __construct(private readonly HttpClientInterface $client) {}
public function __construct(
private readonly HttpClientInterface $client,
private readonly string $username,
private readonly string $token,
private readonly LoggerInterface $logger,
private readonly string $baseUrl = '',
) {}
public function isConfigured(): bool
{
return $this->username !== '' && $this->token !== '';
}
/**
* @return array<string, int> date (Y-m-d) => event count
*/
public function fetch(string $username, string $token, string $baseUrl = 'https://gitlab.com'): array
public function fetch(): array
{
$baseUrl = rtrim($baseUrl, '/');
$baseUrl = rtrim($this->baseUrl !== '' ? $this->baseUrl : 'https://gitlab.com', '/');
$this->logger->debug('GitLabProvider: fetching contributions', ['user' => $this->username, 'url' => $baseUrl]);
// Resolve numeric user ID from username
$userResponse = $this->client->request('GET', "$baseUrl/api/v4/users", [
'headers' => ['PRIVATE-TOKEN' => $token],
'query' => ['username' => $username],
'headers' => ['PRIVATE-TOKEN' => $this->token],
'query' => ['username' => $this->username],
]);
$users = $userResponse->toArray();
if (empty($users)) {
throw new \RuntimeException("GitLab: user '$username' not found on $baseUrl");
throw new \RuntimeException("GitLab: user '{$this->username}' not found on $baseUrl");
}
$userId = $users[0]['id'];
@@ -39,7 +53,7 @@ class GitLabProvider
do {
$response = $this->client->request('GET', "$baseUrl/api/v4/users/$userId/events", [
'headers' => ['PRIVATE-TOKEN' => $token],
'headers' => ['PRIVATE-TOKEN' => $this->token],
'query' => [
'after' => $after,
'per_page' => 100,
@@ -57,6 +71,13 @@ class GitLabProvider
$page++;
} while (count($events) === 100);
$this->logger->info('GitLabProvider: fetched contributions', [
'user' => $this->username,
'pages' => $page - 1,
'days' => count($result),
'total' => array_sum($result),
]);
return $result;
}
}
+27 -6
View File
@@ -2,6 +2,7 @@
namespace App\Service;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
@@ -12,18 +13,32 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
*
* Required token scopes: read:user
*/
class GiteaProvider
class GiteaProvider implements ProviderInterface
{
public function __construct(private readonly HttpClientInterface $client) {}
public function __construct(
private readonly HttpClientInterface $client,
private readonly string $username,
private readonly string $token,
private readonly string $baseUrl,
private readonly LoggerInterface $logger,
) {}
public function isConfigured(): bool
{
return $this->username !== '' && $this->token !== '' && $this->baseUrl !== '';
}
/**
* @return array<string, int> date (Y-m-d) => contribution count
*/
public function fetch(string $username, string $token, string $baseUrl): array
public function fetch(): array
{
$baseUrl = rtrim($baseUrl, '/');
$response = $this->client->request('GET', "$baseUrl/api/v1/users/$username/heatmap", [
'headers' => ['Authorization' => "token $token"],
$baseUrl = rtrim($this->baseUrl, '/');
$this->logger->debug('GiteaProvider: fetching contributions', ['user' => $this->username, 'url' => $baseUrl]);
$response = $this->client->request('GET', "$baseUrl/api/v1/users/{$this->username}/heatmap", [
'headers' => ['Authorization' => "token {$this->token}"],
]);
$data = $response->toArray();
@@ -38,6 +53,12 @@ class GiteaProvider
$result[$date] = ($result[$date] ?? 0) + (int) $entry['contributions'];
}
$this->logger->info('GiteaProvider: fetched contributions', [
'user' => $this->username,
'days' => count($result),
'total' => array_sum($result),
]);
return $result;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Service;
interface ProviderInterface
{
/** @return array<string, int> date (Y-m-d) => contribution count */
public function fetch(): array;
public function isConfigured(): bool;
}