Compare commits
35
Commits
3a42bec2b7
...
0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f66c65b30 | ||
|
|
38312f549c | ||
|
|
a8d5f205db | ||
|
|
85428826a0 | ||
|
|
61b7735afc | ||
|
|
c70d96c3aa | ||
|
|
d3b9463c57 | ||
|
|
71bfb38028 | ||
|
|
225c614057 | ||
|
|
c205fed14b | ||
|
|
3e3a6752af | ||
|
|
5b07eae672 | ||
|
|
235e63bfc0 | ||
|
|
92380e534a | ||
|
|
4654a287a8 | ||
|
|
2427c07f4c | ||
|
|
7c1b893e09 | ||
|
|
4993fdca00 | ||
|
|
c4803ea5cb | ||
|
|
19bfa4cf28 | ||
|
|
e70d035672 | ||
|
|
d57320cb77 | ||
|
|
5feae97dd3 | ||
|
|
cceda8abf2 | ||
|
|
8b8ec9ab2f | ||
|
|
b3e79de069 | ||
|
|
f3770f1c2a | ||
|
|
56035096c6 | ||
|
|
381b8f4489 | ||
|
|
fa035781fd | ||
|
|
d1dce19832 | ||
|
|
0c2a185927 | ||
|
|
ff44161a99 | ||
|
|
c1fde0aed3 | ||
|
|
4ce551013e |
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1,6 @@
|
||||
.git
|
||||
.gitea
|
||||
var/
|
||||
.env.local
|
||||
.env.*.local
|
||||
docker-compose.override.yml
|
||||
@@ -1,5 +1,5 @@
|
||||
APP_ENV=prod
|
||||
APP_DEBUG=0
|
||||
APP_ENV=dev
|
||||
APP_DEBUG=1
|
||||
APP_SECRET=changeme_replace_with_random_32char_string
|
||||
|
||||
# Comma-separated list of allowed hostnames. Leave empty to allow all hosts.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# Builds and pushes a multi-arch Docker image to the Gitea container registry.
|
||||
# Triggered manually via workflow_dispatch — enter an existing semver tag (e.g. 1.2.3)
|
||||
# in the "Release tag" input. The workflow will fail early if the tag does not exist.
|
||||
#
|
||||
# Requires a repository secret REGISTRY_TOKEN — a Gitea PAT with write:package scope.
|
||||
# Create it at: Settings → Applications → Generate Token (scope: write:package)
|
||||
# Then add it: Repository → Settings → Secrets → Actions → REGISTRY_TOKEN
|
||||
#
|
||||
# After a successful run the image is available at:
|
||||
# <your-gitea-host>/<owner>/<repo>:<version>
|
||||
|
||||
name: Docker Publish
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag (semver, e.g. 1.2.3)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
build-push:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Validate tag exists
|
||||
run: |
|
||||
if ! git rev-parse "refs/tags/${{ inputs.tag }}" >/dev/null 2>&1; then
|
||||
echo "Error: tag '${{ inputs.tag }}' does not exist in this repository."
|
||||
exit 1
|
||||
fi
|
||||
git checkout "refs/tags/${{ inputs.tag }}"
|
||||
|
||||
# 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 provided release tag.
|
||||
# 1.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}},value=${{ inputs.tag }}
|
||||
type=semver,pattern={{major}}.{{minor}},value=${{ inputs.tag }}
|
||||
type=semver,pattern={{major}},value=${{ inputs.tag }}
|
||||
labels: |
|
||||
org.opencontainers.image.source=${{ gitea.server_url }}/${{ gitea.repository }}
|
||||
|
||||
# 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.REGISTRY_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
|
||||
@@ -4,3 +4,4 @@
|
||||
/var/
|
||||
/public/bundles/
|
||||
composer.lock
|
||||
/.phpunit.cache
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.1.0] - 2026-05-30
|
||||
|
||||
### Added
|
||||
|
||||
- **FrankenPHP runtime** — base image migrated from `php-cli` to FrankenPHP Alpine for better performance and built-in web server support
|
||||
- **FrankenPHP worker mode** — Symfony worker script (`public/worker.php`) with request reuse and graceful reload
|
||||
- **Caddy configuration** — `docker/frankenphp/Caddyfile` and `Caddyfile.dev` for production and development setups
|
||||
- **Provider health probes** — `ProviderInterface` extended with `ping()` and `probe()` methods; `ProbeTrait` provides the shared implementation
|
||||
- **Per-provider status on `/health`** — the health endpoint now reports `ok`, `degraded`, or `down` for each configured provider (GitHub, GitLab, Gitea), along with an error code and latency
|
||||
- **Supporting value objects** — `ProviderStatus`, `ProviderStatusType`, `ProviderErrorCode`, and `ProviderHealthChecker` service
|
||||
- **`ContributionAggregator` service** — contribution merging logic extracted from `GraphController` into a dedicated, testable service
|
||||
|
||||
### Fixed
|
||||
|
||||
- Optional environment variables (`GITLAB_URL`, `ALLOWED_HOSTS`, etc.) now have explicit empty default values in `docker-compose.yml`, preventing Docker Compose warnings on startup
|
||||
|
||||
### Changed
|
||||
|
||||
- `SvgRenderer` is now `final` and declares `strict_types=1`
|
||||
|
||||
### Tests
|
||||
|
||||
- Unit tests added for `ProbeTrait`, `ProviderHealthChecker`, `ProviderStatus`, `ContributionAggregator`, and all three provider probes (`GitHubProvider`, `GitLabProvider`, `GiteaProvider`)
|
||||
- `SvgRendererTest` refactored to follow project PHPUnit conventions (`#[Test]` attribute, `it_` prefix, Arrange/Act/Assert structure)
|
||||
|
||||
## [0.0.1] - 2025-01-01
|
||||
|
||||
### Added
|
||||
|
||||
- Initial release — GitHub, GitLab, and Gitea contribution graph as a self-hosted SVG endpoint
|
||||
- Light and dark theme support
|
||||
- Filesystem cache with 1-hour TTL
|
||||
- Docker multi-stage build (`base → deps → build → final`)
|
||||
- Basic `/health` endpoint
|
||||
|
||||
[Unreleased]: https://github.com/ArthurErlich/git-contribution-graph/compare/0.1.0...HEAD
|
||||
[0.1.0]: https://github.com/ArthurErlich/git-contribution-graph/compare/0.0.1...0.1.0
|
||||
[0.0.1]: https://github.com/ArthurErlich/git-contribution-graph/releases/tag/0.0.1
|
||||
@@ -0,0 +1,228 @@
|
||||
# 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
|
||||
|
||||
Prefer 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
|
||||
```
|
||||
|
||||
On Windows, run via WSL (If Docker Desctop is not):
|
||||
|
||||
```powershell
|
||||
wsl -e bash -c "cd /mnt/g/_DEV/repos/git-contribution-graph && docker compose exec graph vendor/bin/phpunit --testdox 2>&1"
|
||||
```
|
||||
|
||||
### 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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Gitea Workflows
|
||||
|
||||
Workflow files live in [.gitea/workflows/](.gitea/workflows/). This project uses Gitea Actions (GitHub Actions-compatible syntax).
|
||||
|
||||
**When editing workflow files:**
|
||||
|
||||
- Use `gitea.*` context variables, not `github.*` — e.g. `${{ gitea.server_url }}`, `${{ gitea.actor }}`, `${{ gitea.repository }}`
|
||||
- `GITHUB_ENV` and `GITHUB_OUTPUT` are still the correct env file names (Gitea Actions re-uses these)
|
||||
- Secrets are set under Repository → Settings → Secrets → Actions
|
||||
- The registry hostname must be derived from `gitea.server_url` (strip the protocol prefix)
|
||||
- Triggers use standard `on:` syntax; `tags: '*.*.*'` matches semver pushes without a `v` prefix
|
||||
|
||||
**Current workflows:**
|
||||
|
||||
| File | Trigger | Purpose |
|
||||
| -------------------- | ---------------- | --------------------------------------------------------- |
|
||||
| `docker-publish.yml` | Push tag `*.*.*` | Build & push multi-arch image to Gitea container registry |
|
||||
|
||||
## 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, 1–3 → 1, 4–6 → 2, 7–9 → 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.
|
||||
+39
-22
@@ -1,41 +1,58 @@
|
||||
FROM php:8.3-cli-alpine AS base
|
||||
FROM dunglas/frankenphp:1-php8.4-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
|
||||
libzip
|
||||
|
||||
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 \
|
||||
--no-scripts \
|
||||
--no-interaction \
|
||||
--optimize-autoloader \
|
||||
--prefer-dist
|
||||
--no-dev \
|
||||
--no-scripts \
|
||||
--no-interaction \
|
||||
--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 docker/frankenphp/Caddyfile.dev /etc/caddy/Caddyfile
|
||||
COPY composer.json composer.lock* ./
|
||||
RUN composer install --no-scripts --no-interaction --prefer-dist
|
||||
EXPOSE 8080
|
||||
ENV APP_ENV=dev APP_DEBUG=1
|
||||
CMD ["frankenphp", "run", "--config", "/etc/caddy/Caddyfile"]
|
||||
|
||||
# ── 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 . .
|
||||
COPY docker/frankenphp/Caddyfile /etc/caddy/Caddyfile
|
||||
|
||||
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"]
|
||||
CMD ["frankenphp", "run", "--config", "/etc/caddy/Caddyfile"]
|
||||
|
||||
@@ -6,7 +6,7 @@ A self-hosted Symfony service that merges contribution data from **GitHub**, **G
|
||||
https://your-host/graph.svg?theme=dark
|
||||
```
|
||||
|
||||

