Compare commits
74
Commits
0.0.1
..
a76ed6efc8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a76ed6efc8 | ||
|
|
bce564d68b | ||
|
|
b3dc7a2298 | ||
|
|
9087f91855 | ||
|
|
885dec357e | ||
|
|
78e7a72ee9 | ||
|
|
c929fdfda6 | ||
|
|
3d2c0487b7 | ||
|
|
cb89a1c6b9 | ||
|
|
5e27a5bc93 | ||
|
|
f52a3449c6 | ||
|
|
ca94b80beb | ||
|
|
cd326a34ba | ||
|
|
8fb7781227 | ||
|
|
1e2f022579 | ||
|
|
c89b4e9212 | ||
|
|
5c47888a49 | ||
|
|
f2bf24994c | ||
|
|
fcf841f7ad | ||
|
|
9b631f4777 | ||
|
|
596260bb85 | ||
|
|
9f3c54afd1 | ||
|
|
11bec43bbe | ||
|
|
09c0be8312 | ||
|
|
6d6680ca37 | ||
|
|
406da07397 | ||
|
|
d5d948f423 | ||
|
|
a6e904fc61 | ||
|
|
980463f715 | ||
|
|
095b9675f9 | ||
|
|
8dbfef8496 | ||
|
|
a527eada56 | ||
|
|
423ac5470d | ||
|
|
4e992c8f79 | ||
|
|
4983492088 | ||
|
|
169fa8c76a | ||
|
|
4cefba1a37 | ||
|
|
28a0916487 | ||
|
|
4cfa61f1c0 | ||
|
|
2f3268c0b7 | ||
|
|
89d0e2b0f6 | ||
|
|
fad176419c | ||
|
|
3743ba31d2 | ||
|
|
8a675cf02f | ||
|
|
20c5acc5ae | ||
|
|
21867256e8 | ||
|
|
67d4a50ee1 | ||
|
|
e72ee2541e | ||
|
|
ecdb8c1716 | ||
|
|
841f4329de | ||
|
|
50256c97ef | ||
|
|
2f66c65b30 | ||
|
|
38312f549c | ||
|
|
a8d5f205db | ||
|
|
85428826a0 | ||
|
|
61b7735afc | ||
|
|
c70d96c3aa | ||
|
|
d3b9463c57 | ||
|
|
71bfb38028 | ||
|
|
225c614057 | ||
|
|
c205fed14b | ||
|
|
3e3a6752af | ||
|
|
5b07eae672 | ||
|
|
235e63bfc0 | ||
|
|
92380e534a | ||
|
|
4654a287a8 | ||
|
|
2427c07f4c | ||
|
|
7c1b893e09 | ||
|
|
4993fdca00 | ||
|
|
c4803ea5cb | ||
|
|
19bfa4cf28 | ||
|
|
e70d035672 | ||
|
|
d57320cb77 | ||
|
|
5feae97dd3 |
+1
-10
@@ -1,10 +1 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"command": "php bin/phpunit 2>&1 | tail -20"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
{}
|
||||
+32
-1
@@ -1,6 +1,37 @@
|
||||
# Build descriptors (not application code)
|
||||
Dockerfile*
|
||||
|
||||
# Version control
|
||||
.git
|
||||
.gitea
|
||||
|
||||
# AI / IDE tooling
|
||||
.claude
|
||||
|
||||
# Dev tooling
|
||||
.gitignore
|
||||
/.phpunit.cache
|
||||
phpunit.xml.dist
|
||||
tests/
|
||||
|
||||
# Documentation
|
||||
CHANGELOG.md
|
||||
CLAUDE.md
|
||||
README.md
|
||||
|
||||
# Compose / deployment descriptors (not app code)
|
||||
docker-compose.yml
|
||||
docker-compose.override.yml
|
||||
docker-compose.prod.yml
|
||||
|
||||
# Dependencies — re-installed from lockfile in the build stage;
|
||||
# a local vendor/ in the build context would silently override the clean install
|
||||
vendor/
|
||||
|
||||
# Runtime dirs (generated at build or run time, not from source)
|
||||
var/
|
||||
|
||||
# Env files — .env contains only placeholder defaults and is needed by composer dump-env;
|
||||
# local overrides with real secrets stay excluded
|
||||
.env.local
|
||||
.env.*.local
|
||||
docker-compose.override.yml
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
APP_ENV=dev
|
||||
APP_DEBUG=0
|
||||
APP_DEBUG=1
|
||||
APP_SECRET=changeme_replace_with_random_32char_string
|
||||
|
||||
# Comma-separated list of allowed hostnames. Leave empty to allow all hosts.
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Builds and pushes a multi-arch Docker image to the Gitea container registry
|
||||
# whenever a semver tag (v*.*.*) is pushed.
|
||||
# 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.
|
||||
#
|
||||
# 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).
|
||||
# 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>
|
||||
@@ -12,17 +12,33 @@
|
||||
name: Docker Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
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
|
||||
@@ -30,17 +46,17 @@ jobs:
|
||||
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
|
||||
# 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}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}}
|
||||
type=semver,pattern={{version}},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
|
||||
@@ -55,12 +71,24 @@ jobs:
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.GITEA_TOKEN }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
# Build a single-arch image locally so Trivy can inspect it before the real push.
|
||||
- name: Build local image for scanning
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
target: final
|
||||
platforms: linux/amd64
|
||||
load: true
|
||||
tags: scan-target:${{ inputs.tag }}
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ gitea.repository }}:buildcache
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
target: final
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
|
||||
@@ -3,5 +3,4 @@
|
||||
/vendor/
|
||||
/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
|
||||
@@ -76,15 +76,16 @@ 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 |
|
||||
| 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`
|
||||
|
||||
Prefer to use the tests in `docker compose exec graph`
|
||||
|
||||
```bash
|
||||
# Run full suite
|
||||
@@ -100,6 +101,12 @@ vendor/bin/phpunit tests/Unit/Service/SvgRendererTest.php
|
||||
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:
|
||||
@@ -117,6 +124,24 @@ Add to `.claude/settings.json` to run PHPUnit automatically after every file edi
|
||||
}
|
||||
```
|
||||
|
||||
## 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
|
||||
@@ -191,13 +216,13 @@ GET /graph.svg?theme=dark|light
|
||||
|
||||
## 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 |
|
||||
| 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.
|
||||
|
||||
+34
-31
@@ -1,10 +1,16 @@
|
||||
FROM php:8.3-cli-alpine AS base
|
||||
#syntax=docker/dockerfile:1
|
||||
|
||||
RUN apk add --no-cache \
|
||||
curl \
|
||||
icu-libs \
|
||||
libzip \
|
||||
&& docker-php-ext-install opcache
|
||||
FROM dunglas/frankenphp:1-php8.4-alpine AS base
|
||||
|
||||
RUN apk add --no-cache icu-dev libzip-dev \
|
||||
&& docker-php-ext-install -j$(nproc) intl opcache zip \
|
||||
&& apk del icu-dev libzip-dev \
|
||||
&& apk add --no-cache curl icu-libs libzip \
|
||||
&& cp "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" \
|
||||
&& mkdir -p $PHP_INI_DIR/app.conf.d
|
||||
|
||||
ENV PHP_INI_SCAN_DIR=":$PHP_INI_DIR/app.conf.d"
|
||||
ENV COMPOSER_ALLOW_SUPERUSER=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -13,45 +19,42 @@ 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
|
||||
|
||||
# ── 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"]
|
||||
RUN composer dump-autoload --classmap-authoritative --no-dev --no-interaction && \
|
||||
mkdir -p var/cache var/log && \
|
||||
APP_ENV=prod APP_SECRET=placeholder php bin/console cache:warmup --no-debug && \
|
||||
composer dump-env prod
|
||||
|
||||
# ── final (prod) stage — no composer binary ────────────────────────────────────
|
||||
FROM base AS final
|
||||
|
||||
RUN addgroup -S app && adduser -S -G app app
|
||||
|
||||
COPY --from=build /app/vendor /app/vendor
|
||||
COPY . .
|
||||
COPY --link --from=build /app/vendor /app/vendor
|
||||
COPY --link --from=build /app/var/cache/prod /app/var/cache/prod
|
||||
COPY --link bin/ ./bin/
|
||||
COPY --link config/ ./config/
|
||||
COPY --link public/ ./public/
|
||||
COPY --link src/ ./src/
|
||||
COPY --link composer.json composer.lock ./
|
||||
COPY --link docker/frankenphp/Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --link docker/php/conf.d/20-app.prod.ini $PHP_INI_DIR/app.conf.d/
|
||||
|
||||
RUN mkdir -p var/cache var/log \
|
||||
&& chown -R app:app /app
|
||||
RUN chmod +x bin/console && \
|
||||
mkdir -p var/cache/prod/pools var/log /config/caddy /data/caddy && \
|
||||
chown -R app:app /app /config /data
|
||||
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
ENV APP_ENV=prod APP_DEBUG=0
|
||||
|
||||
CMD ["php", "-S", "0.0.0.0:8080", "-t", "public", "public/index.php"]
|
||||
CMD ["frankenphp", "run", "--config", "/etc/caddy/Caddyfile"]
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
FROM dunglas/frankenphp:1-php8.4-alpine AS dev
|
||||
|
||||
RUN apk add --no-cache icu-dev libzip-dev \
|
||||
&& docker-php-ext-install -j$(nproc) intl opcache zip \
|
||||
&& apk del icu-dev libzip-dev \
|
||||
&& apk add --no-cache curl icu-libs libzip \
|
||||
&& cp "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini" \
|
||||
&& mkdir -p $PHP_INI_DIR/app.conf.d
|
||||
|
||||
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}
|
||||
|
||||
ENV PHP_INI_SCAN_DIR=":$PHP_INI_DIR/app.conf.d"
|
||||
ENV COMPOSER_ALLOW_SUPERUSER=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY docker/php/xdebug.ini /usr/local/etc/php/conf.d/docker-xdebug.ini
|
||||
COPY docker/php/conf.d/20-app.dev.ini $PHP_INI_DIR/app.conf.d/
|
||||
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"]
|
||||
@@ -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
|
||||
|
||||
```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"}
|
||||
```
|
||||
|
||||
---
|
||||
@@ -153,7 +175,7 @@ docker compose up -d --build
|
||||
docker compose exec graph sh
|
||||
|
||||
# Run tests inside the container
|
||||
docker compose exec graph php bin/phpunit
|
||||
docker compose exec graph vendor/bin/phpunit
|
||||
|
||||
# Disable Xdebug for faster test runs
|
||||
XDEBUG_MODE=off docker compose up -d
|
||||
@@ -173,16 +195,16 @@ docker compose -f docker-compose.yml up -d --build
|
||||
|
||||
```bash
|
||||
# Run full suite
|
||||
php bin/phpunit
|
||||
vendor/bin/phpunit
|
||||
|
||||
# Human-readable output
|
||||
php bin/phpunit --testdox
|
||||
vendor/bin/phpunit --testdox
|
||||
|
||||
# Single file
|
||||
php bin/phpunit tests/Unit/Service/SvgRendererTest.php
|
||||
vendor/bin/phpunit tests/Unit/Service/SvgRendererTest.php
|
||||
|
||||
# Filter by name
|
||||
php bin/phpunit --filter it_renders
|
||||
vendor/bin/phpunit --filter it_renders
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
# TODO: persist contribution history in SQLite + audit cleanup
|
||||
|
||||
Backend-only work. Follow Red → Green → Refactor per `CLAUDE.md` for every
|
||||
step that adds behavior (store, retention, provider `$since` handling).
|
||||
Order matters — later steps assume earlier ones are done.
|
||||
|
||||
## 1. Audit cleanup
|
||||
|
||||
- [x] **Remove `eightpoints/guzzle-bundle` + `idci/graphql-client-bundle`.**
|
||||
They exist only to build one near-static GitHub GraphQL query string
|
||||
(`GitHubProvider.php:59-74`); the bundle's own HTTP transport is already
|
||||
bypassed (comment at `GitHubProvider.php:76-77`).
|
||||
- [x] Replace
|
||||
`$graphqlClient->buildQuery(...)->getGraphQLQuery()` with a plain
|
||||
`sprintf`/heredoc query string. Delete the two packages from
|
||||
`composer.json`, `config/bundles.php`, and delete
|
||||
`config/packages/eight_points_guzzle.yaml` +
|
||||
`config/packages/idci_graphql_client.yaml`. Run `composer update` and
|
||||
commit the regenerated `composer.lock`.
|
||||
|
||||
- [x] **Dedupe `baseUrl` normalization.** `GitLabProvider.php` (lines 41,
|
||||
53) and `GiteaProvider.php` (lines 42, 54) each call
|
||||
`rtrim($this->baseUrl..., '/')` twice — once in `ping()`, once in
|
||||
`fetch()`. Compute it once as a `private readonly string $baseUrl` in
|
||||
the constructor instead.
|
||||
|
||||
## 2. Fix stale `config/services.yaml` (found during exploration, blocks step 1 & 4)
|
||||
|
||||
- [x] `services.yaml` still binds `$username`/`$token`/`$baseUrl` to the
|
||||
pre-refactor FQCNs (`App\Service\GitHubProvider` etc.) and
|
||||
`_instanceof: App\Service\ProviderInterface`, left over from the
|
||||
`Service/` → `Provider/`+`Renderer/` namespace reorg. Update all of
|
||||
these to `App\Service\Provider\...`. Currently these bindings silently
|
||||
no-op, and scalar constructor args can't autowire without them — any
|
||||
edit to these constructors (steps 1, 4) needs this fixed first, or the
|
||||
container fails to compile.
|
||||
|
||||
## 3. `ContributionStore` (SQLite via native PDO)
|
||||
|
||||
> Docs: [PDO](https://www.php.net/manual/en/book.pdo.php) ·
|
||||
> [PDO_SQLITE driver](https://www.php.net/manual/en/ref.pdo-sqlite.php) ·
|
||||
> [PDO::prepare / prepared statements](https://www.php.net/manual/en/pdo.prepare.php) ·
|
||||
> [SQLite `INSERT ... ON CONFLICT` upsert](https://www.sqlite.org/lang_upsert.html) ·
|
||||
> [SQLite `STRICT` tables](https://www.sqlite.org/stricttables.html) ·
|
||||
> [SQLite `WITHOUT ROWID` tables](https://www.sqlite.org/withoutrowid.html) ·
|
||||
> [SQLite datatypes (why `date` is `INTEGER`/unixtime, not `TEXT`)](https://www.sqlite.org/datatype3.html)
|
||||
|
||||
- [x] New `src/Service/ContributionStore.php`. PDO SQLite, DB file at
|
||||
`%kernel.project_dir%/var/data/contributions.db` (configurable
|
||||
constructor arg), table created lazily. **Schema note:** `date` is
|
||||
stored as a Unix timestamp (`INTEGER`), not `TEXT` — matches the
|
||||
current implementation:
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS contributions (
|
||||
provider TEXT NOT NULL,
|
||||
date INTEGER NOT NULL,
|
||||
count INTEGER NOT NULL CHECK (count >= 0),
|
||||
PRIMARY KEY (provider, date)
|
||||
) WITHOUT ROWID, STRICT;
|
||||
```
|
||||
- [x] `add(string $provider, int $unixtime, int $count): void` — plain
|
||||
insert (done, needs test coverage — see below).
|
||||
- [x] Fix `add()`: currently a plain `INSERT`, so re-adding an existing
|
||||
`(provider, date)` throws a unique-constraint violation instead of
|
||||
upserting. Switch to
|
||||
`INSERT ... ON CONFLICT(provider, date) DO UPDATE SET count = excluded.count`
|
||||
(see SQLite upsert doc above), or keep `add()` insert-only and add a
|
||||
separate `merge()` for the upsert case used by step 5.
|
||||
- [x] `remove(string $provider, int $unixtime): void` — started, has a
|
||||
bug: `DELETE contributions WHERE ...` is invalid SQL, missing the
|
||||
`FROM` keyword (must be `DELETE FROM contributions WHERE ...`); also
|
||||
drop the `LIKE` on `provider` (exact match, use `=`) since it's an
|
||||
unindexed wildcard scan for what should be an exact key lookup.
|
||||
- [x] **`Contribution` entity.** Small immutable value object
|
||||
(`src/Entity/Contribution.php`) wrapping one row: `provider` (string),
|
||||
`date` (unix timestamp int, or `\DateTimeImmutable` — pick one and
|
||||
use it consistently everywhere, including `add()`/`all()`), `count`
|
||||
(int). Gives `ContributionStore::all()` and the aggregator something
|
||||
typed to pass around instead of raw arrays/tuples.
|
||||
- [x] **`ContributionCollection`.** Typed collection
|
||||
(`src/Entity/ContributionCollection.php`) wrapping
|
||||
`array<Contribution>` — implement `IteratorAggregate` + `Countable`
|
||||
at minimum ([`IteratorAggregate`](https://www.php.net/manual/en/class.iteratoraggregate.php),
|
||||
[`Countable`](https://www.php.net/manual/en/class.countable.php)) so
|
||||
it can be `foreach`'d and `count()`'d like a normal array. This is
|
||||
what `ContributionStore::all()` should return instead of a bare
|
||||
`date => count` array.
|
||||
- [x] `latestDate(string $provider): ?int` — `SELECT MAX(date) WHERE provider = ?`
|
||||
(returns a unix timestamp, not a string, per the schema above).
|
||||
- [x] `merge(string $provider, array $dateCounts): void` — upsert via
|
||||
`INSERT ... ON CONFLICT(provider, date) DO UPDATE SET count = excluded.count`;
|
||||
`$dateCounts` keyed by unix timestamp.
|
||||
- [x] `all(string $provider, ?int $sinceDays = null): ContributionCollection` —
|
||||
fetch all rows for a provider, or since a given range. `null` returns
|
||||
full history (no arbitrary cutoff), a value filters to rows where
|
||||
`date >= (now - sinceDays * 86400)`. **Bug:** current stub in
|
||||
`ContributionStore.php:58` has invalid PHP (`$provider == null` instead
|
||||
of `?string $provider = null` — this won't parse) and returns `void`
|
||||
instead of `ContributionCollection`; fix the signature when implementing.
|
||||
- [x] `prune(): void` — `DELETE FROM contributions WHERE date < ?` using
|
||||
the configured retention window (a unix timestamp cutoff); no-ops if
|
||||
retention is unset/0.
|
||||
- [x] Constructor takes `?int $retentionDays` bound from new env var
|
||||
`CONTRIBUTIONS_RETENTION_DAYS` (empty/default = keep forever). *(constructor
|
||||
param wired; the env binding itself is step 6's job.)*
|
||||
- [x] Tests: `tests/Unit/Service/ContributionStoreTest.php` — store &
|
||||
retrieve, upsert overwrites existing date, `sinceDays` filtering,
|
||||
`prune()` no-ops when retention unset, `prune()` deletes rows older
|
||||
than the window when set.
|
||||
- [x] Tests: `tests/Unit/Entity/ContributionTest.php` and
|
||||
`ContributionCollectionTest.php` — construction, iteration, `count()`.
|
||||
|
||||
## 4. Wire `$since` through providers
|
||||
|
||||
- [ ] `ProviderInterface::fetch()` → `fetch(?\DateTimeImmutable $since = null): array`.
|
||||
- [ ] `GitHubProvider::fetch()` — use `$since ?? new \DateTimeImmutable('-365 days')`
|
||||
for the GraphQL `from` param.
|
||||
- [ ] `GitLabProvider::fetch()` — same, feeds the `after` query param
|
||||
(this is what actually shrinks the pagination loop).
|
||||
- [ ] `GiteaProvider::fetch()` — same, feeds the `$cutoff` timestamp filter.
|
||||
- [ ] Update `GitHubProviderTest.php` (drop `GraphQLApiClientRegistryInterface`
|
||||
stub setup entirely per step 1), `GitLabProviderTest.php`,
|
||||
`GiteaProviderTest.php` — add a case asserting a passed `$since` narrows
|
||||
the request window.
|
||||
|
||||
## 5. Wire `ContributionStore` into `ContributionAggregator`
|
||||
|
||||
- [ ] Inject `ContributionStore` into `ContributionAggregator`.
|
||||
- [ ] Per configured provider: `$since = $store->latestDate($name)` → if
|
||||
set, `(new \DateTimeImmutable($latest))->modify('-3 days')` (3-day
|
||||
overlap for late corrections), else `null` (first run).
|
||||
- [ ] `$fresh = $provider->fetch($since)`, `$store->merge($name, $fresh)`,
|
||||
then read back `$store->all($name, sinceDays: 371)` for the render
|
||||
window (53 weeks × 7 days) — a `ContributionCollection` — and merge
|
||||
its contributions into the returned array.
|
||||
- [ ] Call `$store->prune()` once per `aggregate()` call, after all
|
||||
providers have merged.
|
||||
- [ ] Keep the existing try/catch-and-log-per-provider behavior — a
|
||||
provider failure leaves its DB history stale, doesn't break the render.
|
||||
- [ ] Update `ContributionAggregatorTest.php` with store-interaction and
|
||||
prune-call cases.
|
||||
|
||||
## 6. Docker / env
|
||||
|
||||
- [ ] `docker-compose.yml` — add a `data` named volume mounted at
|
||||
`/app/var/data` (same pattern as `cache`/`logs`), and pass through
|
||||
`CONTRIBUTIONS_RETENTION_DAYS: "${CONTRIBUTIONS_RETENTION_DAYS:-}"`.
|
||||
- [ ] `Dockerfile` — add `var/data` to the `mkdir -p` in the `final` stage
|
||||
alongside `var/cache/prod/pools var/log`, owned by `app`.
|
||||
- [ ] `.env` — document `CONTRIBUTIONS_RETENTION_DAYS` (empty by default),
|
||||
same style as the existing `ALLOWED_HOSTS` comment.
|
||||
|
||||
## 7. PHPStan
|
||||
|
||||
- [ ] `composer require --dev phpstan/phpstan` (plain PHPStan — no
|
||||
Symfony extension needed for this app's size).
|
||||
- [ ] Add `phpstan.neon`: `paths: [src, tests]`, `level: 8`.
|
||||
- [ ] Add composer script `"phpstan": "phpstan analyse"`.
|
||||
- [ ] Fix whatever level-8 flags on first run.
|
||||
|
||||
## 8. `CLAUDE.md` update
|
||||
|
||||
- [ ] Architecture section: add the `ContributionStore` (SQLite) tier
|
||||
between providers and the renderer; note the two-tier cache (1h SVG
|
||||
cache → SQLite raw-data store → provider APIs).
|
||||
- [ ] Environment variables table: add `CONTRIBUTIONS_RETENTION_DAYS`.
|
||||
- [ ] Development section: add `composer phpstan` next to the existing
|
||||
`vendor/bin/phpunit` commands.
|
||||
- [ ] Remove any remaining mentions of the two deleted bundles.
|
||||
|
||||
## Verification
|
||||
|
||||
- `vendor/bin/phpunit --testdox` green after every step.
|
||||
- `composer phpstan` clean at level 8.
|
||||
- `composer install` succeeds with no dangling references to the removed bundles.
|
||||
- `docker compose up -d --build`; clear the FS cache
|
||||
(`docker compose exec graph rm -rf var/cache/*`); hit
|
||||
`/graph.svg?theme=dark` twice; check `docker compose logs -f graph` shows
|
||||
a narrower `since` window on the second fetch.
|
||||
- Set `CONTRIBUTIONS_RETENTION_DAYS=30`; confirm rows older than 30 days
|
||||
are gone after the next refresh
|
||||
(`sqlite3 var/data/contributions.db "SELECT date FROM contributions ORDER BY date LIMIT 1"`).
|
||||
- `curl localhost:8080/health` still reports all configured providers healthy.
|
||||
@@ -5,8 +5,6 @@
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=8.2",
|
||||
"eightpoints/guzzle-bundle": "^8.6",
|
||||
"idci/graphql-client-bundle": "^2.0",
|
||||
"monolog/monolog": "^3.10",
|
||||
"symfony/cache": "7.4.*",
|
||||
"symfony/console": "7.4.*",
|
||||
|
||||
Generated
+4948
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,4 @@
|
||||
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],
|
||||
];
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
eight_points_guzzle:
|
||||
clients:
|
||||
github_graphql:
|
||||
base_url: 'https://api.github.com/graphql'
|
||||
options:
|
||||
headers:
|
||||
Authorization: 'Bearer %env(GITHUB_TOKEN)%'
|
||||
@@ -7,3 +7,7 @@ framework:
|
||||
cache:
|
||||
app: cache.adapter.filesystem
|
||||
default_redis_provider: 'redis://localhost'
|
||||
http_client:
|
||||
default_options:
|
||||
timeout: 10 # connect + wait-for-first-byte cap per request
|
||||
max_duration: 15 # hard cap on total request duration
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
idci_graphql_client:
|
||||
clients:
|
||||
github:
|
||||
http_client: 'eight_points_guzzle.client.github_graphql'
|
||||
+3
-59
@@ -37,7 +37,7 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* @psalm-type ArgumentsType = list<mixed>|array<string, mixed>
|
||||
* @psalm-type CallType = array<string, ArgumentsType>|array{0:string, 1?:ArgumentsType, 2?:bool}|array{method:string, arguments?:ArgumentsType, returns_clone?:bool}
|
||||
* @psalm-type TagsType = list<string|array<string, array<string, mixed>>> // arrays inside the list must have only one element, with the tag name as the key
|
||||
* @psalm-type CallbackType = string|array{0:string|ReferenceConfigurator,1:string}|\Closure|ReferenceConfigurator|ExpressionConfigurator
|
||||
* @psalm-type CallbackType = string|array{0:string|ReferenceConfigurator,1:string}|\Closure|ReferenceConfigurator
|
||||
* @psalm-type DeprecationType = array{package: string, version: string, message?: string}
|
||||
* @psalm-type DefaultsType = array{
|
||||
* public?: bool,
|
||||
@@ -121,7 +121,7 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* }
|
||||
* @psalm-type ServicesConfig = array{
|
||||
* _defaults?: DefaultsType,
|
||||
* _instanceof?: InstanceofType,
|
||||
* _instanceof?: array<class-string, InstanceofType>,
|
||||
* ...<string, DefinitionType|AliasType|PrototypeType|StackType|ArgumentsType|null>
|
||||
* }
|
||||
* @psalm-type ExtensionType = array<string, mixed>
|
||||
@@ -302,7 +302,7 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* },
|
||||
* },
|
||||
* translator?: bool|array{ // Translator configuration
|
||||
* enabled?: bool|Param, // Default: true
|
||||
* enabled?: bool|Param, // Default: false
|
||||
* fallbacks?: string|list<scalar|Param|null>,
|
||||
* logging?: bool|Param, // Default: false
|
||||
* formatter?: scalar|Param|null, // Default: "translator.formatter.default"
|
||||
@@ -833,72 +833,18 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* },
|
||||
* }>,
|
||||
* }
|
||||
* @psalm-type EightPointsGuzzleConfig = array{
|
||||
* clients?: array<string, array{ // Default: []
|
||||
* class?: scalar|Param|null, // Default: "%eight_points_guzzle.http_client.class%"
|
||||
* base_url?: scalar|Param|null, // Default: null
|
||||
* lazy?: bool|Param, // Default: false
|
||||
* logging?: int|Param, // Default: null
|
||||
* handler?: scalar|Param|null, // Default: null
|
||||
* options?: array{
|
||||
* headers?: array<string, scalar|Param|null>,
|
||||
* allow_redirects?: mixed,
|
||||
* auth?: mixed,
|
||||
* query?: mixed,
|
||||
* curl?: list<scalar|Param|null>,
|
||||
* cert?: mixed,
|
||||
* connect_timeout?: scalar|Param|null,
|
||||
* debug?: bool|Param,
|
||||
* decode_content?: mixed,
|
||||
* delay?: float|Param,
|
||||
* form_params?: array<string, mixed>,
|
||||
* multipart?: list<mixed>,
|
||||
* sink?: scalar|Param|null,
|
||||
* http_errors?: bool|Param,
|
||||
* expect?: mixed,
|
||||
* ssl_key?: mixed,
|
||||
* stream?: bool|Param,
|
||||
* synchronous?: bool|Param,
|
||||
* read_timeout?: scalar|Param|null,
|
||||
* timeout?: scalar|Param|null,
|
||||
* verify?: mixed,
|
||||
* cookies?: bool|Param,
|
||||
* proxy?: string|array{
|
||||
* http?: scalar|Param|null,
|
||||
* https?: scalar|Param|null,
|
||||
* no?: list<scalar|Param|null>,
|
||||
* },
|
||||
* version?: scalar|Param|null,
|
||||
* },
|
||||
* plugin?: array<mixed>,
|
||||
* }>,
|
||||
* logging?: bool|Param, // Default: true
|
||||
* profiling?: bool|Param, // Default: true
|
||||
* slow_response_time?: int|Param, // Default: 0
|
||||
* }
|
||||
* @psalm-type IdciGraphqlClientConfig = array{
|
||||
* cache_enabled?: bool|Param, // Default: false
|
||||
* clients?: list<array{ // Default: []
|
||||
* http_client?: scalar|Param|null,
|
||||
* cache?: scalar|Param|null,
|
||||
* }>,
|
||||
* }
|
||||
* @psalm-type ConfigType = array{
|
||||
* imports?: ImportsConfig,
|
||||
* parameters?: ParametersConfig,
|
||||
* services?: ServicesConfig,
|
||||
* framework?: FrameworkConfig,
|
||||
* monolog?: MonologConfig,
|
||||
* eight_points_guzzle?: EightPointsGuzzleConfig,
|
||||
* idci_graphql_client?: IdciGraphqlClientConfig,
|
||||
* "when@dev"?: array{
|
||||
* imports?: ImportsConfig,
|
||||
* parameters?: ParametersConfig,
|
||||
* services?: ServicesConfig,
|
||||
* framework?: FrameworkConfig,
|
||||
* monolog?: MonologConfig,
|
||||
* eight_points_guzzle?: EightPointsGuzzleConfig,
|
||||
* idci_graphql_client?: IdciGraphqlClientConfig,
|
||||
* },
|
||||
* "when@prod"?: array{
|
||||
* imports?: ImportsConfig,
|
||||
@@ -906,8 +852,6 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* services?: ServicesConfig,
|
||||
* framework?: FrameworkConfig,
|
||||
* monolog?: MonologConfig,
|
||||
* eight_points_guzzle?: EightPointsGuzzleConfig,
|
||||
* idci_graphql_client?: IdciGraphqlClientConfig,
|
||||
* },
|
||||
* ...<string, ExtensionType|array{ // extra keys must follow the when@%env% pattern or match an extension alias
|
||||
* imports?: ImportsConfig,
|
||||
|
||||
+16
-4
@@ -1,3 +1,15 @@
|
||||
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
|
||||
@@ -10,21 +22,21 @@ services:
|
||||
- '../src/Kernel.php'
|
||||
|
||||
_instanceof:
|
||||
App\Service\ProviderInterface:
|
||||
App\Service\Provider\ProviderInterface:
|
||||
tags: ['app.provider']
|
||||
|
||||
App\Service\GitHubProvider:
|
||||
App\Service\Provider\GitHubProvider:
|
||||
arguments:
|
||||
$username: '%env(GITHUB_USER)%'
|
||||
$token: '%env(GITHUB_TOKEN)%'
|
||||
|
||||
App\Service\GitLabProvider:
|
||||
App\Service\Provider\GitLabProvider:
|
||||
arguments:
|
||||
$username: '%env(GITLAB_USER)%'
|
||||
$token: '%env(GITLAB_TOKEN)%'
|
||||
$baseUrl: '%env(GITLAB_URL)%'
|
||||
|
||||
App\Service\GiteaProvider:
|
||||
App\Service\Provider\GiteaProvider:
|
||||
arguments:
|
||||
$username: '%env(GITEA_USER)%'
|
||||
$token: '%env(GITEA_TOKEN)%'
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
services:
|
||||
graph:
|
||||
build:
|
||||
dockerfile: Dockerfile.dev
|
||||
target: dev
|
||||
volumes:
|
||||
- .:/app
|
||||
- /app/vendor # keeps vendor from the dev image, not your local dir
|
||||
- ./vendor:/app/vendor
|
||||
- /app/var/data
|
||||
environment:
|
||||
APP_ENV: dev
|
||||
APP_DEBUG: "1"
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
services:
|
||||
graph:
|
||||
image: git.arthurerlich.de/haylan/git-contribution-graph:latest
|
||||
container_name: git-contribution-graph
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
APP_ENV: prod
|
||||
APP_DEBUG: "0"
|
||||
APP_SECRET: "${APP_SECRET}"
|
||||
ALLOWED_HOSTS: "${ALLOWED_HOSTS:-}"
|
||||
GITHUB_USER: "${GITHUB_USER:-}"
|
||||
GITHUB_TOKEN: "${GITHUB_TOKEN:-}"
|
||||
GITLAB_USER: "${GITLAB_USER:-}"
|
||||
GITLAB_TOKEN: "${GITLAB_TOKEN:-}"
|
||||
GITLAB_URL: "${GITLAB_URL:-}"
|
||||
GITEA_USER: "${GITEA_USER:-}"
|
||||
GITEA_TOKEN: "${GITEA_TOKEN:-}"
|
||||
GITEA_URL: "${GITEA_URL:-}"
|
||||
volumes:
|
||||
- cache:/app/var/cache/prod/pools
|
||||
- logs:/app/var/log
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
volumes:
|
||||
cache:
|
||||
logs:
|
||||
+2
-1
@@ -21,13 +21,14 @@ services:
|
||||
GITEA_TOKEN: "${GITEA_TOKEN:-}"
|
||||
GITEA_URL: "${GITEA_URL:-}"
|
||||
volumes:
|
||||
- cache:/app/var/cache
|
||||
- cache:/app/var/cache/prod/pools
|
||||
- logs:/app/var/log
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
volumes:
|
||||
cache:
|
||||
|
||||
@@ -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,2 @@
|
||||
opcache.validate_timestamps=1
|
||||
opcache.revalidate_freq=0
|
||||
@@ -0,0 +1,6 @@
|
||||
opcache.enable=1
|
||||
opcache.enable_cli=0
|
||||
opcache.memory_consumption=128
|
||||
opcache.max_accelerated_files=20000
|
||||
opcache.validate_timestamps=0
|
||||
expose_php=0
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 0 B After Width: | Height: | Size: 2.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 539 B |
@@ -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();
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended"
|
||||
],
|
||||
"separateMajorMinor": true,
|
||||
"major": {
|
||||
"enabled": false
|
||||
},
|
||||
"packageRules": [
|
||||
{
|
||||
"allowedVersions": "^7.0",
|
||||
"description": "Keep Symfony on 7.x LTS until EOL",
|
||||
"matchPackageNames": [
|
||||
"/^symfony//"
|
||||
]
|
||||
},
|
||||
{
|
||||
"matchManagers": ["github-actions"],
|
||||
"enabled": false,
|
||||
"description": "Ignore GitHub Actions — no GITHUB_COM_TOKEN available"
|
||||
},
|
||||
{
|
||||
"matchPackageNames": ["phpunit/phpunit"],
|
||||
"allowedVersions": "^12.0",
|
||||
"description": "Stay on PHPUnit 12.x (compatible with Symfony 7 / PHP 8.2+)"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Service\ProviderInterface;
|
||||
use App\Service\SvgRenderer;
|
||||
use App\Service\ContributionAggregator;
|
||||
use App\Service\Provider\ProviderHealthChecker;
|
||||
use App\Service\Renderer\SvgRenderer;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
@@ -14,17 +16,17 @@ 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(
|
||||
#[TaggedIterator('app.provider')]
|
||||
private readonly iterable $providers,
|
||||
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 = '',
|
||||
) {
|
||||
@@ -51,8 +53,9 @@ class GraphController
|
||||
$svg = $this->cache->get($cacheKey, function (ItemInterface $item) use ($theme, &$cacheMiss): string {
|
||||
$cacheMiss = true;
|
||||
$item->expiresAfter(3600);
|
||||
set_time_limit(30); // ponytail: providers fetch concurrently now (cost ~= max, not sum); GitLab pagination + per-request HTTP timeout (framework.yaml) still need headroom over the 30s default
|
||||
|
||||
return $this->renderer->render($this->fetchAllContributions(), $theme);
|
||||
return $this->renderer->render($this->aggregator->aggregate(), $theme);
|
||||
});
|
||||
|
||||
$this->logger->debug('GraphController: cache ' . ($cacheMiss ? 'miss' : 'hit'), ['theme' => $theme]);
|
||||
@@ -75,37 +78,13 @@ class GraphController
|
||||
#[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;
|
||||
|
||||
/** @return array<string, int> */
|
||||
private function fetchAllContributions(): array
|
||||
{
|
||||
$contributions = [];
|
||||
|
||||
/** @var ProviderInterface $provider */
|
||||
foreach ($this->providers as $provider) {
|
||||
if (!$provider->isConfigured()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$contributions = $this->merge($contributions, $provider->fetch());
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->warning(sprintf('%s fetch failed: %s', $provider::class, $e->getMessage()), ['exception' => $e]);
|
||||
}
|
||||
}
|
||||
|
||||
return $contributions;
|
||||
}
|
||||
|
||||
/** @param array<string, int> $base @param array<string, int> $new @return array<string, int> */
|
||||
private function merge(array $base, array $new): array
|
||||
{
|
||||
foreach ($new as $date => $count) {
|
||||
$base[$date] = ($base[$date] ?? 0) + $count;
|
||||
}
|
||||
|
||||
return $base;
|
||||
return new Response(
|
||||
json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR),
|
||||
$statusCode,
|
||||
['Content-Type' => 'application/json'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
final class Contribution
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $provider,
|
||||
public readonly int $date,
|
||||
public readonly int $count,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
/**
|
||||
* @implements \IteratorAggregate<int, Contribution>
|
||||
*/
|
||||
final class ContributionCollection implements \IteratorAggregate, \Countable
|
||||
{
|
||||
/** @var array<int, Contribution> */
|
||||
private readonly array $contributions;
|
||||
|
||||
public function __construct(Contribution ...$contributions)
|
||||
{
|
||||
$this->contributions = $contributions;
|
||||
}
|
||||
|
||||
public function getIterator(): \ArrayIterator
|
||||
{
|
||||
return new \ArrayIterator($this->contributions);
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->contributions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Service\Provider\ProviderInterface;
|
||||
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
|
||||
{
|
||||
$pending = [];
|
||||
|
||||
/** @var ProviderInterface $provider */
|
||||
foreach ($this->providers as $provider) {
|
||||
if (!$provider->isConfigured()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$pending[] = [$provider, $provider->startFetch()];
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->warning(sprintf('%s fetch failed: %s', $provider::class, $e->getMessage()), ['exception' => $e]);
|
||||
}
|
||||
}
|
||||
|
||||
$contributions = [];
|
||||
|
||||
foreach ($pending as [$provider, $handle]) {
|
||||
try {
|
||||
foreach ($provider->resolveFetch($handle) 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Contribution;
|
||||
use App\Entity\ContributionCollection;
|
||||
use PDO;
|
||||
|
||||
class ContributionStore
|
||||
{
|
||||
private PDO $pdo;
|
||||
private const int DAY_IN_SECONDS = 86400;
|
||||
|
||||
public function __construct(
|
||||
private readonly string $dbPath = "%kernel.project_dir%/var/data/contributions.db",
|
||||
private readonly ?int $retentionDays = null,
|
||||
) {
|
||||
$dir = \dirname($this->dbPath);
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0755, recursive: true);
|
||||
}
|
||||
$this->pdo = new PDO('sqlite:' . $this->dbPath);
|
||||
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->prepareSchema();
|
||||
}
|
||||
|
||||
private function prepareSchema(): void
|
||||
{
|
||||
$this->pdo->exec('
|
||||
CREATE TABLE IF NOT EXISTS contributions (
|
||||
provider TEXT NOT NULL,
|
||||
date INTEGER NOT NULL,
|
||||
count INTEGER NOT NULL CHECK (count >= 0),
|
||||
PRIMARY KEY (provider, date)
|
||||
) WITHOUT ROWID, STRICT
|
||||
');
|
||||
}
|
||||
|
||||
public function add(string $provider, int $unixtime, int $count): void
|
||||
{
|
||||
$stmt = $this->pdo->prepare('
|
||||
INSERT INTO contributions (provider, date, count)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(provider, date) DO UPDATE SET count = excluded.count
|
||||
');
|
||||
$stmt->execute([$provider, $unixtime, $count]);
|
||||
}
|
||||
|
||||
public function remove(string $provider, int $unixtime): void
|
||||
{
|
||||
$stmt = $this->pdo->prepare('
|
||||
DELETE FROM contributions
|
||||
WHERE provider = ? AND date = ?
|
||||
');
|
||||
$stmt->execute([$provider, $unixtime]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $dateCounts unix timestamp => count
|
||||
*/
|
||||
public function merge(string $provider, array $dateCounts): void
|
||||
{
|
||||
foreach ($dateCounts as $unixtime => $count) {
|
||||
$this->add($provider, $unixtime, $count);
|
||||
}
|
||||
}
|
||||
|
||||
public function latestDate(string $provider): ?int
|
||||
{
|
||||
$stmt = $this->pdo->prepare('SELECT MAX(date) FROM contributions WHERE provider = ?');
|
||||
$stmt->execute([$provider]);
|
||||
$result = $stmt->fetchColumn();
|
||||
|
||||
return $result !== null ? (int) $result : null;
|
||||
}
|
||||
|
||||
public function all(string $provider, ?int $sinceDays = null): ContributionCollection
|
||||
{
|
||||
$sql = 'SELECT provider, date, count FROM contributions WHERE provider = ?';
|
||||
$params = [$provider];
|
||||
|
||||
if ($sinceDays !== null) {
|
||||
$sql .= ' AND date >= ?';
|
||||
$params[] = time() - $sinceDays * self::DAY_IN_SECONDS;
|
||||
}
|
||||
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
|
||||
$contributions = array_map(
|
||||
static fn (array $row): Contribution => new Contribution($row['provider'], (int) $row['date'], (int) $row['count']),
|
||||
$stmt->fetchAll(PDO::FETCH_ASSOC),
|
||||
);
|
||||
|
||||
return new ContributionCollection(...$contributions);
|
||||
}
|
||||
|
||||
public function prune(): void
|
||||
{
|
||||
if ($this->retentionDays === null || $this->retentionDays === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cutoff = time() - $this->retentionDays * self::DAY_IN_SECONDS;
|
||||
|
||||
$stmt = $this->pdo->prepare('DELETE FROM contributions WHERE date < ?');
|
||||
$stmt->execute([$cutoff]);
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
/**
|
||||
* Fetches the last 365 days of push/merge events from the GitLab REST API.
|
||||
*
|
||||
* Required token scopes: read_user, read_api
|
||||
* Works with both gitlab.com and self-hosted instances.
|
||||
*/
|
||||
class GitLabProvider implements ProviderInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly HttpClientInterface $client,
|
||||
private readonly string $username,
|
||||
private readonly string $token,
|
||||
private readonly LoggerInterface $logger,
|
||||
private readonly string $baseUrl = '',
|
||||
) {}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->username !== '' && $this->token !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int> date (Y-m-d) => event count
|
||||
*/
|
||||
public function fetch(): array
|
||||
{
|
||||
$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' => $this->token],
|
||||
'query' => ['username' => $this->username],
|
||||
]);
|
||||
|
||||
$users = $userResponse->toArray();
|
||||
if (empty($users)) {
|
||||
throw new \RuntimeException("GitLab: user '{$this->username}' not found on $baseUrl");
|
||||
}
|
||||
$userId = $users[0]['id'];
|
||||
|
||||
$result = [];
|
||||
$after = (new \DateTimeImmutable('-365 days'))->format('Y-m-d');
|
||||
$page = 1;
|
||||
|
||||
do {
|
||||
$response = $this->client->request('GET', "$baseUrl/api/v4/users/$userId/events", [
|
||||
'headers' => ['PRIVATE-TOKEN' => $this->token],
|
||||
'query' => [
|
||||
'after' => $after,
|
||||
'per_page' => 100,
|
||||
'page' => $page,
|
||||
],
|
||||
]);
|
||||
|
||||
$events = $response->toArray();
|
||||
|
||||
foreach ($events as $event) {
|
||||
$date = substr($event['created_at'], 0, 10);
|
||||
$result[$date] = ($result[$date] ?? 0) + 1;
|
||||
}
|
||||
|
||||
$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,75 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Provider;
|
||||
|
||||
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;
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Fetches the last 365 days of contributions from the GitHub GraphQL API.
|
||||
*
|
||||
* Required token scopes: read:user
|
||||
*/
|
||||
class GitHubProvider implements ProviderInterface
|
||||
final class GitHubProvider implements ProviderInterface
|
||||
{
|
||||
use ProbeTrait;
|
||||
|
||||
private const GRAPHQL_URL = 'https://api.github.com/graphql';
|
||||
|
||||
public function __construct(
|
||||
private readonly HttpClientInterface $client,
|
||||
private readonly GraphQLApiClientRegistryInterface $registry,
|
||||
private readonly string $username,
|
||||
private readonly string $token,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'github';
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->username !== '' && $this->token !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int> date (Y-m-d) => contribution count
|
||||
*/
|
||||
public function fetch(): array
|
||||
public function ping(): void
|
||||
{
|
||||
$this->client->request('GET', 'https://api.github.com/user', [
|
||||
'headers' => ['Authorization' => "Bearer {$this->token}"],
|
||||
])->getContent();
|
||||
}
|
||||
|
||||
public function startFetch(): ResponseInterface
|
||||
{
|
||||
$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 = sprintf(
|
||||
'query { user(login: %s) { contributionsCollection(from: %s, to: %s) { contributionCalendar { weeks { contributionDays { date contributionCount } } } } } }',
|
||||
json_encode($this->username),
|
||||
json_encode($from),
|
||||
json_encode($to),
|
||||
);
|
||||
|
||||
$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, [
|
||||
// GitHub's GraphQL API requires application/json.
|
||||
// request() doesn't block; the response is read in resolveFetch() so
|
||||
// multiple providers' requests can be in flight at once.
|
||||
return $this->client->request('POST', self::GRAPHQL_URL, [
|
||||
'headers' => [
|
||||
'Authorization' => "Bearer {$this->token}",
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
'json' => ['query' => $query],
|
||||
]);
|
||||
}
|
||||
|
||||
$data = $response->toArray();
|
||||
/**
|
||||
* @return array<string, int> date (Y-m-d) => contribution count
|
||||
*/
|
||||
public function resolveFetch(mixed $handle): array
|
||||
{
|
||||
/** @var ResponseInterface $handle */
|
||||
$data = $handle->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 = [];
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Provider;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Fetches the last 365 days of push/merge events from the GitLab REST API.
|
||||
*
|
||||
* Required token scopes: read_user, read_api
|
||||
* Works with both gitlab.com and self-hosted instances.
|
||||
*/
|
||||
final class GitLabProvider implements ProviderInterface
|
||||
{
|
||||
use ProbeTrait;
|
||||
|
||||
private readonly string $baseUrl;
|
||||
|
||||
public function __construct(
|
||||
private readonly HttpClientInterface $client,
|
||||
private readonly string $username,
|
||||
private readonly string $token,
|
||||
private readonly LoggerInterface $logger,
|
||||
string $baseUrl = '',
|
||||
) {
|
||||
$this->baseUrl = rtrim($baseUrl !== '' ? $baseUrl : 'https://gitlab.com', '/');
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'gitlab';
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->username !== '' && $this->token !== '';
|
||||
}
|
||||
|
||||
public function ping(): void
|
||||
{
|
||||
|
||||
$this->client->request('GET', "$this->baseUrl/api/v4/user", [
|
||||
'headers' => ['PRIVATE-TOKEN' => $this->token],
|
||||
])->getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{baseUrl: string, userId: int, after: string, page: int, response: ResponseInterface}
|
||||
*
|
||||
* ponytail: the user-id lookup and event pagination stay sequential within
|
||||
* this one provider (each page depends on the previous). Parallelism here
|
||||
* only spans across providers; revisit only if GitLab pagination itself
|
||||
* becomes the bottleneck.
|
||||
*/
|
||||
public function startFetch(): array
|
||||
{
|
||||
|
||||
$this->logger->debug('GitLabProvider: fetching contributions', ['user' => $this->username, 'url' => $this->baseUrl]);
|
||||
|
||||
$userResponse = $this->client->request('GET', "$this->baseUrl/api/v4/users", [
|
||||
'headers' => ['PRIVATE-TOKEN' => $this->token],
|
||||
'query' => ['username' => $this->username],
|
||||
]);
|
||||
|
||||
$users = $userResponse->toArray();
|
||||
if (empty($users)) {
|
||||
throw new NotFoundHttpException("GitLab: user '{$this->username}' not found on $this->baseUrl");
|
||||
}
|
||||
$userId = $users[0]['id'];
|
||||
$after = (new \DateTimeImmutable('-365 days'))->format('Y-m-d');
|
||||
|
||||
$response = $this->client->request('GET', "$this->baseUrl/api/v4/users/$userId/events", [
|
||||
'headers' => ['PRIVATE-TOKEN' => $this->token],
|
||||
'query' => [
|
||||
'after' => $after,
|
||||
'per_page' => 100,
|
||||
'page' => 1,
|
||||
],
|
||||
]);
|
||||
|
||||
return ['baseUrl' => $this->baseUrl, 'userId' => $userId, 'after' => $after, 'page' => 1, 'response' => $response];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int> date (Y-m-d) => event count
|
||||
*/
|
||||
public function resolveFetch(mixed $handle): array
|
||||
{
|
||||
['baseUrl' => $baseUrl, 'userId' => $userId, 'after' => $after, 'page' => $page, 'response' => $response] = $handle;
|
||||
|
||||
$result = [];
|
||||
|
||||
do {
|
||||
$events = $response->toArray();
|
||||
|
||||
foreach ($events as $event) {
|
||||
$date = substr($event['created_at'], 0, 10);
|
||||
$result[$date] = ($result[$date] ?? 0) + 1;
|
||||
}
|
||||
|
||||
$page++;
|
||||
|
||||
if (count($events) === 100) {
|
||||
$response = $this->client->request('GET', "$baseUrl/api/v4/users/$userId/events", [
|
||||
'headers' => ['PRIVATE-TOKEN' => $this->token],
|
||||
'query' => [
|
||||
'after' => $after,
|
||||
'per_page' => 100,
|
||||
'page' => $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,9 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Provider;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Fetches contribution data from the Gitea heatmap endpoint.
|
||||
@@ -13,35 +16,59 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
*
|
||||
* Required token scopes: read:user
|
||||
*/
|
||||
class GiteaProvider implements ProviderInterface
|
||||
final class GiteaProvider implements ProviderInterface
|
||||
{
|
||||
use ProbeTrait;
|
||||
|
||||
private readonly string $baseUrl;
|
||||
|
||||
public function __construct(
|
||||
private readonly HttpClientInterface $client,
|
||||
private readonly string $username,
|
||||
private readonly string $token,
|
||||
private readonly string $baseUrl,
|
||||
string $baseUrl,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {}
|
||||
) {
|
||||
$this->baseUrl = rtrim($baseUrl, '/');
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'gitea';
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->username !== '' && $this->token !== '' && $this->baseUrl !== '';
|
||||
}
|
||||
|
||||
public function ping(): void
|
||||
{
|
||||
|
||||
|
||||
$this->client->request('GET', "$this->baseUrl/api/v1/user", [
|
||||
'headers' => ['Authorization' => "token {$this->token}"],
|
||||
])->getContent();
|
||||
}
|
||||
|
||||
public function startFetch(): ResponseInterface
|
||||
{
|
||||
|
||||
|
||||
$this->logger->debug('GiteaProvider: fetching contributions', ['user' => $this->username, 'url' => $this->baseUrl]);
|
||||
|
||||
return $this->client->request('GET', "$this->baseUrl/api/v1/users/{$this->username}/heatmap", [
|
||||
'headers' => ['Authorization' => "token {$this->token}"],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int> date (Y-m-d) => contribution count
|
||||
*/
|
||||
public function fetch(): array
|
||||
public function resolveFetch(mixed $handle): array
|
||||
{
|
||||
$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();
|
||||
/** @var ResponseInterface $handle */
|
||||
$data = $handle->toArray();
|
||||
$cutoff = (new \DateTimeImmutable('-365 days'))->getTimestamp();
|
||||
$result = [];
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Provider;
|
||||
|
||||
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\Provider;
|
||||
|
||||
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\Provider;
|
||||
|
||||
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,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Provider;
|
||||
|
||||
interface ProviderInterface
|
||||
{
|
||||
/** Fire the HTTP request(s) without blocking; returns an opaque handle for resolveFetch(). */
|
||||
public function startFetch(): mixed;
|
||||
|
||||
/** @return array<string, int> date (Y-m-d) => contribution count */
|
||||
public function resolveFetch(mixed $handle): 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\Provider;
|
||||
|
||||
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\Provider;
|
||||
|
||||
enum ProviderStatusType: string
|
||||
{
|
||||
case Ok = 'ok';
|
||||
case Error = 'error';
|
||||
case NotConfigured = 'not_configured';
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Renderer;
|
||||
|
||||
/**
|
||||
* Renders a GitHub-style contribution heatmap as an inline SVG.
|
||||
@@ -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 = [
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Entity;
|
||||
|
||||
use App\Entity\Contribution;
|
||||
use App\Entity\ContributionCollection;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ContributionCollectionTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_counts_zero_when_empty(): void
|
||||
{
|
||||
$collection = new ContributionCollection();
|
||||
|
||||
$this->assertCount(0, $collection);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_counts_the_contributions_it_wraps(): void
|
||||
{
|
||||
$collection = new ContributionCollection(
|
||||
new Contribution('github', 1_700_000_000, 1),
|
||||
new Contribution('github', 1_700_086_400, 2),
|
||||
);
|
||||
|
||||
$this->assertCount(2, $collection);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_is_iterable_over_its_contributions(): void
|
||||
{
|
||||
$first = new Contribution('github', 1_700_000_000, 1);
|
||||
$second = new Contribution('gitlab', 1_700_086_400, 2);
|
||||
|
||||
$collection = new ContributionCollection($first, $second);
|
||||
|
||||
$this->assertSame([$first, $second], iterator_to_array($collection));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Entity;
|
||||
|
||||
use App\Entity\Contribution;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ContributionTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_exposes_provider_date_and_count(): void
|
||||
{
|
||||
$contribution = new Contribution('github', 1_700_000_000, 4);
|
||||
|
||||
$this->assertSame('github', $contribution->provider);
|
||||
$this->assertSame(1_700_000_000, $contribution->date);
|
||||
$this->assertSame(4, $contribution->count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\ContributionAggregator;
|
||||
use App\Service\Provider\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('resolveFetch')->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('resolveFetch')->willReturn(['2024-01-01' => 3, '2024-01-02' => 1]);
|
||||
|
||||
$providerB = $this->createStub(ProviderInterface::class);
|
||||
$providerB->method('isConfigured')->willReturn(true);
|
||||
$providerB->method('resolveFetch')->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_on_start(): void
|
||||
{
|
||||
$failing = $this->createStub(ProviderInterface::class);
|
||||
$failing->method('isConfigured')->willReturn(true);
|
||||
$failing->method('startFetch')->willThrowException(new \RuntimeException('Network error'));
|
||||
|
||||
$healthy = $this->createStub(ProviderInterface::class);
|
||||
$healthy->method('isConfigured')->willReturn(true);
|
||||
$healthy->method('resolveFetch')->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_continues_fetching_remaining_providers_when_one_throws_on_resolve(): void
|
||||
{
|
||||
$failing = $this->createStub(ProviderInterface::class);
|
||||
$failing->method('isConfigured')->willReturn(true);
|
||||
$failing->method('resolveFetch')->willThrowException(new \RuntimeException('Network error'));
|
||||
|
||||
$healthy = $this->createStub(ProviderInterface::class);
|
||||
$healthy->method('isConfigured')->willReturn(true);
|
||||
$healthy->method('resolveFetch')->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_start_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('startFetch')->willThrowException(new \RuntimeException('fail'));
|
||||
|
||||
(new ContributionAggregator([$provider], $logger))->aggregate();
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_logs_a_warning_when_a_provider_resolve_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('resolveFetch')->willThrowException(new \RuntimeException('fail'));
|
||||
|
||||
(new ContributionAggregator([$provider], $logger))->aggregate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service;
|
||||
|
||||
use App\Service\ContributionStore;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ContributionStoreTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_stores_and_retrieves_a_contribution(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:');
|
||||
|
||||
$store->add('github', 1_700_000_000, 4);
|
||||
$all = $store->all('github');
|
||||
|
||||
$this->assertCount(1, $all);
|
||||
$this->assertSame(4, iterator_to_array($all)[0]->count);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_upserts_on_a_repeated_date(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:');
|
||||
|
||||
$store->add('github', 1_700_000_000, 4);
|
||||
$store->add('github', 1_700_000_000, 9);
|
||||
$all = $store->all('github');
|
||||
|
||||
$this->assertCount(1, $all);
|
||||
$this->assertSame(9, iterator_to_array($all)[0]->count);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_removes_a_contribution(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:');
|
||||
|
||||
$store->add('github', 1_700_000_000, 4);
|
||||
$store->remove('github', 1_700_000_000);
|
||||
|
||||
$this->assertCount(0, $store->all('github'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_merges_a_batch_of_date_counts(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:');
|
||||
|
||||
$store->merge('github', [1_700_000_000 => 1, 1_700_086_400 => 2]);
|
||||
|
||||
$this->assertCount(2, $store->all('github'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_reports_the_latest_date_for_a_provider(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:');
|
||||
|
||||
$store->add('github', 1_700_000_000, 1);
|
||||
$store->add('github', 1_700_086_400, 2);
|
||||
|
||||
$this->assertSame(1_700_086_400, $store->latestDate('github'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_null_latest_date_when_provider_has_no_rows(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:');
|
||||
|
||||
$this->assertNull($store->latestDate('github'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_filters_all_by_since_days(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:');
|
||||
$now = time();
|
||||
|
||||
$store->add('github', $now - 10 * 86400, 1);
|
||||
$store->add('github', $now - 400 * 86400, 2);
|
||||
|
||||
$this->assertCount(1, $store->all('github', sinceDays: 30));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_does_not_prune_when_retention_is_unset(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:', retentionDays: null);
|
||||
|
||||
$store->add('github', time() - 1_000 * 86400, 1);
|
||||
$store->prune();
|
||||
|
||||
$this->assertCount(1, $store->all('github'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_prunes_rows_older_than_the_retention_window(): void
|
||||
{
|
||||
$store = new ContributionStore(':memory:', retentionDays: 30);
|
||||
$now = time();
|
||||
|
||||
$store->add('github', $now - 10 * 86400, 1);
|
||||
$store->add('github', $now - 40 * 86400, 2);
|
||||
$store->prune();
|
||||
|
||||
$this->assertCount(1, $store->all('github'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service\Provider;
|
||||
|
||||
use App\Service\Provider\GitHubProvider;
|
||||
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,
|
||||
): GitHubProvider {
|
||||
return new GitHubProvider(
|
||||
$client ?? $this->createStub(HttpClientInterface::class),
|
||||
$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],
|
||||
]],
|
||||
]));
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$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],
|
||||
]],
|
||||
]));
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$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);
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$provider->resolveFetch($provider->startFetch());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_empty_when_response_has_no_weeks(): void
|
||||
{
|
||||
$client = $this->createStub(HttpClientInterface::class);
|
||||
$client->method('request')->willReturn($this->stubGraphqlResponse([]));
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service\Provider;
|
||||
|
||||
use App\Service\Provider\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);
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$provider->resolveFetch($provider->startFetch());
|
||||
}
|
||||
|
||||
#[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]]);
|
||||
}
|
||||
);
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$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);
|
||||
}
|
||||
);
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$this->assertSame(2, $callCount);
|
||||
$this->assertSame(100, $result['2024-06-10']);
|
||||
$this->assertSame(1, $result['2024-06-11']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service\Provider;
|
||||
|
||||
use App\Service\Provider\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],
|
||||
]));
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$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],
|
||||
]));
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$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([]));
|
||||
|
||||
$provider = $this->makeProvider(client: $client);
|
||||
$result = $provider->resolveFetch($provider->startFetch());
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Unit\Service\Provider;
|
||||
|
||||
use App\Service\Provider\ProbeTrait;
|
||||
use App\Service\Provider\ProviderErrorCode;
|
||||
use App\Service\Provider\ProviderInterface;
|
||||
use App\Service\Provider\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 startFetch(): mixed { return null; }
|
||||
public function resolveFetch(mixed $handle): 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\Provider;
|
||||
|
||||
use App\Service\Provider\ProviderErrorCode;
|
||||
use App\Service\Provider\ProviderHealthChecker;
|
||||
use App\Service\Provider\ProviderInterface;
|
||||
use App\Service\Provider\ProviderStatus;
|
||||
use App\Service\Provider\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\Provider;
|
||||
|
||||
use App\Service\Provider\ProviderErrorCode;
|
||||
use App\Service\Provider\ProviderStatus;
|
||||
use App\Service\Provider\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\Renderer;
|
||||
|
||||
use App\Service\Renderer\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);
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user