12 Commits
Author SHA1 Message Date
haylan cceda8abf2 feat: integrate Monolog for enhanced logging across providers and controller 2026-05-29 18:57:25 +02:00
haylan 8b8ec9ab2f feat: add redirect from index route to graph.svg with query parameters 2026-05-29 18:28:56 +02:00
haylan b3e79de069 fix: php unit startup command 2026-05-29 18:23:36 +02:00
haylan f3770f1c2a docs: update README with token configuration and Docker development instructions 2026-05-29 16:09:07 +02:00
haylan 56035096c6 feat: implement multi-provider architecture for contribution fetching and add Docker support 2026-05-29 11:51:05 +02:00
haylanandClaude-Bot 381b8f4489 docs: add TDD conventions and testing guide to CLAUDE.md
Covers testing file conventions, Red→Green→Refactor cycle with
example prompts, common anti-patterns, test runner commands, and
the auto-run hook setup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 22:09:44 +02:00
haylanandClaude-Bot fa035781fd fix(svg-renderer): correct date alignment and drop unused parameter
- modify('Sunday') → modify('last Sunday') so the grid start is
  reliably the prior Sunday when today is already Sunday
- Remove unused $totalW from renderLegend signature
- Remove unused GAP constant (value preserved inline as a comment on STEP)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 22:09:31 +02:00
haylanandClaude-Bot d1dce19832 refactor(github): migrate contribution query to GraphQL bundle
Use GraphQLApiClientRegistryInterface to build the query via the
bundle's query builder. Keep Symfony HttpClient for the actual POST
since GitHub requires application/json (the bundle's transport sends
form_params instead).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 22:09:25 +02:00
haylanandClaude-Bot 0c2a185927 test: add PHPUnit 11.5 unit test suite
- phpunit.xml.dist with unit suite and source coverage config
- .phpunit.cache excluded in .gitignore
- Initial SvgRendererTest as example test
- .claude/settings.json with PostToolUse hook to auto-run phpunit on edit

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 22:09:17 +02:00
haylanandClaude-Bot ff44161a99 chore(deps): bump Symfony to 7.4 and add GraphQL client bundles
- symfony/* pinned to 7.4.* (was 7.1.*)
- eightpoints/guzzle-bundle ^8.6 and idci/graphql-client-bundle ^2.0 added
- phpunit/phpunit ^11.5 and symfony/phpunit-bridge ^7.4 added as dev deps
- Bundles registered in config/bundles.php
- Guzzle and GraphQL client configured via YAML package configs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 22:09:11 +02:00
haylan c1fde0aed3 Update environment configuration to development mode and add CLAUDE.md for project guidance 2026-05-28 20:15:12 +02:00
haylan 4ce551013e Update example graph image link in README 2026-05-28 20:07:20 +02:00
28 changed files with 1810 additions and 132 deletions
+10
View File
@@ -0,0 +1,10 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "php bin/phpunit 2>&1 | tail -20"
}
]
}
}
+6
View File
@@ -0,0 +1,6 @@
.git
.gitea
var/
.env.local
.env.*.local
docker-compose.override.yml
+1 -1
View File
@@ -1,4 +1,4 @@
APP_ENV=prod APP_ENV=dev
APP_DEBUG=0 APP_DEBUG=0
APP_SECRET=changeme_replace_with_random_32char_string APP_SECRET=changeme_replace_with_random_32char_string
+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
+1
View File
@@ -4,3 +4,4 @@
/var/ /var/
/public/bundles/ /public/bundles/
composer.lock composer.lock
/.phpunit.cache
+203
View File
@@ -0,0 +1,203 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Development
```bash
# Install dependencies (generates composer.lock if missing — commit it)
composer install
# Run dev server
APP_ENV=dev php -S localhost:8080 -t public
# Test the graph endpoint
curl "http://localhost:8080/graph.svg?theme=dark" -o graph.svg
curl "http://localhost:8080/health"
```
### Testing conventions (apply to every test file)
- `declare(strict_types=1)` at the top of every test file
- Test classes are `final` and extend `TestCase`
- Methods: `#[Test]` attribute + `it_` prefix + `snake_case` — e.g. `it_returns_empty_when_no_contributions`
- Structure: Arrange → Act → Assert, separated by blank lines; one assertion per test when possible
- Use `$this->assert*()` not `self::assert*()`
```php
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Service\SvgRenderer;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class SvgRendererTest extends TestCase
{
#[Test]
public function it_renders_an_svg_with_no_contributions(): void
{
$renderer = new SvgRenderer();
$svg = $renderer->render([], 'light');
$this->assertStringContainsString('<svg', $svg);
}
}
```
### TDD: Red → Green → Refactor
Always drive new features and bug fixes with this cycle. Claude writes implementation first by default — override that with explicit prompts.
**Phase 1 — Red (write a failing test first)**
```
Write a failing test for [feature description].
Do NOT write the implementation yet.
The test should fail because the class/method does not exist.
```
**Phase 2 — Green (minimal implementation)**
```
The tests are written and failing. Now implement the minimum code to make them pass. Nothing more.
```
**Phase 3 — Refactor**
```
Tests are green. Refactor the implementation for [readability / removing duplication / naming].
Run vendor/bin/phpunit after each change to confirm tests stay green.
```
**Common anti-patterns**
| Wrong prompt | Why it breaks TDD | Correct prompt |
|---|---|---|
| "Write tests for this feature" | Claude implements first, then fits tests to it | "Write **failing** tests for [feature]. Stop before any implementation." |
| "Add tests and implementation" | Loses the design feedback of failing tests | Two separate prompts: Red, then Green |
| "Make the tests pass" | Encourages skipping to a green state | "Implement the minimum to make the failing tests pass." |
| 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
vendor/bin/phpunit
# Run with human-readable output
vendor/bin/phpunit --testdox
# Run a single test file
vendor/bin/phpunit tests/Unit/Service/SvgRendererTest.php
# Run tests matching a filter
vendor/bin/phpunit --filter it_renders
```
### Auto-run hook
Add to `.claude/settings.json` to run PHPUnit automatically after every file edit:
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "vendor/bin/phpunit 2>&1 | tail -20"
}
]
}
}
```
## Docker
### Development
`docker-compose.override.yml` is picked up automatically and targets the `dev` stage (Xdebug + all deps, source mounted).
```bash
# Start dev container (override applied automatically)
docker compose up -d --build
# 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
```
**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.
### 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
Single-controller Symfony app with no database. The request flow:
```
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 query)
│ ├─ GitLabProvider → GitLab REST /users/:id/events (paginated, 100/page)
│ └─ GiteaProvider → Gitea REST /api/v1/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 contributions → level 0, 13 → 1, 46 → 2, 79 → 3, 10+ → 4) mapped to GitHub's exact 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.
## Environment variables
| Variable | Required | Notes |
|---|---|---|
| `APP_SECRET` | Yes | 32+ char random string |
| `GITHUB_USER` / `GITHUB_TOKEN` | For GitHub | Token scope: `read:user` |
| `GITLAB_USER` / `GITLAB_TOKEN` | For GitLab | Token scopes: `read_user`, `read_api` |
| `GITLAB_URL` | No | Defaults to `https://gitlab.com` |
| `GITEA_USER` / `GITEA_TOKEN` / `GITEA_URL` | For Gitea | Token scope: `read:user` |
| `ALLOWED_HOSTS` | No | Comma-separated hostnames; empty = allow all |
Copy `.env` to `.env.local` for local development — `.env.local` is gitignored.
+29 -13
View File
@@ -1,19 +1,16 @@
FROM php:8.3-cli-alpine AS base FROM php:8.3-cli-alpine AS base
# Runtime dependencies
RUN apk add --no-cache \ RUN apk add --no-cache \
curl \ curl \
icu-libs \ icu-libs \
libzip \ libzip \
&& docker-php-ext-install opcache && docker-php-ext-install opcache
# Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /app WORKDIR /app
# ── deps stage ──────────────────────────────────────────────────────────────── # ── deps stage (prod vendor) ───────────────────────────────────────────────────
FROM base AS deps FROM base AS deps
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./ COPY composer.json composer.lock* ./
RUN composer install \ RUN composer install \
--no-dev \ --no-dev \
@@ -22,20 +19,39 @@ RUN composer install \
--optimize-autoloader \ --optimize-autoloader \
--prefer-dist --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 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 . . COPY . .
RUN mkdir -p var/cache var/log \ RUN mkdir -p var/cache var/log \
&& chmod -R 777 var \ && chown -R app:app /app
&& composer dump-autoload --optimize --no-dev
USER app
EXPOSE 8080 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"] CMD ["php", "-S", "0.0.0.0:8080", "-t", "public", "public/index.php"]
+69 -12
View File
@@ -6,7 +6,7 @@ A self-hosted Symfony service that merges contribution data from **GitHub**, **G
https://your-host/graph.svg?theme=dark https://your-host/graph.svg?theme=dark
``` ```
![Example graph](https://img.shields.io/badge/output-SVG%20heatmap-39d353?style=flat-square) ![Example graph](https://gitgraph.arthurerlich/graph.svg)
--- ---
@@ -104,11 +104,14 @@ All credentials are configured via environment variables — see [Deploy](#deplo
### GitHub ### GitHub
**Fine-grained token (recommended):**
1. Go to **Settings → Developer settings → Personal access tokens → Fine-grained tokens** 1. Go to **Settings → Developer settings → Personal access tokens → Fine-grained tokens**
2. Set **Resource owner** to your account 2. Set **Resource owner** to your account
3. Under **Permissions → Account permissions**, set **Contribution activity** → Read-only 3. Under **Permissions → Account permissions**, set **Contribution activity** → Read-only
4. Generate and copy the token 4. Generate and copy the token
**Classic token:** create a token with the `read:user` scope.
### GitLab ### GitLab
1. Go to **User Settings → Access Tokens** 1. Go to **User Settings → Access Tokens**
@@ -125,6 +128,8 @@ All credentials are configured via environment variables — see [Deploy](#deplo
## Development ## Development
### Local (PHP)
```bash ```bash
# Install deps # Install deps
composer install composer install
@@ -136,24 +141,76 @@ APP_ENV=dev php -S localhost:8080 -t public
curl "http://localhost:8080/graph.svg" -o graph.svg 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 ## Architecture
``` ```
GET /graph.svg GET /graph.svg?theme=dark|light
└─ GraphController
├─ GitHubProvider → GitHub GraphQL API (contributionCalendar) ├─ host check (ALLOWED_HOSTS env, optional)
├─ GitLabProvider → GitLab REST API (/users/:id/events) ├─ cache lookup (filesystem, 1h TTL, key = "graph_{theme}")
└─ GiteaProvider → Gitea REST API (/users/:user/heatmap) │ └─ on miss:
│ ├─ GitHubProvider → GitHub GraphQL API (contributionCalendar)
merge by date (sum counts) │ ├─ GitLabProvider → GitLab REST API (/users/:id/events, paginated)
│ └─ GiteaProvider → Gitea REST API (/users/:user/heatmap)
SvgRenderer │ each returns array<string, int> (Y-m-d => count)
│ failures are caught and logged; remaining providers still render
image/svg+xml (cached 1h) └─ 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 ## License
+15 -5
View File
@@ -5,10 +5,16 @@
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": ">=8.2", "php": ">=8.2",
"symfony/cache": "^7.1", "eightpoints/guzzle-bundle": "^8.6",
"symfony/framework-bundle": "^7.1", "idci/graphql-client-bundle": "^2.0",
"symfony/http-client": "^7.1", "monolog/monolog": "^3.10",
"symfony/runtime": "^7.1" "symfony/cache": "7.4.*",
"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.*"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
@@ -20,6 +26,10 @@
"App\\Tests\\": "tests/" "App\\Tests\\": "tests/"
} }
}, },
"require-dev": {
"phpunit/phpunit": "^11.5",
"symfony/phpunit-bridge": "^7.4"
},
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,
"sort-packages": true, "sort-packages": true,
@@ -30,7 +40,7 @@
"extra": { "extra": {
"symfony": { "symfony": {
"allow-contrib": false, "allow-contrib": false,
"require": "7.1.*" "require": "7.4.*"
} }
} }
} }
+3
View File
@@ -2,4 +2,7 @@
return [ return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true], 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],
]; ];
+7
View File
@@ -0,0 +1,7 @@
eight_points_guzzle:
clients:
github_graphql:
base_url: 'https://api.github.com/graphql'
options:
headers:
Authorization: 'Bearer %env(GITHUB_TOKEN)%'
+4
View File
@@ -0,0 +1,4 @@
idci_graphql_client:
clients:
github:
http_client: 'eight_points_guzzle.client.github_graphql'
+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
+1010
View File
File diff suppressed because it is too large Load Diff
+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: services:
graph: graph:
build: . build:
context: .
target: final
container_name: git-contribution-graph container_name: git-contribution-graph
restart: unless-stopped restart: unless-stopped
ports: 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
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
cacheDirectory=".phpunit.cache"
>
<testsuites>
<testsuite name="unit">
<directory>tests/Unit</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">src</directory>
</include>
</source>
</phpunit>
View File
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
+32 -54
View File
@@ -2,12 +2,12 @@
namespace App\Controller; namespace App\Controller;
use App\Service\GiteaProvider; use App\Service\ProviderInterface;
use App\Service\GitHubProvider;
use App\Service\GitLabProvider;
use App\Service\SvgRenderer; use App\Service\SvgRenderer;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire; 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\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
@@ -20,30 +20,13 @@ class GraphController
private readonly array $allowedHosts; private readonly array $allowedHosts;
public function __construct( public function __construct(
private readonly GitHubProvider $github, #[TaggedIterator('app.provider')]
private readonly GitLabProvider $gitlab, private readonly iterable $providers,
private readonly GiteaProvider $gitea,
private readonly SvgRenderer $renderer, private readonly SvgRenderer $renderer,
private readonly CacheInterface $cache, private readonly CacheInterface $cache,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
#[Autowire(env: 'ALLOWED_HOSTS')] #[Autowire(env: 'ALLOWED_HOSTS')]
string $allowedHosts = '', 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)))); $this->allowedHosts = array_values(array_filter(array_map('trim', explode(',', $allowedHosts))));
} }
@@ -56,78 +39,73 @@ class GraphController
public function graph(Request $request): Response public function graph(Request $request): Response
{ {
if ($this->allowedHosts !== [] && !in_array($request->getHost(), $this->allowedHosts, true)) { 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); return new Response('Forbidden', 403);
} }
$theme = $request->query->get('theme', 'dark'); $theme = $request->query->get('theme', 'dark');
$cacheKey = 'graph_' . $theme; $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); $item->expiresAfter(3600);
$contributions = $this->fetchAllContributions(); return $this->renderer->render($this->fetchAllContributions(), $theme);
return $this->renderer->render($contributions, $theme);
}); });
$this->logger->debug('GraphController: cache ' . ($cacheMiss ? 'miss' : 'hit'), ['theme' => $theme]);
return new Response($svg, 200, [ return new Response($svg, 200, [
'Content-Type' => 'image/svg+xml', 'Content-Type' => 'image/svg+xml',
'Cache-Control' => 'public, max-age=3600', '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'])] #[Route('/health', name: 'health', methods: ['GET'])]
public function health(): Response public function health(): Response
{ {
return new Response('{"status":"ok"}', 200, ['Content-Type' => 'application/json']); return new Response('{"status":"ok"}', 200, ['Content-Type' => 'application/json']);
} }
/** @return array<string, int> */
private function fetchAllContributions(): array private function fetchAllContributions(): array
{ {
$contributions = []; $contributions = [];
if ($this->githubUser !== '' && $this->githubToken !== '') { /** @var ProviderInterface $provider */
try { foreach ($this->providers as $provider) {
$contributions = $this->merge($contributions, $this->github->fetch($this->githubUser, $this->githubToken)); if (!$provider->isConfigured()) {
} catch (\Throwable $e) { continue;
$this->logger->warning('GitHub fetch failed: ' . $e->getMessage());
} }
}
if ($this->gitlabUser !== '' && $this->gitlabToken !== '') {
try { try {
$contributions = $this->merge($contributions, $this->gitlab->fetch( $contributions = $this->merge($contributions, $provider->fetch());
$this->gitlabUser,
$this->gitlabToken,
$this->gitlabUrl !== '' ? $this->gitlabUrl : 'https://gitlab.com'
));
} catch (\Throwable $e) { } catch (\Throwable $e) {
$this->logger->warning('GitLab fetch failed: ' . $e->getMessage()); $this->logger->warning(sprintf('%s fetch failed: %s', $provider::class, $e->getMessage()), ['exception' => $e]);
}
}
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());
} }
} }
return $contributions; 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 private function merge(array $base, array $new): array
{ {
foreach ($new as $date => $count) { foreach ($new as $date => $count) {
$base[$date] = ($base[$date] ?? 0) + $count; $base[$date] = ($base[$date] ?? 0) + $count;
} }
return $base; return $base;
} }
} }
+45 -24
View File
@@ -2,6 +2,9 @@
namespace App\Service; namespace App\Service;
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClient;
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClientRegistryInterface;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
/** /**
@@ -9,46 +12,58 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
* *
* Required token scopes: read:user * Required token scopes: read:user
*/ */
class GitHubProvider class GitHubProvider implements ProviderInterface
{ {
private const GRAPHQL_URL = 'https://api.github.com/graphql'; private const GRAPHQL_URL = 'https://api.github.com/graphql';
private const QUERY = <<<'GRAPHQL' public function __construct(
query($username: String!, $from: DateTime!, $to: DateTime!) { private readonly HttpClientInterface $client,
user(login: $username) { private readonly GraphQLApiClientRegistryInterface $registry,
contributionsCollection(from: $from, to: $to) { private readonly string $username,
contributionCalendar { private readonly string $token,
weeks { private readonly LoggerInterface $logger,
contributionDays { ) {}
date
contributionCount
}
}
}
}
}
}
GRAPHQL;
public function __construct(private readonly HttpClientInterface $client) {} public function isConfigured(): bool
{
return $this->username !== '' && $this->token !== '';
}
/** /**
* @return array<string, int> date (Y-m-d) => contribution count * @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'); $from = (new \DateTimeImmutable('-365 days'))->format('Y-m-d\T00:00:00\Z');
$to = (new \DateTimeImmutable())->format('Y-m-d\T23:59:59\Z'); $to = (new \DateTimeImmutable())->format('Y-m-d\T23:59:59\Z');
/** @var GraphQLApiClient $graphqlClient */
$graphqlClient = $this->registry->get('github');
$query = $graphqlClient->buildQuery(
['user' => ['login' => $this->username]],
[
'contributionsCollection' => [
'_parameters' => ['from' => $from, 'to' => $to],
'contributionCalendar' => [
'weeks' => [
'contributionDays' => ['date', 'contributionCount'],
],
],
],
]
)->getGraphQLQuery();
// GitHub's GraphQL API requires application/json — the bundle's built-in
// transport sends form_params, so we use Symfony HttpClient here instead.
$response = $this->client->request('POST', self::GRAPHQL_URL, [ $response = $this->client->request('POST', self::GRAPHQL_URL, [
'headers' => [ 'headers' => [
'Authorization' => "Bearer $token", 'Authorization' => "Bearer {$this->token}",
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
], ],
'json' => [ 'json' => ['query' => $query],
'query' => self::QUERY,
'variables' => ['username' => $username, 'from' => $from, 'to' => $to],
],
]); ]);
$data = $response->toArray(); $data = $response->toArray();
@@ -68,6 +83,12 @@ class GitHubProvider
} }
} }
$this->logger->info('GitHubProvider: fetched contributions', [
'user' => $this->username,
'days' => count($result),
'total' => array_sum($result),
]);
return $result; return $result;
} }
} }
+29 -8
View File
@@ -2,6 +2,7 @@
namespace App\Service; namespace App\Service;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
/** /**
@@ -10,26 +11,39 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
* Required token scopes: read_user, read_api * Required token scopes: read_user, read_api
* Works with both gitlab.com and self-hosted instances. * 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 * @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 // Resolve numeric user ID from username
$userResponse = $this->client->request('GET', "$baseUrl/api/v4/users", [ $userResponse = $this->client->request('GET', "$baseUrl/api/v4/users", [
'headers' => ['PRIVATE-TOKEN' => $token], 'headers' => ['PRIVATE-TOKEN' => $this->token],
'query' => ['username' => $username], 'query' => ['username' => $this->username],
]); ]);
$users = $userResponse->toArray(); $users = $userResponse->toArray();
if (empty($users)) { 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']; $userId = $users[0]['id'];
@@ -39,7 +53,7 @@ class GitLabProvider
do { do {
$response = $this->client->request('GET', "$baseUrl/api/v4/users/$userId/events", [ $response = $this->client->request('GET', "$baseUrl/api/v4/users/$userId/events", [
'headers' => ['PRIVATE-TOKEN' => $token], 'headers' => ['PRIVATE-TOKEN' => $this->token],
'query' => [ 'query' => [
'after' => $after, 'after' => $after,
'per_page' => 100, 'per_page' => 100,
@@ -57,6 +71,13 @@ class GitLabProvider
$page++; $page++;
} while (count($events) === 100); } 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; return $result;
} }
} }
+27 -6
View File
@@ -2,6 +2,7 @@
namespace App\Service; namespace App\Service;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
/** /**
@@ -12,18 +13,32 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
* *
* Required token scopes: read:user * 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 * @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, '/'); $baseUrl = rtrim($this->baseUrl, '/');
$response = $this->client->request('GET', "$baseUrl/api/v1/users/$username/heatmap", [
'headers' => ['Authorization' => "token $token"], $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(); $data = $response->toArray();
@@ -38,6 +53,12 @@ class GiteaProvider
$result[$date] = ($result[$date] ?? 0) + (int) $entry['contributions']; $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; 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;
}
+8 -8
View File
@@ -28,8 +28,7 @@ class SvgRenderer
]; ];
private const CELL = 10; // px private const CELL = 10; // px
private const GAP = 3; // px private const STEP = 13; // CELL + 3px gap
private const STEP = 13; // CELL + GAP
private const WEEKS = 53; private const WEEKS = 53;
private const MARGIN_X = 28; // left margin for day labels private const MARGIN_X = 28; // left margin for day labels
private const MARGIN_Y = 20; // top margin for month labels private const MARGIN_Y = 20; // top margin for month labels
@@ -42,7 +41,7 @@ class SvgRenderer
$today = new \DateTimeImmutable('today'); $today = new \DateTimeImmutable('today');
// align grid: last column always ends on the Saturday of the current week // align grid: last column always ends on the Saturday of the current week
$endSat = $today->modify('Saturday this week'); $endSat = $today->modify('Saturday this week');
$start = $endSat->modify('-' . (self::WEEKS - 1) . ' weeks')->modify('Sunday'); $start = $endSat->modify('-' . (self::WEEKS - 1) . ' weeks')->modify('last Sunday');
$grid = $this->buildGrid($start, $today, $contributions); $grid = $this->buildGrid($start, $today, $contributions);
$stats = $this->computeStats($contributions); $stats = $this->computeStats($contributions);
@@ -69,7 +68,7 @@ class SvgRenderer
$out .= $this->renderCells($grid, $colors); $out .= $this->renderCells($grid, $colors);
// Legend row (Less → More) // Legend row (Less → More)
$out .= $this->renderLegend($totalW, $totalH, $colors); $out .= $this->renderLegend($totalH, $colors);
// Total count // Total count
$out .= sprintf( $out .= sprintf(
@@ -196,9 +195,10 @@ class SvgRenderer
$y = self::MARGIN_Y + $d * self::STEP; $y = self::MARGIN_Y + $d * self::STEP;
$color = $colors['levels'][$this->level($cell['count'])]; $color = $colors['levels'][$this->level($cell['count'])];
$ts = strtotime($cell['date']); $ts = strtotime($cell['date']);
$label = $cell['count'] > 0 $suffix = $cell['count'] !== 1 ? 's' : '';
? $cell['count'] . ' contribution' . ($cell['count'] !== 1 ? 's' : '') . ' on ' . date('F j, Y', $ts) $label = $cell['count'] > 0
? $cell['count'] . ' contribution' . $suffix . ' on ' . date('F j, Y', $ts)
: 'No contributions on ' . date('F j, Y', $ts); : 'No contributions on ' . date('F j, Y', $ts);
$out .= sprintf( $out .= sprintf(
@@ -216,7 +216,7 @@ class SvgRenderer
return $out; return $out;
} }
private function renderLegend(int $totalW, int $totalH, array $colors): string private function renderLegend(int $totalH, array $colors): string
{ {
$y = $totalH - 14; $y = $totalH - 14;
$out = sprintf( $out = sprintf(
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Service;
use App\Service\SvgRenderer;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
#[CoversClass(SvgRenderer::class)]
final class SvgRendererTest extends TestCase
{
private SvgRenderer $renderer;
protected function setUp(): void
{
$this->renderer = new SvgRenderer();
}
#[Test]
public function it_returns_a_valid_svg_element(): void
{
$svg = $this->renderer->render([]);
$this->assertStringStartsWith('<svg', $svg);
$this->assertStringEndsWith('</svg>', $svg);
}
#[Test]
public function it_includes_accessibility_attributes(): void
{
$svg = $this->renderer->render([]);
$this->assertStringContainsString('role="img"', $svg);
$this->assertStringContainsString('aria-label="Contribution graph"', $svg);
}
#[Test]
public function it_applies_dark_theme_background_color(): void
{
$svg = $this->renderer->render([], 'dark');
$this->assertStringContainsString('#0d1117', $svg);
}
#[Test]
public function it_applies_light_theme_background_color(): void
{
$svg = $this->renderer->render([], 'light');
$this->assertStringContainsString('#ffffff', $svg);
}
#[Test]
public function it_falls_back_to_dark_theme_for_unknown_theme_names(): void
{
$svg = $this->renderer->render([], 'unknown');
$this->assertStringContainsString('#0d1117', $svg);
}
#[Test]
public function it_shows_zero_contributions_when_no_data_is_provided(): void
{
$svg = $this->renderer->render([]);
$this->assertStringContainsString('0 contributions in the last year', $svg);
}
#[Test]
public function it_displays_formatted_total_contribution_count(): void
{
$today = (new \DateTimeImmutable('today'))->format('Y-m-d');
$svg = $this->renderer->render([$today => 1234]);
$this->assertStringContainsString('1,234 contributions in the last year', $svg);
}
#[Test]
public function it_renders_all_53_week_columns(): void
{
$svg = $this->renderer->render([]);
// MARGIN_X(28) + col_52 * STEP(13) = 704
$this->assertStringContainsString('x="704"', $svg);
}
#[Test]
public function it_renders_day_of_week_labels_matching_github(): void
{
$svg = $this->renderer->render([]);
$this->assertStringContainsString('>Mon<', $svg);
$this->assertStringContainsString('>Wed<', $svg);
$this->assertStringContainsString('>Fri<', $svg);
}
#[Test]
public function it_renders_a_legend_with_less_and_more_labels(): void
{
$svg = $this->renderer->render([]);
$this->assertStringContainsString('>Less<', $svg);
$this->assertStringContainsString('>More<', $svg);
}
#[Test]
public function it_sums_contributions_from_multiple_dates(): void
{
$today = (new \DateTimeImmutable('today'))->format('Y-m-d');
$yesterday = (new \DateTimeImmutable('yesterday'))->format('Y-m-d');
$svg = $this->renderer->render([$today => 3, $yesterday => 7]);
$this->assertStringContainsString('10 contributions in the last year', $svg);
}
}