|
||||

|
||||
|
||||
---
|
||||
|
||||
@@ -27,15 +27,36 @@ https://your-host/graph.svg?theme=dark
|
||||
|
||||
- Docker + Docker Compose
|
||||
|
||||
### 1. Clone and configure
|
||||
### 1. Create a `docker-compose.yml`
|
||||
|
||||
```bash
|
||||
git clone https://git.arthurerlich.de/haylan/git-contribution-graph.git
|
||||
cd git-contribution-graph
|
||||
cp .env .env.local
|
||||
Use the pre-built image — no need to clone the repo:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
graph:
|
||||
image: git.arthurerlich.de/haylan/git-contribution-graph:latest
|
||||
ports:
|
||||
- "8080:8080"
|
||||
env_file:
|
||||
- .env.local
|
||||
volumes:
|
||||
- cache:/var/www/html/var/cache
|
||||
|
||||
volumes:
|
||||
cache:
|
||||
```
|
||||
|
||||
Edit `.env.local` with your credentials:
|
||||
The image is published to the Gitea container registry. Pull it manually with:
|
||||
|
||||
```bash
|
||||
docker pull git.arthurerlich.de/haylan/git-contribution-graph:latest
|
||||
```
|
||||
|
||||
Semver tags are published (`0`, `0.0`, `0.0.1`) alongside `latest` — see the [container registry](https://git.arthurerlich.de/haylan/-/packages/container/git-contribution-graph/latest) for all available tags.
|
||||
|
||||
### 2. Configure
|
||||
|
||||
Create a `.env.local` file next to your `docker-compose.yml`:
|
||||
|
||||
```dotenv
|
||||
APP_SECRET=<generate with: openssl rand -hex 16>
|
||||
@@ -60,7 +81,7 @@ ALLOWED_HOSTS=
|
||||
|
||||
Only configure the platforms you use — unused ones are silently skipped.
|
||||
|
||||
### 2. Start
|
||||
### 3. Start
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
@@ -68,10 +89,11 @@ docker compose up -d
|
||||
|
||||
The service listens on **port 8080** by default. Put Traefik or nginx in front of it for HTTPS.
|
||||
|
||||
### 3. Health check
|
||||
### 4. Verify
|
||||
|
||||
```
|
||||
GET /health → {"status":"ok"}
|
||||
```bash
|
||||
curl http://localhost:8080/health
|
||||
# {"status":"ok"}
|
||||
```
|
||||
|
||||
---
|
||||
@@ -104,11 +126,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 +150,8 @@ All credentials are configured via environment variables — see [Deploy](#deplo
|
||||
|
||||
## Development
|
||||
|
||||
### Local (PHP)
|
||||
|
||||
```bash
|
||||
# Install deps
|
||||
composer install
|
||||
@@ -136,24 +163,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, 1–3 → 1, 4–6 → 2, 7–9 → 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
|
||||
|
||||
+15
-5
@@ -5,10 +5,16 @@
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=8.2",
|
||||
"symfony/cache": "^7.1",
|
||||
"symfony/framework-bundle": "^7.1",
|
||||
"symfony/http-client": "^7.1",
|
||||
"symfony/runtime": "^7.1"
|
||||
"eightpoints/guzzle-bundle": "^8.6",
|
||||
"idci/graphql-client-bundle": "^2.0",
|
||||
"monolog/monolog": "^3.10",
|
||||
"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": {
|
||||
"psr-4": {
|
||||
@@ -20,6 +26,10 @@
|
||||
"App\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^11.5",
|
||||
"symfony/phpunit-bridge": "^7.4"
|
||||
},
|
||||
"config": {
|
||||
"optimize-autoloader": true,
|
||||
"sort-packages": true,
|
||||
@@ -30,7 +40,7 @@
|
||||
"extra": {
|
||||
"symfony": {
|
||||
"allow-contrib": false,
|
||||
"require": "7.1.*"
|
||||
"require": "7.4.*"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,4 +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],
|
||||
];
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
eight_points_guzzle:
|
||||
clients:
|
||||
github_graphql:
|
||||
base_url: 'https://api.github.com/graphql'
|
||||
options:
|
||||
headers:
|
||||
Authorization: 'Bearer %env(GITHUB_TOKEN)%'
|
||||
@@ -0,0 +1,4 @@
|
||||
idci_graphql_client:
|
||||
clients:
|
||||
github:
|
||||
http_client: 'eight_points_guzzle.client.github_graphql'
|
||||
@@ -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
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
parameters:
|
||||
env(APP_SECRET): ''
|
||||
env(ALLOWED_HOSTS): ''
|
||||
env(GITHUB_USER): ''
|
||||
env(GITHUB_TOKEN): ''
|
||||
env(GITLAB_USER): ''
|
||||
env(GITLAB_TOKEN): ''
|
||||
env(GITLAB_URL): ''
|
||||
env(GITEA_USER): ''
|
||||
env(GITEA_TOKEN): ''
|
||||
env(GITEA_URL): ''
|
||||
|
||||
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)%'
|
||||
@@ -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
@@ -1,6 +1,8 @@
|
||||
services:
|
||||
graph:
|
||||
build: .
|
||||
build:
|
||||
context: .
|
||||
target: final
|
||||
container_name: git-contribution-graph
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
admin off
|
||||
auto_https off
|
||||
|
||||
frankenphp {
|
||||
worker /app/public/worker.php
|
||||
}
|
||||
}
|
||||
|
||||
:8080 {
|
||||
root * /app/public
|
||||
php_server
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
admin off
|
||||
auto_https off
|
||||
debug
|
||||
|
||||
frankenphp
|
||||
}
|
||||
|
||||
:8080 {
|
||||
root * /app/public
|
||||
php_server
|
||||
}
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Disallow: /
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Kernel;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
require_once dirname(__DIR__).'/vendor/autoload.php';
|
||||
|
||||
$kernel = new Kernel($_SERVER['APP_ENV'] ?? 'prod', (bool) ($_SERVER['APP_DEBUG'] ?? false));
|
||||
$kernel->boot();
|
||||
|
||||
$handler = static function () use ($kernel): void {
|
||||
$request = Request::createFromGlobals();
|
||||
$response = $kernel->handle($request);
|
||||
$response->send();
|
||||
$kernel->terminate($request, $response);
|
||||
};
|
||||
|
||||
$maxRequests = (int) ($_SERVER['MAX_REQUESTS'] ?? 0);
|
||||
$requestCount = 0;
|
||||
|
||||
while (\frankenphp_handle_request($handler)) {
|
||||
if ($maxRequests > 0 && ++$requestCount >= $maxRequests) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$kernel->shutdown();
|
||||
@@ -1,49 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Service\GiteaProvider;
|
||||
use App\Service\GitHubProvider;
|
||||
use App\Service\GitLabProvider;
|
||||
use App\Service\ContributionAggregator;
|
||||
use App\Service\ProviderHealthChecker;
|
||||
use App\Service\SvgRenderer;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
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
|
||||
final class GraphController
|
||||
{
|
||||
/** @var list<string> */
|
||||
private readonly array $allowedHosts;
|
||||
|
||||
public function __construct(
|
||||
private readonly GitHubProvider $github,
|
||||
private readonly GitLabProvider $gitlab,
|
||||
private readonly GiteaProvider $gitea,
|
||||
private readonly ContributionAggregator $aggregator,
|
||||
private readonly SvgRenderer $renderer,
|
||||
private readonly CacheInterface $cache,
|
||||
private readonly LoggerInterface $logger,
|
||||
private readonly ProviderHealthChecker $healthChecker,
|
||||
#[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 +41,49 @@ 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->aggregator->aggregate(), $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']);
|
||||
}
|
||||
$result = $this->healthChecker->check();
|
||||
$statusCode = $result['status'] === 'degraded' ? 503 : 200;
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->gitlabUser !== '' && $this->gitlabToken !== '') {
|
||||
try {
|
||||
$contributions = $this->merge($contributions, $this->gitlab->fetch(
|
||||
$this->gitlabUser,
|
||||
$this->gitlabToken,
|
||||
$this->gitlabUrl !== '' ? $this->gitlabUrl : 'https://gitlab.com'
|
||||
));
|
||||
} 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());
|
||||
}
|
||||
}
|
||||
|
||||
return $contributions;
|
||||
}
|
||||
|
||||
/** Sum contributions by date from two maps. */
|
||||
private function merge(array $base, array $new): array
|
||||
{
|
||||
foreach ($new as $date => $count) {
|
||||
$base[$date] = ($base[$date] ?? 0) + $count;
|
||||
}
|
||||
return $base;
|
||||
return new Response(
|
||||
json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR),
|
||||
$statusCode,
|
||||
['Content-Type' => 'application/json'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
|
||||
|
||||
final class ContributionAggregator
|
||||
{
|
||||
public function __construct(
|
||||
#[AutowireIterator('app.provider')]
|
||||
private readonly iterable $providers,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
/** @return array<string, int> */
|
||||
public function aggregate(): array
|
||||
{
|
||||
$contributions = [];
|
||||
|
||||
/** @var ProviderInterface $provider */
|
||||
foreach ($this->providers as $provider) {
|
||||
if (!$provider->isConfigured()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($provider->fetch() as $date => $count) {
|
||||
$contributions[$date] = ($contributions[$date] ?? 0) + $count;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->warning(sprintf('%s fetch failed: %s', $provider::class, $e->getMessage()), ['exception' => $e]);
|
||||
}
|
||||
}
|
||||
|
||||
return $contributions;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClient;
|
||||
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClientRegistryInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
/**
|
||||
@@ -9,52 +15,78 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
*
|
||||
* Required token scopes: read:user
|
||||
*/
|
||||
class GitHubProvider
|
||||
final class GitHubProvider implements ProviderInterface
|
||||
{
|
||||
use ProbeTrait;
|
||||
|
||||
private const GRAPHQL_URL = 'https://api.github.com/graphql';
|
||||
|
||||
private const QUERY = <<<'GRAPHQL'
|
||||
query($username: String!, $from: DateTime!, $to: DateTime!) {
|
||||
user(login: $username) {
|
||||
contributionsCollection(from: $from, to: $to) {
|
||||
contributionCalendar {
|
||||
weeks {
|
||||
contributionDays {
|
||||
date
|
||||
contributionCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 __construct(private readonly HttpClientInterface $client) {}
|
||||
public function getName(): string
|
||||
{
|
||||
return 'github';
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->username !== '' && $this->token !== '';
|
||||
}
|
||||
|
||||
public function ping(): void
|
||||
{
|
||||
$this->client->request('GET', 'https://api.github.com/user', [
|
||||
'headers' => ['Authorization' => "Bearer {$this->token}"],
|
||||
])->getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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');
|
||||
|
||||
/** @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, [
|
||||
'headers' => [
|
||||
'Authorization' => "Bearer $token",
|
||||
'Authorization' => "Bearer {$this->token}",
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
'json' => [
|
||||
'query' => self::QUERY,
|
||||
'variables' => ['username' => $username, 'from' => $from, 'to' => $to],
|
||||
],
|
||||
'json' => ['query' => $query],
|
||||
]);
|
||||
|
||||
$data = $response->toArray();
|
||||
|
||||
if (isset($data['errors'])) {
|
||||
throw new \RuntimeException('GitHub GraphQL error: ' . json_encode($data['errors']));
|
||||
throw new ServiceUnavailableHttpException(null, 'GitHub GraphQL error: ' . json_encode($data['errors']));
|
||||
}
|
||||
|
||||
$result = [];
|
||||
@@ -68,6 +100,12 @@ class GitHubProvider
|
||||
}
|
||||
}
|
||||
|
||||
$this->logger->info('GitHubProvider: fetched contributions', [
|
||||
'user' => $this->username,
|
||||
'days' => count($result),
|
||||
'total' => array_sum($result),
|
||||
]);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
/**
|
||||
@@ -10,26 +14,54 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
* Required token scopes: read_user, read_api
|
||||
* Works with both gitlab.com and self-hosted instances.
|
||||
*/
|
||||
class GitLabProvider
|
||||
final class GitLabProvider implements ProviderInterface
|
||||
{
|
||||
public function __construct(private readonly HttpClientInterface $client) {}
|
||||
use ProbeTrait;
|
||||
|
||||
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 getName(): string
|
||||
{
|
||||
return 'gitlab';
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->username !== '' && $this->token !== '';
|
||||
}
|
||||
|
||||
public function ping(): void
|
||||
{
|
||||
$baseUrl = rtrim($this->baseUrl !== '' ? $this->baseUrl : 'https://gitlab.com', '/');
|
||||
|
||||
$this->client->request('GET', "$baseUrl/api/v4/user", [
|
||||
'headers' => ['PRIVATE-TOKEN' => $this->token],
|
||||
])->getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 NotFoundHttpException("GitLab: user '{$this->username}' not found on $baseUrl");
|
||||
}
|
||||
$userId = $users[0]['id'];
|
||||
|
||||
@@ -39,7 +71,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 +89,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
/**
|
||||
@@ -12,18 +15,48 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
*
|
||||
* Required token scopes: read:user
|
||||
*/
|
||||
class GiteaProvider
|
||||
final class GiteaProvider implements ProviderInterface
|
||||
{
|
||||
public function __construct(private readonly HttpClientInterface $client) {}
|
||||
use ProbeTrait;
|
||||
|
||||
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 getName(): string
|
||||
{
|
||||
return 'gitea';
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->username !== '' && $this->token !== '' && $this->baseUrl !== '';
|
||||
}
|
||||
|
||||
public function ping(): void
|
||||
{
|
||||
$baseUrl = rtrim($this->baseUrl, '/');
|
||||
|
||||
$this->client->request('GET', "$baseUrl/api/v1/user", [
|
||||
'headers' => ['Authorization' => "token {$this->token}"],
|
||||
])->getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 +71,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
||||
|
||||
trait ProbeTrait
|
||||
{
|
||||
public function probe(): ProviderStatus
|
||||
{
|
||||
if (!$this->isConfigured()) {
|
||||
return new ProviderStatus($this->getName(), ProviderStatusType::NotConfigured);
|
||||
}
|
||||
|
||||
try {
|
||||
$this->ping();
|
||||
|
||||
return new ProviderStatus($this->getName(), ProviderStatusType::Ok);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->statusFromException($e);
|
||||
}
|
||||
}
|
||||
|
||||
private function statusFromException(\Throwable $e): ProviderStatus
|
||||
{
|
||||
[$error, $message] = $this->classifyException($e);
|
||||
|
||||
return new ProviderStatus($this->getName(), ProviderStatusType::Error, $error, $message);
|
||||
}
|
||||
|
||||
/** @return array{ProviderErrorCode, string} */
|
||||
private function classifyException(\Throwable $e): array
|
||||
{
|
||||
if ($e instanceof TransportExceptionInterface) {
|
||||
return [ProviderErrorCode::UrlUnreachable, 'Could not reach the server: ' . $e->getMessage()];
|
||||
}
|
||||
|
||||
if ($e instanceof HttpExceptionInterface) {
|
||||
$code = $e->getResponse()->getStatusCode();
|
||||
|
||||
return match (true) {
|
||||
$code === 401 => [ProviderErrorCode::AuthFailed, 'Invalid or expired token — verify your credentials'],
|
||||
$code === 403 => [ProviderErrorCode::AuthFailed, 'Access denied — token lacks the required scopes'],
|
||||
$code === 404 => [ProviderErrorCode::UrlUnreachable, 'Endpoint not found — check the configured URL'],
|
||||
default => [ProviderErrorCode::Unknown, "HTTP {$code}: " . $e->getMessage()],
|
||||
};
|
||||
}
|
||||
|
||||
$msg = $e->getMessage();
|
||||
$lower = strtolower($msg);
|
||||
$error = match (true) {
|
||||
str_contains($msg, 'not found') || str_contains($msg, 'Could not resolve') => ProviderErrorCode::UserNotFound,
|
||||
str_contains($msg, 'GraphQL error')
|
||||
&& (str_contains($lower, 'unauthorized') || str_contains($lower, 'bad credentials')) => ProviderErrorCode::AuthFailed,
|
||||
default => ProviderErrorCode::Unknown,
|
||||
};
|
||||
|
||||
return [$error, $msg];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
enum ProviderErrorCode: string
|
||||
{
|
||||
case AuthFailed = 'auth_failed';
|
||||
case UrlUnreachable = 'url_unreachable';
|
||||
case UserNotFound = 'user_not_found';
|
||||
case Unknown = 'unknown';
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
|
||||
|
||||
final class ProviderHealthChecker
|
||||
{
|
||||
public function __construct(
|
||||
#[AutowireIterator('app.provider')]
|
||||
private readonly iterable $providers,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{status: string, providers: array<string, array<string, string>>}
|
||||
*/
|
||||
public function check(): array
|
||||
{
|
||||
$statuses = [];
|
||||
$hasError = false;
|
||||
|
||||
/** @var ProviderInterface $provider */
|
||||
foreach ($this->providers as $provider) {
|
||||
$status = $provider->probe();
|
||||
$statuses[$status->name] = $status->toArray();
|
||||
|
||||
if ($status->status === ProviderStatusType::Error) {
|
||||
$hasError = true;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => $hasError ? 'degraded' : 'ok',
|
||||
'providers' => $statuses,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?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;
|
||||
|
||||
public function getName(): string;
|
||||
|
||||
public function probe(): ProviderStatus;
|
||||
|
||||
public function ping(): void;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
final class ProviderStatus
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $name,
|
||||
public readonly ProviderStatusType $status,
|
||||
public readonly ?ProviderErrorCode $error = null,
|
||||
public readonly ?string $message = null,
|
||||
) {}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function toArray(): array
|
||||
{
|
||||
$data = ['status' => $this->status->value];
|
||||
if ($this->error !== null) {
|
||||
$data['error'] = $this->error->value;
|
||||
}
|
||||
if ($this->message !== null) {
|
||||
$data['message'] = $this->message;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
enum ProviderStatusType: string
|
||||
{
|
||||
case Ok = 'ok';
|
||||
case Error = 'error';
|
||||
case NotConfigured = 'not_configured';
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
/**
|
||||
@@ -11,7 +13,7 @@ namespace App\Service;
|
||||
* - Month labels above, weekday labels (Mon/Wed/Fri) on the left
|
||||
* - 5 intensity levels (0–4) matched to GitHub's colour palette
|
||||
*/
|
||||
class SvgRenderer
|
||||
final class SvgRenderer
|
||||
{
|
||||
// GitHub's exact colour tokens
|
||||
private const THEMES = [
|
||||
@@ -28,8 +30,7 @@ class SvgRenderer
|
||||
];
|
||||
|
||||
private const CELL = 10; // px
|
||||
private const GAP = 3; // px
|
||||
private const STEP = 13; // CELL + GAP
|
||||
private const STEP = 13; // CELL + 3px gap
|
||||
private const WEEKS = 53;
|
||||
private const MARGIN_X = 28; // left margin for day labels
|
||||
private const MARGIN_Y = 20; // top margin for month labels
|
||||
@@ -42,7 +43,7 @@ class SvgRenderer
|
||||
$today = new \DateTimeImmutable('today');
|
||||
// align grid: last column always ends on the Saturday of the current 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);
|
||||
$stats = $this->computeStats($contributions);
|
||||
@@ -69,7 +70,7 @@ class SvgRenderer
|
||||
$out .= $this->renderCells($grid, $colors);
|
||||
|
||||
// Legend row (Less → More)
|
||||
$out .= $this->renderLegend($totalW, $totalH, $colors);
|
||||
$out .= $this->renderLegend($totalH, $colors);
|
||||
|
||||
// Total count
|
||||
$out .= sprintf(
|
||||
@@ -196,9 +197,10 @@ class SvgRenderer
|
||||
$y = self::MARGIN_Y + $d * self::STEP;
|
||||
$color = $colors['levels'][$this->level($cell['count'])];
|
||||
|
||||
$ts = strtotime($cell['date']);
|
||||
$label = $cell['count'] > 0
|
||||
? $cell['count'] . ' contribution' . ($cell['count'] !== 1 ? 's' : '') . ' on ' . date('F j, Y', $ts)
|
||||
$ts = strtotime($cell['date']);
|
||||
$suffix = $cell['count'] !== 1 ? 's' : '';
|
||||
$label = $cell['count'] > 0
|
||||
? $cell['count'] . ' contribution' . $suffix . ' on ' . date('F j, Y', $ts)
|
||||
: 'No contributions on ' . date('F j, Y', $ts);
|
||||
|
||||
$out .= sprintf(
|
||||
@@ -216,7 +218,7 @@ class SvgRenderer
|
||||
return $out;
|
||||
}
|
||||
|
||||
private function renderLegend(int $totalW, int $totalH, array $colors): string
|
||||
private function renderLegend(int $totalH, array $colors): string
|
||||
{
|
||||
$y = $totalH - 14;
|
||||
$out = sprintf(
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\ContributionAggregator;
|
||||
use App\Service\ProviderInterface;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
#[CoversClass(ContributionAggregator::class)]
|
||||
final class ContributionAggregatorTest extends TestCase
|
||||
{
|
||||
private LoggerInterface $logger;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->logger = $this->createStub(LoggerInterface::class);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_empty_array_when_no_providers_are_given(): void
|
||||
{
|
||||
$aggregator = new ContributionAggregator([], $this->logger);
|
||||
|
||||
$result = $aggregator->aggregate();
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_skips_unconfigured_providers(): void
|
||||
{
|
||||
$provider = $this->createStub(ProviderInterface::class);
|
||||
$provider->method('isConfigured')->willReturn(false);
|
||||
|
||||
$aggregator = new ContributionAggregator([$provider], $this->logger);
|
||||
|
||||
$result = $aggregator->aggregate();
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_contributions_from_a_configured_provider(): void
|
||||
{
|
||||
$provider = $this->createStub(ProviderInterface::class);
|
||||
$provider->method('isConfigured')->willReturn(true);
|
||||
$provider->method('fetch')->willReturn(['2024-01-01' => 3]);
|
||||
|
||||
$aggregator = new ContributionAggregator([$provider], $this->logger);
|
||||
|
||||
$result = $aggregator->aggregate();
|
||||
|
||||
$this->assertSame(['2024-01-01' => 3], $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_sums_contributions_from_multiple_providers_on_the_same_date(): void
|
||||
{
|
||||
$providerA = $this->createStub(ProviderInterface::class);
|
||||
$providerA->method('isConfigured')->willReturn(true);
|
||||
$providerA->method('fetch')->willReturn(['2024-01-01' => 3, '2024-01-02' => 1]);
|
||||
|
||||
$providerB = $this->createStub(ProviderInterface::class);
|
||||
$providerB->method('isConfigured')->willReturn(true);
|
||||
$providerB->method('fetch')->willReturn(['2024-01-01' => 2, '2024-01-03' => 5]);
|
||||
|
||||
$aggregator = new ContributionAggregator([$providerA, $providerB], $this->logger);
|
||||
|
||||
$result = $aggregator->aggregate();
|
||||
|
||||
$this->assertSame(['2024-01-01' => 5, '2024-01-02' => 1, '2024-01-03' => 5], $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_continues_fetching_remaining_providers_when_one_throws(): void
|
||||
{
|
||||
$failing = $this->createStub(ProviderInterface::class);
|
||||
$failing->method('isConfigured')->willReturn(true);
|
||||
$failing->method('fetch')->willThrowException(new \RuntimeException('Network error'));
|
||||
|
||||
$healthy = $this->createStub(ProviderInterface::class);
|
||||
$healthy->method('isConfigured')->willReturn(true);
|
||||
$healthy->method('fetch')->willReturn(['2024-01-01' => 7]);
|
||||
|
||||
$aggregator = new ContributionAggregator([$failing, $healthy], $this->logger);
|
||||
|
||||
$result = $aggregator->aggregate();
|
||||
|
||||
$this->assertSame(['2024-01-01' => 7], $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_logs_a_warning_when_a_provider_fetch_throws(): void
|
||||
{
|
||||
$logger = $this->createMock(LoggerInterface::class);
|
||||
$logger->expects($this->once())->method('warning');
|
||||
|
||||
$provider = $this->createStub(ProviderInterface::class);
|
||||
$provider->method('isConfigured')->willReturn(true);
|
||||
$provider->method('fetch')->willThrowException(new \RuntimeException('fail'));
|
||||
|
||||
(new ContributionAggregator([$provider], $logger))->aggregate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\GitHubProvider;
|
||||
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClient;
|
||||
use IDCI\Bundle\GraphQLClientBundle\Client\GraphQLApiClientRegistryInterface;
|
||||
use IDCI\Bundle\GraphQLClientBundle\Query\GraphQLQuery;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
#[CoversClass(GitHubProvider::class)]
|
||||
final class GitHubProviderTest extends TestCase
|
||||
{
|
||||
private function makeProvider(
|
||||
string $username = 'user',
|
||||
string $token = 'token',
|
||||
?HttpClientInterface $client = null,
|
||||
?GraphQLApiClientRegistryInterface $registry = null,
|
||||
): GitHubProvider {
|
||||
if ($registry === null) {
|
||||
$graphqlQuery = $this->createStub(GraphQLQuery::class);
|
||||
$graphqlQuery->method('getGraphQLQuery')->willReturn('query {}');
|
||||
|
||||
$graphqlClient = $this->createStub(GraphQLApiClient::class);
|
||||
$graphqlClient->method('buildQuery')->willReturn($graphqlQuery);
|
||||
|
||||
$registry = $this->createStub(GraphQLApiClientRegistryInterface::class);
|
||||
$registry->method('get')->willReturn($graphqlClient);
|
||||
}
|
||||
|
||||
return new GitHubProvider(
|
||||
$client ?? $this->createStub(HttpClientInterface::class),
|
||||
$registry,
|
||||
$username,
|
||||
$token,
|
||||
$this->createStub(LoggerInterface::class),
|
||||
);
|
||||
}
|
||||
|
||||
private function stubGraphqlResponse(array $weeks): ResponseInterface
|
||||
{
|
||||
$response = $this->createStub(ResponseInterface::class);
|
||||
$response->method('toArray')->willReturn([
|
||||
'data' => [
|
||||
'user' => [
|
||||
'contributionsCollection' => [
|
||||
'contributionCalendar' => ['weeks' => $weeks],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_github_as_name(): void
|
||||
{
|
||||
$this->assertSame('github', $this->makeProvider()->getName());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_configured_when_credentials_are_set(): void
|
||||
{
|
||||
$this->assertTrue($this->makeProvider()->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_not_configured_when_username_is_empty(): void
|
||||
{
|
||||
$this->assertFalse($this->makeProvider(username: '')->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_not_configured_when_token_is_empty(): void
|
||||
{
|
||||
$this->assertFalse($this->makeProvider(token: '')->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_parses_contribution_days_from_the_graphql_response(): void
|
||||
{
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubGraphqlResponse([
|
||||
['contributionDays' => [
|
||||
['date' => '2024-06-10', 'contributionCount' => 4],
|
||||
['date' => '2024-06-11', 'contributionCount' => 2],
|
||||
]],
|
||||
]));
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertSame(4, $result['2024-06-10']);
|
||||
$this->assertSame(2, $result['2024-06-11']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_skips_days_with_zero_contributions(): void
|
||||
{
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubGraphqlResponse([
|
||||
['contributionDays' => [
|
||||
['date' => '2024-06-11', 'contributionCount' => 0],
|
||||
]],
|
||||
]));
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertArrayNotHasKey('2024-06-11', $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_throws_service_unavailable_exception_on_graphql_errors(): void
|
||||
{
|
||||
$response = $this->createStub(ResponseInterface::class);
|
||||
$response->method('toArray')->willReturn([
|
||||
'errors' => [['message' => 'Bad credentials']],
|
||||
]);
|
||||
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($response);
|
||||
|
||||
$this->expectException(ServiceUnavailableHttpException::class);
|
||||
|
||||
$this->makeProvider(client: $client)->fetch();
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_empty_when_response_has_no_weeks(): void
|
||||
{
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubGraphqlResponse([]));
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\GitLabProvider;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
#[CoversClass(GitLabProvider::class)]
|
||||
final class GitLabProviderTest extends TestCase
|
||||
{
|
||||
private function makeProvider(
|
||||
string $username = 'user',
|
||||
string $token = 'token',
|
||||
string $baseUrl = '',
|
||||
?HttpClientInterface $client = null,
|
||||
): GitLabProvider {
|
||||
return new GitLabProvider(
|
||||
$client ?? $this->createStub(HttpClientInterface::class),
|
||||
$username,
|
||||
$token,
|
||||
$this->createStub(LoggerInterface::class),
|
||||
$baseUrl,
|
||||
);
|
||||
}
|
||||
|
||||
private function stubResponse(array $data): ResponseInterface
|
||||
{
|
||||
$response = $this->createStub(ResponseInterface::class);
|
||||
$response->method('toArray')->willReturn($data);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_gitlab_as_name(): void
|
||||
{
|
||||
$this->assertSame('gitlab', $this->makeProvider()->getName());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_configured_when_credentials_are_set(): void
|
||||
{
|
||||
$this->assertTrue($this->makeProvider()->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_not_configured_when_username_is_empty(): void
|
||||
{
|
||||
$this->assertFalse($this->makeProvider(username: '')->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_not_configured_when_token_is_empty(): void
|
||||
{
|
||||
$this->assertFalse($this->makeProvider(token: '')->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_throws_not_found_exception_when_user_does_not_exist(): void
|
||||
{
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubResponse([]));
|
||||
|
||||
$this->expectException(NotFoundHttpException::class);
|
||||
|
||||
$this->makeProvider(client: $client)->fetch();
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_fetches_events_and_counts_them_by_date(): void
|
||||
{
|
||||
$client = $this->createMock(HttpClientInterface::class);
|
||||
$client->method('request')->willReturnCallback(
|
||||
function (string $method, string $url): ResponseInterface {
|
||||
if (str_contains($url, '/events')) {
|
||||
return $this->stubResponse([
|
||||
['created_at' => '2024-06-10T12:00:00.000Z'],
|
||||
['created_at' => '2024-06-10T14:00:00.000Z'],
|
||||
['created_at' => '2024-06-11T08:00:00.000Z'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->stubResponse([['id' => 42]]);
|
||||
}
|
||||
);
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertSame(2, $result['2024-06-10']);
|
||||
$this->assertSame(1, $result['2024-06-11']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_fetches_multiple_pages_until_page_has_fewer_than_100_events(): void
|
||||
{
|
||||
$callCount = 0;
|
||||
|
||||
$client = $this->createMock(HttpClientInterface::class);
|
||||
$client->method('request')->willReturnCallback(
|
||||
function (string $method, string $url) use (&$callCount): ResponseInterface {
|
||||
if (!str_contains($url, '/events')) {
|
||||
return $this->stubResponse([['id' => 42]]);
|
||||
}
|
||||
|
||||
$callCount++;
|
||||
$data = $callCount === 1
|
||||
? array_fill(0, 100, ['created_at' => '2024-06-10T12:00:00.000Z'])
|
||||
: [['created_at' => '2024-06-11T08:00:00.000Z']];
|
||||
|
||||
return $this->stubResponse($data);
|
||||
}
|
||||
);
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertSame(2, $callCount);
|
||||
$this->assertSame(100, $result['2024-06-10']);
|
||||
$this->assertSame(1, $result['2024-06-11']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\GiteaProvider;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
#[CoversClass(GiteaProvider::class)]
|
||||
final class GiteaProviderTest extends TestCase
|
||||
{
|
||||
private function makeProvider(
|
||||
string $username = 'user',
|
||||
string $token = 'token',
|
||||
string $baseUrl = 'https://gitea.example.com',
|
||||
?HttpClientInterface $client = null,
|
||||
): GiteaProvider {
|
||||
return new GiteaProvider(
|
||||
$client ?? $this->createStub(HttpClientInterface::class),
|
||||
$username,
|
||||
$token,
|
||||
$baseUrl,
|
||||
$this->createStub(LoggerInterface::class),
|
||||
);
|
||||
}
|
||||
|
||||
private function stubResponse(array $data): ResponseInterface
|
||||
{
|
||||
$response = $this->createStub(ResponseInterface::class);
|
||||
$response->method('toArray')->willReturn($data);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_gitea_as_name(): void
|
||||
{
|
||||
$this->assertSame('gitea', $this->makeProvider()->getName());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_configured_when_all_credentials_are_set(): void
|
||||
{
|
||||
$this->assertTrue($this->makeProvider()->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_not_configured_when_username_is_empty(): void
|
||||
{
|
||||
$this->assertFalse($this->makeProvider(username: '')->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_not_configured_when_token_is_empty(): void
|
||||
{
|
||||
$this->assertFalse($this->makeProvider(token: '')->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_not_configured_when_base_url_is_empty(): void
|
||||
{
|
||||
$this->assertFalse($this->makeProvider(baseUrl: '')->isConfigured());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_parses_heatmap_entries_into_contributions(): void
|
||||
{
|
||||
$now = time();
|
||||
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubResponse([
|
||||
['timestamp' => $now, 'contributions' => 5],
|
||||
]));
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertSame(5, $result[date('Y-m-d', $now)]);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_filters_out_entries_older_than_365_days(): void
|
||||
{
|
||||
$old = (new \DateTimeImmutable('-366 days'))->getTimestamp();
|
||||
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubResponse([
|
||||
['timestamp' => $old, 'contributions' => 3],
|
||||
]));
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_empty_when_response_has_no_entries(): void
|
||||
{
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubResponse([]));
|
||||
|
||||
$result = $this->makeProvider(client: $client)->fetch();
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\ProbeTrait;
|
||||
use App\Service\ProviderErrorCode;
|
||||
use App\Service\ProviderInterface;
|
||||
use App\Service\ProviderStatusType;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
#[CoversClass(ProbeTrait::class)]
|
||||
final class ProbeTraitTest extends TestCase
|
||||
{
|
||||
private function makeProvider(bool $configured, \Closure $ping): ProviderInterface
|
||||
{
|
||||
return new class($configured, $ping) implements ProviderInterface {
|
||||
use ProbeTrait;
|
||||
|
||||
public function __construct(
|
||||
private bool $configured,
|
||||
private \Closure $ping,
|
||||
) {}
|
||||
|
||||
public function isConfigured(): bool { return $this->configured; }
|
||||
public function getName(): string { return 'test'; }
|
||||
public function ping(): void { ($this->ping)(); }
|
||||
public function fetch(): array { return []; }
|
||||
};
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_not_configured_when_provider_is_not_configured(): void
|
||||
{
|
||||
$provider = $this->makeProvider(false, fn() => null);
|
||||
|
||||
$status = $provider->probe();
|
||||
|
||||
$this->assertSame(ProviderStatusType::NotConfigured, $status->status);
|
||||
$this->assertNull($status->error);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_ok_when_ping_succeeds(): void
|
||||
{
|
||||
$provider = $this->makeProvider(true, fn() => null);
|
||||
|
||||
$status = $provider->probe();
|
||||
|
||||
$this->assertSame(ProviderStatusType::Ok, $status->status);
|
||||
$this->assertNull($status->error);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_url_unreachable_on_transport_failure(): void
|
||||
{
|
||||
$exception = $this->createStub(TransportExceptionInterface::class);
|
||||
$provider = $this->makeProvider(true, fn() => throw $exception);
|
||||
|
||||
$status = $provider->probe();
|
||||
|
||||
$this->assertSame(ProviderStatusType::Error, $status->status);
|
||||
$this->assertSame(ProviderErrorCode::UrlUnreachable, $status->error);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_auth_failed_on_401(): void
|
||||
{
|
||||
$response = $this->createStub(ResponseInterface::class);
|
||||
$response->method('getStatusCode')->willReturn(401);
|
||||
|
||||
$exception = $this->createStub(ClientExceptionInterface::class);
|
||||
$exception->method('getResponse')->willReturn($response);
|
||||
|
||||
$status = $this->makeProvider(true, fn() => throw $exception)->probe();
|
||||
|
||||
$this->assertSame(ProviderStatusType::Error, $status->status);
|
||||
$this->assertSame(ProviderErrorCode::AuthFailed, $status->error);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_auth_failed_on_403(): void
|
||||
{
|
||||
$response = $this->createStub(ResponseInterface::class);
|
||||
$response->method('getStatusCode')->willReturn(403);
|
||||
|
||||
$exception = $this->createStub(ClientExceptionInterface::class);
|
||||
$exception->method('getResponse')->willReturn($response);
|
||||
|
||||
$status = $this->makeProvider(true, fn() => throw $exception)->probe();
|
||||
|
||||
$this->assertSame(ProviderStatusType::Error, $status->status);
|
||||
$this->assertSame(ProviderErrorCode::AuthFailed, $status->error);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_url_unreachable_on_404(): void
|
||||
{
|
||||
$response = $this->createStub(ResponseInterface::class);
|
||||
$response->method('getStatusCode')->willReturn(404);
|
||||
|
||||
$exception = $this->createStub(ClientExceptionInterface::class);
|
||||
$exception->method('getResponse')->willReturn($response);
|
||||
|
||||
$status = $this->makeProvider(true, fn() => throw $exception)->probe();
|
||||
|
||||
$this->assertSame(ProviderStatusType::Error, $status->status);
|
||||
$this->assertSame(ProviderErrorCode::UrlUnreachable, $status->error);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_unknown_error_on_unexpected_exception(): void
|
||||
{
|
||||
$provider = $this->makeProvider(true, fn() => throw new \RuntimeException('Something went wrong'));
|
||||
|
||||
$status = $provider->probe();
|
||||
|
||||
$this->assertSame(ProviderStatusType::Error, $status->status);
|
||||
$this->assertSame(ProviderErrorCode::Unknown, $status->error);
|
||||
$this->assertSame('Something went wrong', $status->message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\ProviderErrorCode;
|
||||
use App\Service\ProviderHealthChecker;
|
||||
use App\Service\ProviderInterface;
|
||||
use App\Service\ProviderStatus;
|
||||
use App\Service\ProviderStatusType;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
#[CoversClass(ProviderHealthChecker::class)]
|
||||
final class ProviderHealthCheckerTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_returns_ok_when_all_providers_are_healthy(): void
|
||||
{
|
||||
$provider = $this->createStub(ProviderInterface::class);
|
||||
$provider->method('probe')->willReturn(new ProviderStatus('test', ProviderStatusType::Ok));
|
||||
|
||||
$result = (new ProviderHealthChecker([$provider]))->check();
|
||||
|
||||
$this->assertSame('ok', $result['status']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_degraded_when_a_provider_has_an_error(): void
|
||||
{
|
||||
$provider = $this->createStub(ProviderInterface::class);
|
||||
$provider->method('probe')->willReturn(
|
||||
new ProviderStatus('test', ProviderStatusType::Error, ProviderErrorCode::AuthFailed, 'Invalid token'),
|
||||
);
|
||||
|
||||
$result = (new ProviderHealthChecker([$provider]))->check();
|
||||
|
||||
$this->assertSame('degraded', $result['status']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_does_not_degrade_when_a_provider_is_not_configured(): void
|
||||
{
|
||||
$provider = $this->createStub(ProviderInterface::class);
|
||||
$provider->method('probe')->willReturn(new ProviderStatus('test', ProviderStatusType::NotConfigured));
|
||||
|
||||
$result = (new ProviderHealthChecker([$provider]))->check();
|
||||
|
||||
$this->assertSame('ok', $result['status']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_indexes_provider_statuses_by_name(): void
|
||||
{
|
||||
$provider = $this->createStub(ProviderInterface::class);
|
||||
$provider->method('probe')->willReturn(new ProviderStatus('github', ProviderStatusType::Ok));
|
||||
|
||||
$result = (new ProviderHealthChecker([$provider]))->check();
|
||||
|
||||
$this->assertArrayHasKey('github', $result['providers']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_ok_with_no_providers(): void
|
||||
{
|
||||
$result = (new ProviderHealthChecker([]))->check();
|
||||
|
||||
$this->assertSame('ok', $result['status']);
|
||||
$this->assertSame([], $result['providers']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_includes_all_provider_statuses_in_output(): void
|
||||
{
|
||||
$github = $this->createStub(ProviderInterface::class);
|
||||
$github->method('probe')->willReturn(new ProviderStatus('github', ProviderStatusType::Ok));
|
||||
|
||||
$gitlab = $this->createStub(ProviderInterface::class);
|
||||
$gitlab->method('probe')->willReturn(new ProviderStatus('gitlab', ProviderStatusType::NotConfigured));
|
||||
|
||||
$result = (new ProviderHealthChecker([$github, $gitlab]))->check();
|
||||
|
||||
$this->assertArrayHasKey('github', $result['providers']);
|
||||
$this->assertArrayHasKey('gitlab', $result['providers']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\ProviderErrorCode;
|
||||
use App\Service\ProviderStatus;
|
||||
use App\Service\ProviderStatusType;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
#[CoversClass(ProviderStatus::class)]
|
||||
final class ProviderStatusTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_serializes_ok_status(): void
|
||||
{
|
||||
$status = new ProviderStatus('github', ProviderStatusType::Ok);
|
||||
|
||||
$this->assertSame(['status' => 'ok'], $status->toArray());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_serializes_not_configured_status(): void
|
||||
{
|
||||
$status = new ProviderStatus('github', ProviderStatusType::NotConfigured);
|
||||
|
||||
$this->assertSame(['status' => 'not_configured'], $status->toArray());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_serializes_error_status_with_code_and_message(): void
|
||||
{
|
||||
$status = new ProviderStatus('github', ProviderStatusType::Error, ProviderErrorCode::AuthFailed, 'Token expired');
|
||||
|
||||
$this->assertSame([
|
||||
'status' => 'error',
|
||||
'error' => 'auth_failed',
|
||||
'message' => 'Token expired',
|
||||
], $status->toArray());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_omits_null_error_fields_from_array(): void
|
||||
{
|
||||
$status = new ProviderStatus('github', ProviderStatusType::Ok);
|
||||
|
||||
$array = $status->toArray();
|
||||
|
||||
$this->assertArrayNotHasKey('error', $array);
|
||||
$this->assertArrayNotHasKey('message', $array);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_exposes_typed_status_property(): void
|
||||
{
|
||||
$status = new ProviderStatus('github', ProviderStatusType::Error, ProviderErrorCode::Unknown, 'msg');
|
||||
|
||||
$this->assertSame(ProviderStatusType::Error, $status->status);
|
||||
$this->assertSame(ProviderErrorCode::Unknown, $status->error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\SvgRenderer;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
#[CoversClass(SvgRenderer::class)]
|
||||
final class SvgRendererTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_returns_an_svg_opening_tag(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
$this->assertStringStartsWith('<svg', $svg);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_a_closed_svg_element(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
$this->assertStringEndsWith('</svg>', $svg);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_includes_role_img_attribute_for_accessibility(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
$this->assertStringContainsString('role="img"', $svg);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_includes_aria_label_attribute_for_accessibility(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
$this->assertStringContainsString('aria-label="Contribution graph"', $svg);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
#[DataProvider('theme_background_provider')]
|
||||
public function it_applies_background_color_for_theme(string $theme, string $expectedColor): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([], $theme);
|
||||
|
||||
$this->assertStringContainsString($expectedColor, $svg);
|
||||
}
|
||||
|
||||
public static function theme_background_provider(): iterable
|
||||
{
|
||||
yield 'dark theme' => ['dark', '#0d1117'];
|
||||
yield 'light theme' => ['light', '#ffffff'];
|
||||
yield 'unknown theme' => ['unknown', '#0d1117'];
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_shows_zero_contributions_when_no_data_is_provided(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->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 = (new SvgRenderer())->render([$today => 1234]);
|
||||
|
||||
$this->assertStringContainsString('1,234 contributions in the last year', $svg);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_renders_all_53_week_columns(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
// MARGIN_X(28) + col_52 * STEP(13) = 704
|
||||
$this->assertStringContainsString('x="704"', $svg);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
#[DataProvider('day_of_week_label_provider')]
|
||||
public function it_renders_day_of_week_label(string $label): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
$this->assertStringContainsString('>' . $label . '<', $svg);
|
||||
}
|
||||
|
||||
public static function day_of_week_label_provider(): iterable
|
||||
{
|
||||
yield 'Monday' => ['Mon'];
|
||||
yield 'Wednesday' => ['Wed'];
|
||||
yield 'Friday' => ['Fri'];
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_renders_a_less_label_in_the_legend(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
$this->assertStringContainsString('>Less<', $svg);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_renders_a_more_label_in_the_legend(): void
|
||||
{
|
||||
$svg = (new SvgRenderer())->render([]);
|
||||
|
||||
$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 = (new SvgRenderer())->render([$today => 3, $yesterday => 7]);
|
||||
|
||||
$this->assertStringContainsString('10 contributions in the last year', $svg);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user