From 5bf3160d0f0c949f578bcfbe931b3556837d1355 Mon Sep 17 00:00:00 2001 From: bidi Date: Thu, 12 Nov 2026 00:58:47 +0200 Subject: [PATCH 1/3] code refactor, updated composer, docs, workflow, tests Signed-off-by: bidi --- .claude/hooks/guard-bash.sh | 246 ++++++ .claude/hooks/guard-protected-paths.sh | 57 ++ .claude/hooks/markdown-lint.sh | 49 ++ .claude/hooks/normalize-file.sh | 91 +++ .claude/hooks/php-lint.sh | 35 + .claude/hooks/session-start.sh | 89 ++ .claude/plan-code-review.md | 767 ++++++++++++++++++ .claude/skills/plan-major-upgrade/SKILL.md | 102 +++ .github/workflows/codecov.yml | 8 +- .github/workflows/static-analysis.yml | 10 +- .gitignore | 1 + .laminas-ci.json | 5 +- CHANGELOG.md | 326 +++++++- README.md | 34 +- SECURITY.md | 12 +- composer.json | 14 +- docs/book/v4/configuration.md | 79 ++ docs/book/v4/installation.md | 9 + docs/book/v4/overview.md | 19 + docs/book/v4/upgrading.md | 28 + docs/book/v4/usage.md | 69 ++ mkdocs.yml | 9 +- phpstan.neon | 2 +- phpunit.xml | 26 +- src/ConfigProvider.php | 8 +- src/Exception/InvalidConfigException.php | 52 ++ .../ResponseHeaderMiddlewareFactory.php | 25 +- src/Middleware/ResponseHeaderMiddleware.php | 106 ++- test/ConfigProviderTest.php | 26 +- .../ResponseHeaderMiddlewareFactoryTest.php | 98 ++- test/Fixture/ArrayContainer.php | 37 + test/Fixture/FixedResponseHandler.php | 35 + test/Fixture/ServiceNotFoundException.php | 12 + .../ResponseHeaderMiddlewareTest.php | 260 +++--- 34 files changed, 2488 insertions(+), 258 deletions(-) create mode 100644 .claude/hooks/guard-bash.sh create mode 100644 .claude/hooks/guard-protected-paths.sh create mode 100644 .claude/hooks/markdown-lint.sh create mode 100644 .claude/hooks/normalize-file.sh create mode 100644 .claude/hooks/php-lint.sh create mode 100644 .claude/hooks/session-start.sh create mode 100644 .claude/plan-code-review.md create mode 100644 .claude/skills/plan-major-upgrade/SKILL.md create mode 100644 docs/book/v4/configuration.md create mode 100644 docs/book/v4/installation.md create mode 100644 docs/book/v4/overview.md create mode 100644 docs/book/v4/upgrading.md create mode 100644 docs/book/v4/usage.md create mode 100644 src/Exception/InvalidConfigException.php create mode 100644 test/Fixture/ArrayContainer.php create mode 100644 test/Fixture/FixedResponseHandler.php create mode 100644 test/Fixture/ServiceNotFoundException.php diff --git a/.claude/hooks/guard-bash.sh b/.claude/hooks/guard-bash.sh new file mode 100644 index 0000000..e84159b --- /dev/null +++ b/.claude/hooks/guard-bash.sh @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# PreToolUse guard for Bash commands in Dotkernel projects. +# Catches installs and destructive git even when hidden inside compound commands +# ("cd x && composer require y"), which path-based permission rules cannot see. +# Quoted arguments, comments and heredoc bodies are data and are not matched, so +# grep "rm -rf" docs/ is allowed. Quoted code is still checked: the script after a -c +# option (sh -c "..."), the arguments of eval, ssh and watch, and a heredoc or +# here-string fed to a shell. +# This matches text, not a parsed shell: an unusual spelling can still get past it. +# bash, sed and awk; jq is used for the payload when installed. +# Exit 0 = allow, exit 2 = block. + +set -u +export LC_ALL=C + +payload=$(cat) + +# Print tool_input.command with its JSON escapes decoded. +extract_command() { + if command -v jq >/dev/null 2>&1 \ + && printf '%s' "$payload" | jq -r '.tool_input.command // empty' 2>/dev/null; then + return + fi + # No jq: park the two escapes that can hide a quote (\\ and \") on control bytes, + # which valid JSON never contains raw, so [^"]* ends exactly at the closing quote. + local bs='\' sl='/' esc_bs=$'\002' esc_q=$'\001' s + s=$(printf '%s' "$payload" | tr -d '\n' | sed -n \ + -e 's/\\\\/'"$esc_bs"'/g' \ + -e 's/\\"/'"$esc_q"'/g' \ + -e 's/.*"command"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') + s=${s//"${bs}n"/$'\n'} + s=${s//"${bs}t"/$'\t'} + s=${s//"${bs}r"/$'\r'} + s=${s//"$bs$sl"/$sl} + s=${s//"$esc_q"/\"} + s=${s//"$esc_bs"/$bs} + printf '%s' "$s" +} + +cmd=$(extract_command) +[ -z "$cmd" ] && exit 0 + +# Reduce the command to the text that would run. Quoted strings, comments and heredoc +# bodies become the placeholder Q, and ; & | ( ) ` and newlines become separate words. +# Code inside quotes or a heredoc (the script after a -c option, the arguments of eval, +# ssh or watch, a heredoc or here-string fed to a shell) is reduced the same way and +# appended after a " ; ". An unterminated quote leaves the rest of the command unmasked. +IFS= read -r -d '' SHELL_VIEW <<'AWK' || true +{ src = (NR == 1) ? $0 : src "\n" $0 } +END { printf "%s", scan(src, 0) } + +# out: the reduced command; seg0: where the current simple command starts in out; +# ws: the next character starts a word (so # opens a comment). +function scan(s, depth, n, i, c, j, out, seg0, ws, extra, body, q, seg, code, strip, + d, nd, hd, hs, hf, h, lines, nl, ln, pos, found, cmp, start) { + n = length(s); i = 1; out = ""; seg0 = 1; ws = 1; extra = ""; nd = 0 + while (i <= n) { + if (match(substr(s, i, 512), /^[^\\'"$#<;&|()`\n]+/)) { # ordinary text, in runs + out = out substr(s, i, RLENGTH); i += RLENGTH + ws = (substr(out, length(out), 1) ~ /[ \t]/); continue + } + c = substr(s, i, 1) + + if (c == "\\") { # escaped character, or line continuation + if (substr(s, i + 1, 1) != "\n") { out = out substr(s, i + 1, 1); ws = 0 } + i += 2; continue + } + + if (c == "'" || c == "\"" || (c == "$" && substr(s, i + 1, 1) == "'")) { + q = c; j = i + 1 + if (c == "$") { q = "'"; j = i + 2 } + if (c == "'") { + j = index(substr(s, j), "'"); if (j) j += i + } else { # "..." and $'...' honour backslash escapes + while (j <= n && substr(s, j, 1) != q) j += (substr(s, j, 1) == "\\") ? 2 : 1 + if (j > n) j = 0 + } + if (!j) { out = out substr(s, i); break } + body = substr(s, i + 1, j - i - 1) + seg = substr(out, seg0); code = 0 + if (seg ~ /(^|[ \t])-[a-z]*c[ \t]*$/ || seg ~ /(^|[ \t\/])(eval|ssh|watch)[ \t]/) code = 1 + else if (sub(/<<<[ \t]*$/, "", seg)) code = feeds_shell(seg) + if (code && c != "$") extra = extra " ; " nested((c == "\"") ? undq(body) : body, depth) + out = out "Q"; i = j + 1; ws = 0; continue + } + + if (c == "#" && ws) { # comment, up to the end of the line + j = index(substr(s, i), "\n") + if (!j) break + i += j - 1; continue + } + + if (c == "<" && substr(s, i, 3) == "<<<") { out = out "<<<"; i += 3; ws = 1; continue } + if (c == "<" && substr(s, i, 2) == "<<") { # heredoc + j = i + 2; strip = 0 + if (substr(s, j, 1) == "-") { strip = 1; j++ } + while (substr(s, j, 1) == " " || substr(s, j, 1) == "\t") j++ + d = ""; q = substr(s, j, 1) + if (q == "'" || q == "\"") { + c = index(substr(s, j + 1), q) + if (c) { d = substr(s, j + 1, c - 1); j += c + 1 } + } else { + while (j <= n && substr(s, j, 1) !~ /[ \t\n;&|()<>'"]/) { + if (substr(s, j, 1) == "\\") j++ + d = d substr(s, j, 1); j++ + } + } + if (d == "") { out = out "<<"; i += 2; ws = 1; continue } + nd++; hd[nd] = d; hs[nd] = strip; hf[nd] = feeds_shell(substr(out, seg0)) + out = out " << Q "; i = j; ws = 0; continue + } + + if (c == "\n") { + out = out " ; "; seg0 = length(out) + 1; ws = 1; i++ + if (nd) { # bodies of the heredocs opened on that line + nl = split(substr(s, i), lines, "\n"); ln = 1; pos = i + for (h = 1; h <= nd; h++) { + start = pos; found = 0 + for (; ln <= nl; ln++) { + cmp = lines[ln] + if (hs[h]) sub(/^\t+/, "", cmp) + if (cmp == hd[h]) { found = 1; break } + pos += length(lines[ln]) + 1 + } + if (!found) { pos = start; break } # no terminator: scan it as commands + if (hf[h]) extra = extra " ; " nested(substr(s, start, pos - start), depth) + pos += length(lines[ln]) + 1; ln++ + } + i = pos; nd = 0 + } + continue + } + + if (index(";&|()`", c)) { out = out " " c " "; seg0 = length(out) + 1; ws = 1; i++; continue } + out = out c; ws = 0; i++ + } + return out extra +} + +# The command so far ends with a shell that reads its script from stdin. +function feeds_shell(seg) { return seg ~ /(^|[ \t\/])(ba|z|da|k|a)?sh([ \t]+-[a-z]+)*[ \t]*$/ } + +function nested(s, depth) { return (depth < 4) ? scan(s, depth + 1) : s } + +function undq(s, r, i, n, c, nx) { # remove the escapes "..." honours + r = ""; n = length(s) + for (i = 1; i <= n; i++) { + c = substr(s, i, 1) + if (c == "\\" && i < n) { + nx = substr(s, i + 1, 1) + if (nx == "\n") { i++; continue } + if (index("\"\\$`", nx)) { r = r nx; i++; continue } + } + r = r c + } + return r +} +AWK + +lc=$(printf '%s' "$cmd" | tr '[:upper:]' '[:lower:]') +view=$(printf '%s' "$lc" | awk "$SHELL_VIEW") || view=$lc +norm=$(printf '%s' "$view" | tr '\t\r\n' ' ' | tr -s ' ') + +block() { + local shown=$cmd + [ ${#shown} -gt 500 ] && shown="${shown:0:500}..." + printf 'BLOCKED command: %s\n%s\n' "$shown" "$1" >&2 + exit 2 +} + +set -f +# shellcheck disable=SC2206 # word splitting is the point; globbing is off +words=($norm) +set +f +nw=${#words[@]} + +# composer [options] [global] . Composer resolves any unambiguous prefix of a +# command name (req, upd, inst, rem) and the aliases r, i, u, upgrade, rm, uninstall. +for ((i = 0; i < nw; i++)); do + case ${words[i]} in + composer|composer.phar|*/composer|*/composer.phar) ;; + *) continue ;; + esac + j=$((i + 1)) + while ((j < nw)); do + case ${words[j]} in + -d|--working-dir) j=$((j + 2)) ;; + -*) j=$((j + 1)) ;; + *) [[ global == "${words[j]}"* ]] && j=$((j + 1)) || break ;; + esac + done + sub=${words[j]:-} + [[ $sub =~ ^[a-z]+$ ]] || continue + for name in require remove update upgrade install uninstall rm; do + [[ $name == "$sub"* ]] \ + && block "Dependency changes need my explicit approval. Tell me the package and why, and I will run it." + done +done + +case " $norm " in + *"npm install"*|*"npm i "*|*"npm uninstall"*|*"npm update"*|*"npm ci"*|\ + *"yarn add"*|*"yarn remove"*|*"pnpm add"*|*"pnpm remove"*|*"pip install"*) + block "Package installs need my explicit approval." ;; +esac + +case " $norm " in + *"git push"*|*"git reset --hard"*|*"git clean -"*|*"git checkout -- "*|\ + *"git submodule"*|*"git filter-branch"*|*"git rebase"*) + block "Destructive or publishing git operations are mine to run." ;; +esac + +# rm with both a recursive and a force flag, in any spelling: -rf, -fr, -r -f, -Rf, +# --recursive --force. Its arguments end at a separator, at -- and at find's "{} +". +for ((i = 0; i < nw; i++)); do + case ${words[i]} in rm|*/rm) ;; *) continue ;; esac + rec=0 force=0 + for ((j = i + 1; j < nw; j++)); do + w=${words[j]} + case $w in + ';'|'&'|'|'|'('|')'|'`'|--|+) break ;; + --?*) [[ recursive == "${w#--}"* ]] && rec=1 + [[ force == "${w#--}"* ]] && force=1 ;; + -?*) [[ $w == *r* ]] && rec=1 + [[ $w == *f* ]] && force=1 ;; + esac + done + ((rec && force)) && block "Refusing destructive filesystem command." +done + +case " $norm " in + *"mkfs"*|*"chmod -r 777"*) + block "Refusing destructive filesystem command." ;; +esac + +case " $norm " in + *"doctrine-migrations migrate"*|*"doctrine-migrations execute"*|\ + *"fixtures:execute"*|*"schema:drop"*|*"schema:update"*) + block "Database-mutating commands need my approval. Show me the command and what it will change." ;; +esac + +case " $norm " in + *"development-enable"*|*"development-disable"*) + block "Toggling development mode changes committed config state. Ask me first." ;; +esac + +exit 0 diff --git a/.claude/hooks/guard-protected-paths.sh b/.claude/hooks/guard-protected-paths.sh new file mode 100644 index 0000000..6dcb4fa --- /dev/null +++ b/.claude/hooks/guard-protected-paths.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# PreToolUse guard for Dotkernel projects. +# Blocks writes to vendored, generated, secret or dependency-manifest files. +# Pure bash, no jq — works in Git Bash on Windows. +# Exit 0 = allow, exit 2 = block (stderr is shown to Claude). + +set -u + +payload=$(cat) + +# Pull the target path out of tool_input without a JSON parser: "file_path" for +# Edit, Write and MultiEdit, "notebook_path" for NotebookEdit. +path_field() { + printf '%s' "$payload" \ + | tr -d '\n' \ + | sed -n 's/.*"'"$1"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' +} +raw_path=$(path_field file_path) +[ -z "$raw_path" ] && raw_path=$(path_field notebook_path) + +[ -z "$raw_path" ] && exit 0 + +# Normalise: unescape JSON backslashes, turn \ into /, drop a drive prefix, lowercase. +path=${raw_path//\\\\/\\} +path=${path//\\//} +path=${path#[A-Za-z]:} +lower=$(printf '%s' "$path" | tr '[:upper:]' '[:lower:]') + +block() { + printf 'BLOCKED: %s\n%s\n' "$raw_path" "$1" >&2 + exit 2 +} + +case "$lower" in + */vendor/*|vendor/*) + block "vendor/ is Composer-managed. Change the dependency or your own code instead." ;; + */node_modules/*|node_modules/*) + block "node_modules/ is npm-managed." ;; + */migration/*|*/migrations/*) + block "Migrations are generated. Adjust the entity and regenerate with 'doctrine-migrations diff'." ;; + */data/cache/*|*/data/lock/*|*/data/oauth/*|data/cache/*|data/lock/*|data/oauth/*) + block "data/ holds generated cache, locks and keys. Never hand-edit." ;; + */log/*|log/*) + block "log/ is runtime output." ;; + */public/uploads/*|public/uploads/*) + block "public/uploads/ is user-uploaded content." ;; + *composer.json|*composer.lock|*package.json|*package-lock.json|*yarn.lock|*pnpm-lock.yaml) + block "Dependency manifests require explicit user approval. Propose the change in chat first." ;; + *.local.php|*/local.php|local.php|*/local.test.php|local.test.php) + block "Local config holds environment secrets and is git-ignored. Edit the .dist template and let the user apply it." ;; + *.phpcs-cache|*.phpunit.result.cache|*/.git/*) + block "Tool cache / git internals." ;; + *.png|*.jpg|*.jpeg|*.gif|*.svg|*.ico|*.zip|*.phar|*.key|*.pem) + block "Binary or key material." ;; +esac + +exit 0 diff --git a/.claude/hooks/markdown-lint.sh b/.claude/hooks/markdown-lint.sh new file mode 100644 index 0000000..84f3c8c --- /dev/null +++ b/.claude/hooks/markdown-lint.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# PostToolUse: markdownlint a .md file right after it is written. +# Report-only by design — it does NOT run --fix. Reformatting a file that Claude +# just wrote invalidates its in-memory copy and breaks the next targeted edit, +# so bulk fixing stays a deliberate end-of-task action. +# Exit 2 surfaces the violations to Claude immediately. +# Silent exit 0 when markdownlint-cli2 is not installed, so .claude/ stays +# drop-in with no npm requirement. + +set -u + +payload=$(cat) + +raw_path=$(printf '%s' "$payload" | tr -d '\n' \ + | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') + +[ -z "$raw_path" ] && exit 0 + +path=${raw_path//\\\\/\\} +path=${path//\\//} + +lower=$(printf '%s' "$path" | tr '[:upper:]' '[:lower:]') + +case "$lower" in + *.md|*.markdown) ;; + *) exit 0 ;; +esac +case "$lower" in + */vendor/*|*/node_modules/*|*/.git/*|*/data/*|*/log/*) exit 0 ;; +esac +[ -f "$path" ] || exit 0 + +config="${CLAUDE_PROJECT_DIR:-.}/.claude/markdownlint.jsonc" +[ -f "$config" ] || exit 0 + +bin="" +if [ -x ./node_modules/.bin/markdownlint-cli2 ]; then + bin=./node_modules/.bin/markdownlint-cli2 +elif command -v markdownlint-cli2 >/dev/null 2>&1; then + bin=markdownlint-cli2 +fi +[ -z "$bin" ] && exit 0 + +if ! output=$("$bin" --config "$config" "$path" 2>&1); then + printf 'markdownlint violations in %s\n%s\n' "$path" "$output" >&2 + exit 2 +fi + +exit 0 diff --git a/.claude/hooks/normalize-file.sh b/.claude/hooks/normalize-file.sh new file mode 100644 index 0000000..e436548 --- /dev/null +++ b/.claude/hooks/normalize-file.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# PostToolUse normaliser for Dotkernel projects. +# Enforces: UTF-8 without BOM, LF line endings, no trailing whitespace, +# exactly one trailing newline. Pure bash + sed + awk, no jq. +# Rewrites the file in place, so its permissions, owner and links survive. +# Exit 0 always — this fixes silently rather than blocking. + +set -u + +payload=$(cat) + +raw_path=$(printf '%s' "$payload" | tr -d '\n' \ + | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') + +[ -z "$raw_path" ] && exit 0 + +path=${raw_path//\\\\/\\} +path=${path//\\//} + +[ -f "$path" ] || exit 0 + +lower=$(printf '%s' "$path" | tr '[:upper:]' '[:lower:]') + +# Skip binaries and anything not ours. +case "$lower" in + *.png|*.jpg|*.jpeg|*.gif|*.ico|*.svg|*.zip|*.phar|*.pdf|*.woff|*.woff2|*.ttf|*.eot|*.key|*.pem) + exit 0 ;; + */vendor/*|*/node_modules/*|*/.git/*|*/data/*|*/log/*) + exit 0 ;; +esac + +# Text files only. +case "$lower" in + *.php|*.phtml|*.twig|*.md|*.json|*.xml|*.neon|*.yml|*.yaml|*.sh|*.txt|*.dist|*.html|*.css|*.js|*.sql|*.editorconfig|*.gitattributes|*.gitignore) ;; + *) exit 0 ;; +esac + +changed="" +tmp=$(mktemp "${TMPDIR:-/tmp}/dk-normalize.XXXXXX") || exit 0 +trap 'rm -f "$tmp"' EXIT + +# Copy the fixed text back over the original. Writing through the existing file, rather +# than moving a new one into place, keeps its mode (an executable script stays +# executable), its owner, and any symlink or hard link to it. +write_back() { { cat "$tmp" > "$path"; } 2>/dev/null; } + +# 1. Strip UTF-8 BOM. +bom=$(printf '\357\273\277') +if [ "$(head -c 3 "$path" 2>/dev/null)" = "$bom" ]; then + tail -c +4 "$path" > "$tmp" && write_back && changed="${changed} BOM-removed" +fi + +# 2. CRLF -> LF, then a lone CR (classic Mac line ending) -> LF. +if LC_ALL=C grep -qU $'\r' "$path" 2>/dev/null; then + LC_ALL=C sed $'s/\r$//' "$path" | tr '\r' '\n' > "$tmp" && write_back \ + && changed="${changed} CRLF->LF" +fi + +# 3. Trailing whitespace (skip markdown: two trailing spaces are a hard line break). +case "$lower" in + *.md) ;; + *) + if LC_ALL=C grep -q '[[:space:]]$' "$path"; then + sed 's/[[:space:]]*$//' "$path" > "$tmp" && write_back \ + && changed="${changed} trailing-ws-stripped" + fi + ;; +esac + +# 4. Exactly one trailing newline: add a missing one, drop blank or whitespace-only lines +# at the end. A file with nothing but whitespace is left alone. +if [ -s "$path" ]; then + LC_ALL=C awk ' + /^[ \t\f\v]*$/ { held = held $0 "\n"; next } # blank: hold until a line follows + { printf "%s%s\n", held, $0; held = "" } # still held at the end: dropped + ' "$path" > "$tmp" + if [ -s "$tmp" ] && ! cmp -s "$tmp" "$path"; then + if [ "$(wc -c < "$tmp")" -gt "$(wc -c < "$path")" ]; then + fix=newline-added + else + fix=trailing-blank-lines-removed + fi + write_back && changed="${changed} ${fix}" + fi +fi + +if [ -n "$changed" ]; then + printf 'File hygiene applied to %s:%s\n' "$path" "$changed" >&2 +fi + +exit 0 diff --git a/.claude/hooks/php-lint.sh b/.claude/hooks/php-lint.sh new file mode 100644 index 0000000..d902a12 --- /dev/null +++ b/.claude/hooks/php-lint.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# PostToolUse: syntax-check a PHP file right after it is written. +# Report-only by design — it does NOT reformat. Reformatting a file that Claude +# just wrote invalidates its in-memory copy and breaks the next targeted edit, +# so phpcbf is deliberately left to `composer cs-fix` / /dk-check at the end. +# Exit 2 surfaces the parse error to Claude immediately. + +set -u + +payload=$(cat) + +raw_path=$(printf '%s' "$payload" | tr -d '\n' \ + | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') + +[ -z "$raw_path" ] && exit 0 + +path=${raw_path//\\\\/\\} +path=${path//\\//} + +case "$path" in + *.php) ;; + *) exit 0 ;; +esac +case "$path" in + */vendor/*|*/node_modules/*) exit 0 ;; +esac +[ -f "$path" ] || exit 0 +command -v php >/dev/null 2>&1 || exit 0 + +if ! output=$(php -l "$path" 2>&1); then + printf 'PHP syntax error in %s\n%s\n' "$path" "$output" >&2 + exit 2 +fi + +exit 0 diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh new file mode 100644 index 0000000..fbcf056 --- /dev/null +++ b/.claude/hooks/session-start.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +# SessionStart: print a short briefing that becomes part of Claude's context. +# Detects which Dotkernel project this is and what is not set up yet. +# Everything here is read-only. Keep the output compact. + +set -u +cd "${CLAUDE_PROJECT_DIR:-.}" 2>/dev/null || exit 0 + +echo "## Project state" + +# --- which Dotkernel project? --- +if [ -f composer.json ]; then + pkg=$(sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' composer.json | head -1) + ns=$(grep '": "src/' composer.json 2>/dev/null | grep -v '"Core' | head -1 \ + | sed 's/^[^"]*"\([A-Za-z]*\).*/\1/') + variant="unknown" + case "$pkg" in + */api) variant="API (REST/HAL)" ;; + */admin) variant="Admin (templated, forms)" ;; + */frontend) variant="Frontend (templated, forms)" ;; + */light) variant="Light (minimal starter)" ;; + */queue) variant="Queue (CLI/worker)" ;; + esac + if [ "$variant" = "unknown" ]; then + hal=0 form=0 + grep -q 'mezzio/mezzio-hal' composer.json && hal=1 + grep -q 'laminas/laminas-form' composer.json && form=1 + case "$hal$form" in + 10) variant="API-style (has mezzio-hal)" ;; + 01) variant="templated-style (has laminas-form)" ;; + 11) variant="unclear (has mezzio-hal and laminas-form; infer the parent from the PSR-4 roots)" ;; + esac + fi + echo "- package: ${pkg:-unknown} | variant: ${variant}" + [ -n "$ns" ] && echo "- root namespace: ${ns}" + guards=config/autoload/authorization-guards.global.php + if [ -f "$guards" ]; then + policy=$(sed -n "s/.*protection_policy.*\(POLICY_[A-Z]*\).*/\1/p" "$guards" | head -1) + echo "- authorization: guards + RBAC (${guards##*/}${policy:+, $policy})" + [ "$policy" = POLICY_ALLOW ] && echo " unlisted routes are PUBLIC — every new route needs a guard rule" + elif [ -f config/autoload/authorization.global.php ]; then + echo "- authorization: RBAC (authorization.global.php) — unlisted routes are denied" + fi +fi + +# --- git --- +# Ask git rather than test for a .git directory: in a worktree or a submodule checkout +# .git is a file. +if command -v git >/dev/null 2>&1 \ + && [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = true ]; then + eol_bad=$(git ls-files --eol 2>/dev/null | grep -c 'w/crlf' || true) + [ "${eol_bad:-0}" -gt 0 ] && echo "- WARNING: ${eol_bad} tracked file(s) have CRLF in the worktree; run /dk-hygiene" + top=$(git rev-parse --show-toplevel 2>/dev/null) + if [ -f "$top/.gitmodules" ]; then + subs=$(git config -f "$top/.gitmodules" --get-regexp '^submodule\..*\.path$' 2>/dev/null \ + | cut -d' ' -f2- | tr '\n' ' ') + subs=${subs% } + case " $subs " in + *" src/Core "*) echo "- git submodules: ${subs}. Core is one: commit inside src/Core, then bump the pointer here" ;; + " ") ;; + *) echo "- git submodules: ${subs}" ;; + esac + fi +fi + +# --- setup completeness --- +[ -f composer.json ] && [ ! -d vendor ] \ + && echo "- vendor/ missing — dependencies are not installed (run /dk-bootstrap)" + +for d in config/autoload/*.dist config/*.dist; do + [ -e "$d" ] || continue + target=${d%.dist} + [ -f "$target" ] && continue + case "$target" in + config/development.config.php) continue ;; # managed by development-mode, not copied by hand + esac + echo "- missing ${target} (copy from ${d})" +done + +for d in docs/features documentation/features; do + [ -d "$d" ] || continue + n=$(ls -1 "$d"/*.md 2>/dev/null | grep -vc '/README\.md$' || true) + echo "- ${d}/: ${n:-0} feature doc(s) — read the relevant one before adding behaviour there" +done + +[ -f config/development.config.php ] && echo "- development mode is ENABLED" +[ -f data/cache/config-cache.php ] && echo "- config cache present; clear it after config edits" + +exit 0 diff --git a/.claude/plan-code-review.md b/.claude/plan-code-review.md new file mode 100644 index 0000000..d2096f2 --- /dev/null +++ b/.claude/plan-code-review.md @@ -0,0 +1,767 @@ +# Plan: dotkernel/dot-response-header 4.0.0 + +Plan for the next major release of `dotkernel/dot-response-header`, written on 2026-11-11 on the `upgrade` branch (cut from `3.0` at tag `3.6.0`). The target is `4.0.0`, supporting PHP 8.3 to 8.6, PHPUnit 12, PHPStan level 8, and `mezzio/mezzio-router` 3.x and 4.x. The work is on `upgrade` and will be merged into a new `4.0` branch after review. Re-checked on 2026-11-11 after the maintainer's `composer.json` edits and `composer update`, then implemented the same day (rollout steps 2 to 8). `composer check` passes. Nothing is committed. + +## Implementation status + +| Item | State | Notes | +| --- | --- | --- | +| V1 PHP range in `composer.json` | Done by the maintainer | `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.6.0`; `composer why-not php 8.6.0` and `8.3.0` find no blocker | +| V2 `phpunit/phpunit` to 12 | Done by the maintainer | `^12.5`; 12.5.43 installed | +| V3 Remaining `composer.json` edits | Done by the maintainer | Exactly as planned; `composer validate --strict` passes. Optional: router floor `^3.17` (see V3) | +| V4 Workflows and `.laminas-ci.json` | Done | Maintainer: versions and actions. Me: `codecov.yml` on 8.5 only; `static-analysis.yml` job id `static-analysis`, `coverage: none`. All 4 workflow files parse as YAML; not run in CI yet. `.laminas-ci.json` unchanged | +| V5 `phpstan.neon` level 8 | Done | Level 8 and `--level max` both clean in the repository, no ignores | +| V6 `phpunit.xml` and `.gitignore` | Done | Local schema, `failOn*` flags (confirmed: the 5 old notices made PHPUnit exit 1). `.gitignore` has `.phpunit.cache` and keeps `.phpunit.result.cache` for 3.x checkouts | +| F1 to F6 code fixes | Done | Code as in the findings; `src/Exception/InvalidConfigException.php` added | +| F7 to F9 tests | Done | 27 tests, 42 assertions; fixtures `ArrayContainer`, `ServiceNotFoundException`, `FixedResponseHandler`. 14 failed against the 3.6.0 `src/` before step 5 (7 errors, 7 failures). No mocks left | +| D1 docs `v4`, README, SECURITY, mkdocs | Done | New `docs/book/v4/` (overview, installation, configuration, usage, upgrading). All 10 nav targets exist; `mkdocs build` not run (not installed). Badges and the license link in README and `v4/overview.md` point at branch `4.0`; `v3/overview.md` keeps `3.0` | +| D2 CHANGELOG | Done | `3.0.0` to `4.0.0`, newest first, `3.0.1` date fixed to 2021-05-18; lint-clean | +| D3 Upgrade guide | Done | `docs/book/v4/upgrading.md`; the error message it quotes was produced at runtime | +| Release | Waiting for the maintainer | Review, merge `upgrade` into `4.0`, tag `4.0.0`, CHANGELOG date, re-enable the BC check after release | + +## Decision: version 4 + +- `4.0.0` is a major release because it drops PHP 8.2, and the recommended fixes (F2, F3, F5) change behaviour for misconfigured applications and make two classes `final`. +- Release lines in the repository: branches `3.0` (default), `upgrade` (this work) and `gh-pages`; tags `3.0.0` to `3.6.0`. There is no `4.x` branch and no parallel line, so 4.x is the direct successor of 3.x. No discontinued-line page is needed (T13 does not apply). +- The work is on `upgrade` and will be merged into `4.0` after review (decided by the maintainer on 2026-11-11). Badges and links that name a branch (`?branch=`, `blob//LICENSE`) in README and `v4/overview.md` use `4.0`; `v3/overview.md` keeps `3.0`. `3.0` stays for security fixes. +- After release, `3.0` should be marked "security fixes only" in `SECURITY.md` and the README. + +## Baseline + +Run on 2026-11-11, first in scratch (before `vendor/` existed), then re-run in the repository after the maintainer's `composer update`. + +| Check | Result | +| --- | --- | +| `git describe --tags` | `3.6.0` (HEAD is exactly the tag) | +| PHP available locally | 8.5.12 only. No pcov or Xdebug | +| Installed in the repository | PHPUnit 12.5.43, PHPStan 2.3.5, phpstan-phpunit 2.1.1, mezzio-router 4.3.0, diactoros 3.10.0, laminas-coding-standard 3.1.0, psr/container 2.0.2, psr/http-message 2.0, psr/http-server-handler 1.0.2, psr/http-server-middleware 1.0.2 | +| `composer validate --strict` | Valid | +| `composer check` in the repository | **Fails at PHPStan**: phpcs clean; PHPUnit 9 tests, 45 assertions, OK with 5 PHPUnit notices; PHPStan level 8 the same 7 errors as in V5. Identical to scratch A | +| `composer why-not php 8.6.0` / `8.3.0` | No installed package blocks either version | +| `composer show -l --direct` | All direct dependencies at their latest allowed version. PHPUnit 13.4.6 exists (requires PHP `>=8.4.1`), so 12 stays the right major while 8.3 is supported | +| Scratch runs (before `vendor/` existed) | Against two sibling `vendor/` directories (read-only symlinks) with a bootstrap that adds this package's PSR-4 namespaces; see below | +| Scratch A: `dot-errorhandler/vendor` | PHPUnit 12.5.43, PHPStan 2.3.5, phpstan-phpunit 2.1.1, mezzio-router **4.3.0**, diactoros 3.10.0, laminas-coding-standard 3.1.0 | +| Scratch B: `admin/vendor` | PHPUnit 12.5.38, PHPStan 2.2.17, mezzio-router **3.20.0**, diactoros 3.8.0, mezzio 3.x with FastRoute and laminas-servicemanager | +| phpcs | Clean (A) | +| PHPUnit 12, current tests | 9 tests, 45 assertions, OK **with 5 PHPUnit notices** (A and B): mock objects without expectations | +| PHPStan level 5 (old level) | Clean (B) | +| PHPStan level 8 | 7 errors (A and B), listed in V5 | +| Laminas BC check | Disabled by the maintainer (`backwardCompatibilityCheck: false`). Enabled, it would compare against `3.6.0` and report the intended breaks (F5 `final`, F2 validation). Re-enable after `4.0.0` is tagged so 4.x minors are checked against `4.0.0` | + +## Done by the maintainer + +Uncommitted edits found in the working tree: + +| File | Edit | Status | +| --- | --- | --- | +| `composer.json` | `php`: first `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.2.0`, corrected to `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.6.0` | Correct after the re-check | +| `composer.json` | `phpunit/phpunit`: `^10.2` to `^12.5` | Correct | +| `composer.json` | V3 edits: router `^3.16 \|\| ^4.0`, `psr/container`, `psr/http-server-handler`, `psr/http-server-middleware` added, `psr/http-client` removed, diactoros `^3.10` | Correct, matches the diff below | +| `phpstan.neon` | `level: 5` to `level: 8` | Correct | +| `codecov.yml`, `static-analysis.yml` | PHP matrix 8.3 to 8.6; `actions/checkout@v7`, `actions/cache@v6`, `codecov/codecov-action@v7` | Correct, see V4 for the rest | +| `.laminas-ci.json` | `ignore_php_platform_requirements` for 8.6; `backwardCompatibilityCheck: false` | Correct for the major | + +The `composer.json` edits that were requested (all applied by the maintainer and installed): + +```diff + "require": { +- "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.2.0", +- "mezzio/mezzio-router": "^3.16", +- "psr/http-client": "^1.0", +- "psr/http-message": "^1.0 || ^2.0" ++ "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", ++ "mezzio/mezzio-router": "^3.16 || ^4.0", ++ "psr/container": "^1.1 || ^2.0", ++ "psr/http-message": "^1.0 || ^2.0", ++ "psr/http-server-handler": "^1.0", ++ "psr/http-server-middleware": "^1.0" + }, + "require-dev": { + "laminas/laminas-coding-standard": "^3.0", +- "laminas/laminas-diactoros": "^3.1", ++ "laminas/laminas-diactoros": "^3.10", + "phpstan/phpstan": "^2.1", + "phpstan/phpstan-phpunit": "^2.0", + "phpunit/phpunit": "^12.5" + }, +``` + +Optional follow-up (see V3): `"mezzio/mezzio-router": "^3.17 || ^4.0"`, because no `3.16.x` release can install on PHP 8.3 or newer. + +## Findings + +### V1. PHP range + +- Status: fixed by the maintainer on 2026-11-11; the "After" below is now in `composer.json`. +- Location: `composer.json:22`. +- Evidence (before the fix): the constraint read `~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.2.0`. 8.2 is still allowed and 8.6 is missing. PHPUnit 12 requires `php >=8.3` (read from `vendor/phpunit/phpunit/composer.json`), so a PHP 8.2 install cannot resolve dev dependencies. The custom workflows run 8.6, where `composer install` refuses the root package. Laminas CI builds its matrix from this constraint, so it never runs 8.6. + +Before: + +```json +"php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.2.0", +``` + +After: + +```json +"php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", +``` + +- Why: matches the agreed range (8.3 to 8.6), the workflows and PHPUnit 12. + +### V2. PHPUnit 12 (T5) + +- Done by the maintainer in `composer.json`. What the tests and config need: + - `phpunit.xml` schema points at 10.2 (V6). + - Annotations: none are used, so nothing to convert. New data providers must be `public static` and attached with `#[DataProvider]` (F8 does this). + - Mock rules: PHPUnit 12 raises a notice for a mock with no expectations. The current `ResponseHeaderMiddlewareTest::setUp()` creates two mocks for every test, which gives the 5 notices in the baseline. F8 replaces them with real objects and a fixture handler; `createStub()` would be the fallback. + - `PHPUnit\Framework\MockObject\Exception` in `@throws` tags disappears with the mocks. + - `failOn*` flags: V6. + +### V3. Undeclared and unused dependencies (T10, T11) + +Imports in `src/` (from `grep -rn "^use " src`) against `require`: + +| Package | Used in `src/` | Declared | Action | +| --- | --- | --- | --- | +| `mezzio/mezzio-router` | `RouteResult` (middleware) | `^3.16` | Widen to `^3.16 \|\| ^4.0` | +| `psr/container` | Factory | No (comes via `mezzio-router`) | Add `^1.1 \|\| ^2.0` | +| `psr/http-message` | Middleware | `^1.0 \|\| ^2.0` | Keep | +| `psr/http-server-middleware` | `MiddlewareInterface` | No | Add `^1.0` | +| `psr/http-server-handler` | `RequestHandlerInterface` | No | Add `^1.0` | +| `psr/http-client` | Nowhere in `src/` or `test/` | `^1.0` | Remove | + +- `mezzio-router` 4.x: `4.3.0` (read from `dot-errorhandler/vendor`) declares `php: ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0`; `3.20.0` (from `admin/vendor`) declares `~8.2.0 || ... || ~8.5.0`. So **PHP 8.6 needs router 4.x**. `RouteResult::getMatchedRouteName(): false|string` and `isSuccess()` are the same in both. The full suite and PHPStan pass against both (Baseline A and B). `mezzio/mezzio` 3.29.0 accepts `^3.15.0 || ^4.0.0`. +- Lowest installable router per PHP version, from Packagist metadata (`composer show --all mezzio/mezzio-router `): + +| PHP | Lowest router allowed by `^3.16 \|\| ^4.0` | Why | +| --- | --- | --- | +| 8.3 | 3.17.0 | 3.16.x declares `~8.1.0 \|\| ~8.2.0` only | +| 8.4 | 3.18.0 | | +| 8.5 | 3.19.0 | | +| 8.6 | 4.3.0 | No 3.x release and no 4.0 to 4.2 release declares 8.6 (4.0.x stops at 8.4, 4.1 and 4.2 at 8.5) | + +- So the `3.16` floor is unreachable on every supported PHP version. It does no harm (Composer filters by platform), but `^3.17 || ^4.0` states the real floor. Optional; not needed for correctness. +- Removal evaluation for `mezzio-router` (T11): it is needed for one class, `RouteResult`, which is how the middleware finds the matched route name. There is no PSR interface for a matched route. Options: (a) keep it, (b) read a configurable request attribute instead, which breaks every existing config and loses the type check. Recommendation: **keep it**; the package is Mezzio middleware by design. +- `laminas/laminas-diactoros` (dev): `3.10.0` declares 8.6; `3.8.0` and `3.9.0` stop at 8.5. Raise to `^3.10` so lowest-dependency CI on 8.6 does not need the platform override for it. +- `suggest` and `conflict`: none needed. +- `laminas/laminas-servicemanager` is not a runtime requirement, so T20 does not apply. + +### V4. Workflows (T4) + +Checked every file in `.github/workflows` and `.laminas-ci.json`. + +| File | State | Change | +| --- | --- | --- | +| `continuous-integration.yml` | Uses `laminas/workflow-continuous-integration@1.x` | None. Its matrix follows the `composer.json` PHP range (V1) | +| `docs-build.yml` | Uses `dotkernel/documentation-theme/...@main` | None | +| `codecov.yml` | Bumped by the maintainer | Run on one PHP version only | +| `static-analysis.yml` | Bumped by the maintainer | `coverage: none`; rename job id `mutation` | +| `.laminas-ci.json` | Edited by the maintainer | None now; re-enable BC check after `4.0.0` | + +`codecov.yml` uploads four coverage reports per push, and pcov for PHP 8.6 may not exist yet (unverified). + +Before (`codecov.yml`): + +```yaml + php: + - "8.3" + - "8.4" + - "8.5" + - "8.6" +``` + +After: + +```yaml + php: + - "8.5" +``` + +`static-analysis.yml` loads pcov although PHPStan never uses it, and the job id says `mutation`. + +Before: + +```yaml +jobs: + mutation: + name: PHPStan ${{ matrix.php }}-${{ matrix.os }} +... + coverage: pcov +``` + +After: + +```yaml +jobs: + static-analysis: + name: PHPStan ${{ matrix.php }}-${{ matrix.os }} +... + coverage: none +``` + +- Why: the 8.6 row in both custom workflows can install now that V1 is in. `composer why-not php 8.6.0` finds no blocker in the installed (latest) tree, so no `--ignore-platform-req` is needed for latest dependencies. +- `.laminas-ci.json` `ignore_php_platform_requirements` for 8.6: likely no longer needed for direct dependencies (router 4.3.0 and diactoros 3.10.0 both declare 8.6). Keep it until a CI run on lowest dependencies for 8.6 is green without it, then remove it. + +### V5. PHPStan level 8 (T3) + +Current level was 5 (clean). At level 8, identical on router 3.20 and 4.3: + +| # | Location | Identifier | Fix | +| --- | --- | --- | --- | +| 1 | `src/ConfigProvider.php:12` | `missingType.iterableValue` | Array shape `@return` (F6) | +| 2 | `src/ConfigProvider.php:19` | `missingType.iterableValue` | Array shape `@return` (F6) | +| 3 | `src/Middleware/ResponseHeaderMiddleware.php:19` | `missingType.iterableValue` | Typed config property (F2) | +| 4 | `src/Middleware/ResponseHeaderMiddleware.php:21` | `missingType.iterableValue` | `@param array`, normalised into the typed property (F2) | +| 5 | `src/Middleware/ResponseHeaderMiddleware.php:36` | `argument.type` (`string\|false` given) | Check `getMatchedRouteName() !== false` (F1) | +| 6 | `test/Middleware/ResponseHeaderMiddlewareTest.php:34` | `argument.type` (`MockObject\|ServerRequestInterface`) | Real `ServerRequest`, no mocks (F8) | +| 7 | `test/Middleware/ResponseHeaderMiddlewareTest.php:34` | `argument.type` (`MockObject\|RequestHandlerInterface`) | Fixture handler (F8) | + +No ignores, baseline, `assert()` or `@var` overrides are used. The prototype is clean at level 8 and at `max`. + +### V6. `phpunit.xml` and `.gitignore` (T5, T15) + +Before: + +```xml + + + + ./test + + + + + + ./src + + + +``` + +After (validated by PHPUnit 12.5.38 and 12.5.43 in scratch): + +```xml + + + + + test + + + + + src + + + +``` + +`.gitignore`: add `.phpunit.cache`; keep `.phpunit.result.cache`, which PHPUnit still writes on a 3.x checkout. + +- Why: the local schema follows the installed PHPUnit; the flags turn the 5 current notices (and any future deprecation) into failures. Deprecations raised inside vendor code on PHP 8.6 would also fail the build; if that happens, the fix is a dependency bump, or `` already limits deprecation reporting to `src`, so first-party code stays strict (unverified on 8.6). + +### F1. Matched route name is `false|string` + +- Severity: low (type safety; no runtime failure found). +- Location: `src/Middleware/ResponseHeaderMiddleware.php:35-36`. +- Evidence: PHPStan error V5 #5. `isSuccess()` makes it safe today, but the type is not narrowed. + +Before: + +```php +$routeResult = $request->getAttribute(RouteResult::class); +if ($routeResult instanceof RouteResult && $routeResult->isSuccess()) { + $response = $this->addHeaders($response, $routeResult->getMatchedRouteName()); +} +return $response; +``` + +After: + +```php +$routeResult = $request->getAttribute(RouteResult::class); +if (! $routeResult instanceof RouteResult) { + return $response; +} + +$routeName = $routeResult->getMatchedRouteName(); +if ($routeName === false) { + return $response; +} + +return $this->addHeaders($response, $routeName); +``` + +- Why: `getMatchedRouteName()` returns `false` exactly when the result is a failure in both router 3.20 and 4.3, so this is the same behaviour with a checked type. + +### F2. Invalid header config fails on every request, or is silently ignored + +- Severity: medium. +- Location: `src/Middleware/ResponseHeaderMiddleware.php:41-58`. +- Evidence (scratch script `repro.php`, same result on router 3.20 and 4.3): + +| Config | Result today | +| --- | --- | +| `'*' => 'oops'` (route not an array) | PHP warning `foreach() argument must be of type array\|object`, headers silently dropped | +| `'*' => ['X-A' => 'v']` (shorthand) | `TypeError: array_key_exists(): Argument #2 ($array) must be of type array, string given` on every request | +| `'value' => null` | `Laminas\Diactoros\Exception\InvalidArgumentException` on every request | +| `'overwrite' => 1` on an existing header | Silently treated as `false` | +| `'value' => 3600` | Works with Diactoros, but PSR-7 `withHeader()` only promises `string\|string[]` | + +The errors surface per request, inside the response, after the handler already ran, and the message never names the config key. + +Before: + +```php +private array $config; + +public function __construct(array $config) +{ + $this->config = $config; +} +``` + +After (full class, verified): + +```php +/** + * @phpstan-type HeaderConfig array{value: string|non-empty-list, overwrite: bool} + * @phpstan-type ResponseHeadersConfig array> + */ +class ResponseHeaderMiddleware implements MiddlewareInterface +{ + private const ALL_ROUTES = '*'; + + /** @var ResponseHeadersConfig */ + private readonly array $config; + + /** + * @param array $config + * @throws InvalidConfigException + */ + public function __construct(array $config) + { + $this->config = self::normalize($config); + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + // as in F1 + } + + public function addHeaders(ResponseInterface $response, string $route): ResponseInterface + { + foreach ($this->config[$route] ?? [] as $header => $data) { + if ($response->hasHeader($header) && ! $data['overwrite']) { + continue; + } + $response = $response->withHeader($header, $data['value']); + } + + return $response; + } + + /** + * @param array $config + * @return ResponseHeadersConfig + * @throws InvalidConfigException + */ + private static function normalize(array $config): array + { + $normalized = []; + foreach ($config as $route => $headers) { + if (! is_array($headers)) { + throw InvalidConfigException::routeNotArray($route, $headers); + } + foreach ($headers as $header => $data) { + if (! is_array($data)) { + throw InvalidConfigException::headerNotArray($route, $header, $data); + } + if (! array_key_exists('value', $data)) { + continue; + } + $overwrite = $data['overwrite'] ?? false; + if (! is_bool($overwrite)) { + throw InvalidConfigException::invalidOverwrite($route, $header, $overwrite); + } + + $normalized[(string) $route][(string) $header] = [ + 'value' => self::normalizeValue($route, $header, $data['value']), + 'overwrite' => $overwrite, + ]; + } + } + + return $normalized; + } + + /** + * @return string|non-empty-list + * @throws InvalidConfigException + */ + private static function normalizeValue(int|string $route, int|string $header, mixed $value): string|array + { + if (is_string($value)) { + return $value; + } + if (is_int($value) || is_float($value)) { + return (string) $value; + } + if (! is_array($value) || $value === [] || ! array_is_list($value)) { + throw InvalidConfigException::invalidValue($route, $header, $value); + } + + $values = []; + foreach ($value as $item) { + if (! is_string($item)) { + throw InvalidConfigException::invalidValue($route, $header, $value); + } + $values[] = $item; + } + + return $values; + } +} +``` + +New `src/Exception/InvalidConfigException.php`: + +```php + []` throws `Exception: Unable to find dot-response-header config.`, although the middleware handles an empty config as a no-op (`process()` returns early). A `config` service that is an `ArrayObject` or `null` gives a `TypeError` from `array_key_exists()`. `$container->get('config')` is called twice, and the `?? []` is dead code. + +Before: + +```php +class ResponseHeaderMiddlewareFactory +{ + // constants unchanged + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ + public function __invoke(ContainerInterface $container): ResponseHeaderMiddleware + { + if (! $container->has('config')) { + throw new Exception(self::MESSAGE_MISSING_CONFIG); + } + $config = $container->get('config'); + + if ( + ! array_key_exists('dot_response_headers', $config) + || ! is_array($config['dot_response_headers']) + || empty($config['dot_response_headers']) + ) { + throw new Exception(self::MESSAGE_MISSING_PACKAGE_CONFIG); + } + + return new ResponseHeaderMiddleware($container->get('config')['dot_response_headers'] ?? []); + } +} +``` + +After: + +```php +final class ResponseHeaderMiddlewareFactory +{ + public const MESSAGE_MISSING_CONFIG = 'Unable to find config.'; + public const MESSAGE_MISSING_PACKAGE_CONFIG = 'Unable to find dot-response-header config.'; + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws InvalidConfigException + */ + public function __invoke(ContainerInterface $container): ResponseHeaderMiddleware + { + if (! $container->has('config')) { + throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); + } + + $config = $container->get('config'); + if (! is_array($config) && ! $config instanceof ArrayAccess) { + throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); + } + + $headers = $config['dot_response_headers'] ?? null; + if (! is_array($headers)) { + throw new InvalidConfigException(self::MESSAGE_MISSING_PACKAGE_CONFIG); + } + + return new ResponseHeaderMiddleware($headers); + } +} +``` + +- Why: an empty array is a valid way to turn all headers off (for example per environment). A missing key still throws, so a forgotten config file is still reported. `InvalidConfigException` extends `InvalidArgumentException`, which extends `Exception`, so `catch (Exception)` keeps working and the message constants are unchanged. + +### F4. Route headers cannot replace `*` headers unless `overwrite` is `true` + +- Severity: documentation only (behaviour kept). +- Evidence: with `'*' => ['X-All' => ['value' => 'a']]` and `'home' => ['X-All' => ['value' => 'route']]`, a request to `home` gets `X-All: a`. `*` headers are applied first, so a route header is an "existing header" and needs `overwrite => true`. The existing test `testWillAddHeadersWithCommonWithRouteSpecificHeadersConfiguredWhenRouteMatched` asserts this, so it is intended. +- Change: say it in `usage.md` (D1). Also say that route keys match the **exact** route name; the README's "any route name matching 'user'" reads like a pattern. + +### F5. `ConfigProvider` and the factory are not `final` + +- Severity: low (API hygiene). +- Before: `class ConfigProvider`, `class ResponseHeaderMiddlewareFactory`. +- After: `final class ...` for both. `ResponseHeaderMiddleware` stays non-final and `addHeaders()` stays public, since applications may extend or call it. +- Why: same choice as `dot-cache` 5.0. Breaking for anyone extending them; listed in the upgrade guide. + +### F6. `ConfigProvider` return types + +- Location: `src/ConfigProvider.php:12,19` (V5 #1 and #2). + +Before: + +```php +public function __invoke(): array +``` + +After: + +```php +/** + * @return array{dependencies: array{factories: array}} + */ +public function __invoke(): array +``` + +and `@return array{factories: array}` on `getDependencies()`. + +### F7. Coverage gaps (T16) + +Measured by reading the tests (no coverage driver here, so line numbers are not from a report): + +- `process()` is only called with an empty config, so lines 33-38 (common headers, route lookup) never run. +- The factory success path is never tested; neither is a non-array `config`. +- `ConfigProviderTest` only asserts `assertIsArray`, which is always true. +- `addHeaders()` on a missing `value` key (line 45-47) is not tested. +- Route failure (404/405 `RouteResult`) is not tested. + +### F8. Rewrite the tests (T8, T16) + +- Replace mocks with real collaborators: `Laminas\Diactoros\ServerRequest`, a real `RouteResult::fromRoute()` / `fromRouteFailure()`, and three fixtures in `test/Fixture/`: + - `ArrayContainer` (`final readonly`, PSR-11 `get()` / `has()` over an array; same as `dot-cache`). + - `ServiceNotFoundException extends RuntimeException implements NotFoundExceptionInterface`. + - `FixedResponseHandler` (`RequestHandlerInterface` returning one `Response`, optionally with pre-set headers). +- Data providers are `public static` with `#[DataProvider]`; test classes are `final`. +- Prototype: 27 tests, 42 assertions, OK on PHPUnit 12.5.38 and 12.5.43, phpcs clean, PHPStan level 8 and `max` clean. **14 of the 27 fail against the current `src/`** (the bug tests for F2 and F3). + +| Test class | Cases | +| --- | --- | +| `ConfigProviderTest` | `__invoke()` wraps `getDependencies()`; the middleware maps to its factory | +| `ResponseHeaderMiddlewareFactoryTest` | Missing `config`; non-array `config`; package key missing / string / null (provider); empty package config is a no-op; `ArrayObject` config; invalid package config fails at creation | +| `ResponseHeaderMiddlewareTest` | Empty config returns the handler response unchanged; no `RouteResult`; route failure; matched route with `overwrite` true/false against `*`; route without config; handler header kept unless `overwrite`; header without `value` skipped; valid values string / int / float / list (provider); 6 invalid configs with exact messages (provider) | + +Before (excerpt): + +```php +public function setUp(): void +{ + $this->responseHeader = new ResponseHeaderMiddleware([]); + $this->serverRequest = $this->createMock(ServerRequestInterface::class); + $this->requestHandler = $this->createMock(RequestHandlerInterface::class); +} +``` + +After (excerpt): + +```php +public function testMatchedRouteAddsRouteHeadersAfterCommonHeaders(): void +{ + $response = (new ResponseHeaderMiddleware(self::CONFIG)) + ->process($this->requestForRoute('home'), new FixedResponseHandler()); + + $this->assertSame('home', $response->getHeaderLine('X-Home')); + $this->assertSame('home', $response->getHeaderLine('X-All'), 'route header with overwrite replaces *'); + $this->assertSame('all', $response->getHeaderLine('X-Overwrite'), 'route header without overwrite keeps *'); +} +``` + +- Coverage driver: none installed here. CI already uses pcov in `codecov.yml`. Mutation testing (`infection/infection`) is optional for a package this size; not recommended as a new dev dependency now. + +### F9. Integration check (T18) + +- Scratch Mezzio 3 application (laminas-servicemanager, FastRoute, router 3.20) with `RouteMiddleware`, this middleware, `DispatchMiddleware`, `NotFoundHandler`, and the README config pasted verbatim. +- Result, old and new code identical: `/` gets `CustomHeader1` overwritten, `CustomHeader2` kept from the handler, `CustomHeader` added; `/login` gets `LoginHeader`; `/missing` (404) gets only the `*` headers. +- Not run against router 4.x with a real router implementation (no FastRoute in the 4.x vendor here). + +## Documentation + +`docs/book/index.md` is a symlink to `../../README.md`, so README edits are the docs home page. + +| Page | Required change | +| --- | --- | +| `docs/book/v3/*` | Unchanged | +| `docs/book/v4/` | New folder, copied from `v3` | +| `v4/overview.md` | Badge `php-v/.../3.6.0` to `4.0.0`; `?branch=4.0` and `blob/4.0/LICENSE` | +| `v4/installation.md` | `composer require dotkernel/dot-response-header:^4.0` | +| `v4/configuration.md` | PHP 8.3 to 8.6; `value` accepts string, number or list of strings; `overwrite` must be a bool; empty `dot_response_headers` is allowed; invalid config throws `InvalidConfigException` naming the key | +| `v4/usage.md` | `*` first, then the exact route name (F4); route header needs `overwrite => true` to replace a `*` header; middleware must be piped after `RouteMiddleware` or route headers never apply; example of a multi-value header | +| `v4/upgrading.md` | New, content below | +| `README.md` | Versions table (below); "PHP: 8.3, 8.4, 8.5 or 8.6"; badge `3.6.0` to `4.0.0`; "matching 'user'" wording (F4); missing trailing comma in the `LoginHeader` example | +| `SECURITY.md` | Rows below; fix the double blank line (MD012) and the typo "newc" | +| `mkdocs.yml` | `current_version: v4`; `versions: [v4, v3]`; `v4` nav first with Overview, Installation, Configuration, Usage, Upgrading | +| `CHANGELOG.md` | D2 | + +README and `SECURITY.md` versions table: + +| Version | Supported | PHP | +| --- | --- | --- | +| 4.x | :white_check_mark: | 8.3 to 8.6 | +| 3.x | Security fixes only | 8.2 to 8.5 | +| <= 2.x | :x: | | + +All existing PHP snippets in README, `v3` docs and `config/response-header.global.php.dist` pass `php -l` (the fragment in `usage.md` was wrapped in an array to lint it). The README config example runs unchanged in the integration check. + +### D3. Upgrade guide (`v4/upgrading.md`) + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 dropped | Composer refuses to install | PHP 8.3 or newer | +| `overwrite` must be a `bool` | `InvalidConfigException: dot_response_headers..
.overwrite must be a bool, int given.` | Use `true` / `false`. In 3.x, `1` or `'true'` were silently treated as `false` | +| Route and header entries must be arrays | `InvalidConfigException` naming the key | In 3.x a string route entry was ignored with a PHP warning, and a string header entry threw `TypeError` per request | +| `value` must be a string, number or non-empty list of strings | `InvalidConfigException` | In 3.x `null` threw from the PSR-7 implementation on every request | +| Factory throws `InvalidConfigException` | Code catching `Exception` still works; code checking `get_class()` or the exact class does not | Catch `InvalidArgumentException` or `InvalidConfigException` | +| `ConfigProvider` and factory are `final` | `Class ... cannot extend final class` | Decorate or write your own factory | + +Changes in behaviour: empty `dot_response_headers` now creates a no-op middleware; numeric values are sent as strings; invalid config fails when the middleware is created instead of on each request. + +## CHANGELOG + +The file has only `3.0.0` and `3.0.1`, oldest first, with `3.0.1` dated `2021-01-18` (the tag is `2021-05-18`). It fails markdownlint (MD041, MD022, MD032). Rewrite newest first, add `# Changelog`, blank lines around headings and lists, `-` bullets, and keep the Changed / Added / Deprecated / Removed / Fixed sections with "Nothing" where empty. Entries from the git history between tags: + +| Version | Date | Content | +| --- | --- | --- | +| 4.0.0 | TBD | Changed: PHP `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.6.0`; `mezzio-router` `^3.16 \|\| ^4.0`; config validated on construction (F2); factory throws `InvalidConfigException`; `ConfigProvider` and factory `final`; PHPUnit 12, PHPStan level 8, `failOn*`; actions v7/v6/v7. Added: PHP 8.6, router 4, `InvalidConfigException`, explicit `psr/container` and `psr/http-server-*` requirements, `v4` docs and upgrade guide. Removed: PHP 8.2, `psr/http-client` (unused). Fixed: empty config throwing (F3), `TypeError` for non-array `config`, warnings and per-request errors for bad config | +| 3.6.0 | 2025-10-30 | Removed PHP 8.1; added PHP 8.4 and 8.5 | +| 3.5.0 | 2025-03-12 | Replaced Psalm with PHPStan | +| 3.4.1 | 2025-01-28 | Psalm 6; "DotKernel" spelled "Dotkernel" | +| 3.4.0 | 2024-10-22 | PHP 8.4; laminas-coding-standard 3 | +| 3.3.1 | 2024-05-27 | `psr/http-message` back to `^1.0 \|\| ^2.0` | +| 3.3.0 | 2024-05-03 | v3 documentation; `psr/http-message` `^2.0` only; SECURITY unsupported versions | +| 3.2.3 | 2023-11-30 | PHP 8.3 | +| 3.2.2 | 2023-08-22 | Codecov workflow and badges | +| 3.2.1 | 2023-08-16 | `psr/http-message` `^1.0 \|\| ^2.0`; diactoros `^3.1` | +| 3.2.0 | 2023-07-28 | PHP `~8.1.0 \|\| ~8.2.0`; required `mezzio-router`, `psr/http-client`, `psr/http-message`; tests, laminas-coding-standard, Psalm; `DotTest` autoload | +| 3.1.0 | 2022-04-06 | PHP `~7.4.0 \|\| ~8.0.0 \|\| ~8.1.0`; PHPUnit 9.5 | +| 3.0.1 | 2021-05-18 | CHANGELOG added; README and middleware changes | +| 3.0.0 | 2021-05-14 | Initial release | + +## Rollout order + +1. ~~Maintainer: apply the `composer.json` edits (V1, V3) and run `composer update`.~~ Done; baseline re-run in the repository on 2026-11-11. +2. ~~`phpunit.xml` and `.gitignore` (V6).~~ Done: PHPUnit exits 1 on the 5 old notices. +3. ~~`ConfigProvider` types and `final` (F5, F6).~~ Done: PHPStan 7 to 5 errors, phpcs clean. +4. ~~Tests rewritten with fixtures (F8), first against the current `src/`.~~ Done: 14 expected failures confirmed. +5. ~~`InvalidConfigException`, middleware (F1, F2), factory (F3).~~ Done: `composer check` passes. +6. ~~Workflows (V4).~~ Done. +7. ~~Docs `v4`, README, SECURITY, mkdocs (D1, D3).~~ Done; lint-clean. +8. ~~CHANGELOG (D2).~~ Done; lint-clean. +9. Maintainer: review, merge `upgrade` into `4.0`, tag `4.0.0`, CHANGELOG date; then re-enable `backwardCompatibilityCheck` in `.laminas-ci.json`. + +## Verification checklist + +- [x] `composer validate --strict` (valid after the maintainer's edits) +- [x] `composer why-not php 8.6.0` and `8.3.0`: no blocker +- [x] `composer check` (phpcs, PHPUnit, PHPStan) passes in the repository: 27 tests, 42 assertions, PHPStan level 8 clean +- [x] `vendor/bin/phpstan analyse --level max`: clean +- [x] No `MockObject` left in `test/`: `grep -rn "createMock\|MockObject" test` finds nothing +- [x] Every new bug test fails on the 3.6.0 code and passes after the fix (14 failed before step 5) +- [x] `php -l` on every PHP snippet in README and `docs/book/v4` (the one-line `ConfigProvider::class,` fragment linted inside an array) +- [x] Every v4 usage and configuration example run through the middleware; output matches what the docs say +- [x] Every `mkdocs.yml` nav target exists +- [ ] `mkdocs build --strict` (not installed here) +- [x] markdownlint passes on README, SECURITY, CHANGELOG, `docs/book/v4/*.md` and this plan with `~/.claude/.markdownlint.jsonc` +- [x] No CRLF line endings; every changed file ends with a newline +- [ ] CI green on 8.3, 8.4, 8.5 and 8.6, lowest and latest dependencies +- [ ] Unverified here, to confirm in CI: + - [ ] PHP 8.3, 8.4 and 8.6 (only 8.5.12 is installed locally) + - [ ] Lowest dependencies: `mezzio-router` 3.17.0 (8.3), 3.18.0 (8.4), 3.19.0 (8.5), 4.3.0 (8.6); `psr/container` 1.1; `psr/http-message` 1.0; diactoros 3.10.0 + - [x] Which `mezzio-router` release first declares PHP 8.6: 4.3.0 (Packagist metadata; 4.0.x stops at 8.4) + - [ ] Whether `ignore_php_platform_requirements` for 8.6 can be removed from `.laminas-ci.json` + - [ ] pcov availability for PHP 8.6 on `setup-php` (only matters if codecov keeps 8.6) + - [ ] Line coverage numbers (no pcov or Xdebug locally) + - [ ] Integration with router 4.x and a real router implementation + - [ ] Vendor deprecations on PHP 8.6 with `failOnDeprecation` diff --git a/.claude/skills/plan-major-upgrade/SKILL.md b/.claude/skills/plan-major-upgrade/SKILL.md new file mode 100644 index 0000000..541cb38 --- /dev/null +++ b/.claude/skills/plan-major-upgrade/SKILL.md @@ -0,0 +1,102 @@ +--- +name: plan-major-upgrade +description: Build the written plan for the next major version of a Dotkernel PHP package, saved in `.claude/plan-code-review.md`. Use when asked to review a package and plan its next major release - code review with before/after fixes, phpstan level, workflow and PHP version bumps, PHPUnit upgrade, new docs folder, CHANGELOG and tests. Also use to re-check or update that plan after the maintainer changes `composer.json`. +--- + +# Plan a major upgrade + +Produce one plan file, `.claude/plan-code-review.md`, and keep it current while the work is done. +The plan is the deliverable of the first pass. Make no other changes until the maintainer asks you to implement it. + +## Ground rules + +- **Measure before you claim.** Run the checks and reproduce each suspected bug with a failing test or a small script before it goes in the plan as a bug. Mark anything you could not run as "unverified" and say why (PHP version not installed, no coverage driver, lowest dependencies not installed). +- **Do not edit `composer.json` or install packages.** Edits are denied by the permission settings and the guard hooks block installs. Give the exact lines to change and ask the maintainer to apply them and run the install. Re-check the plan after every such change. +- **Do not circumvent a hook.** If a guard blocks a command, adapt (use the Edit and Write tools, a scratch directory) or ask. +- **Verify facts about other packages from the source**, for example `vendor/` or the published package listing, never from memory. A wrong claim in the plan becomes wrong docs. +- **Markdown is lint-clean.** Every `.md` file you write or edit must pass the maintainer's markdownlint config before you report it as done. + +## Inputs to settle first + +Ask only what you cannot determine from the repository. + +| Item | How to find it | +| --- | --- | +| Next major version number and branch | Ask. Use the current branch name for the plan. Check `git tag`, `git describe --tags` and the remote branches for existing lines | +| Whether other release lines exist | Check branches and tags. A separate line (for example an attribute-based `5.x`) changes the upgrade guide and the README | +| Target PHP versions | From the maintainer or the CI workflow. Note which are installed locally | +| What the maintainer does by hand | Typically `composer.json`, `phpstan.neon` level and the workflow versions. Do not redo or revert them | + +## Task list + +The first eight items (T1 to T8) are the requested tasks. The rest were missed in the original list and should be part of every plan. + +### Requested + +- **T1. Recommend fixes for issues and bugs in the codebase.** Review `src/` for correctness, robustness, types and style. Give each finding an id (F1, F2, ...), a severity, a location and evidence from a reproduction. +- **T2. Add before/after sections** for every recommended update: current code or behaviour, recommended code or behaviour, and why. Cover code, config, docs and tests. +- **T3. `phpstan.neon` to level 8.** Record the current level, run PHPStan at level 8 and list every error with its identifier and fix. Do not propose ignores, baselines or `assert()` workarounds. +- **T4. Workflow versions.** Remove the old PHP version, add the new one, and set the action versions the maintainer named (for example `actions/checkout@v7`, `actions/cache@v6`, `codecov/codecov-action@v7`). Check every file in `.github/workflows` and `.laminas-ci.json`. +- **T5. `phpunit/phpunit` to the new major.** Say whether the maintainer has to do it (it edits `composer.json`) and list the PHPUnit changes the tests need: configuration schema, attributes instead of annotations, static data providers, mock and stub rules, `failOn*` flags. +- **T6. New docs folder for the next major version** in `docs/book`, copied from the most recent version. Keep the old version folders unchanged. List every page that needs content changes. +- **T7. CHANGELOG.md** with all missing releases and the new major release, following the file's section convention. +- **T8. Update the tests**, including new tests for each fixed bug. + +### Recommended additions + +- **T9. Baseline.** Before planning, run `composer check` and record the result, the PHP versions available locally, and the nearest reachable tag (`git describe --tags`). State what the Laminas backward-compatibility check will compare against. +- **T10. Dependency review** of `composer.json`: PHP constraint, each runtime requirement and its range, requirements that are used but undeclared, requirements that are declared but unused, dev dependencies, `suggest` and `conflict`. List exact edits for the maintainer. +- **T11. Dependency removal evaluation.** For any dependency that exists for one import, check whether a PSR interface can replace it and what that would break. Give options and a recommendation. +- **T12. Upgrade guide** (`upgrading.md`) for each older line, with a table of changes that can break code: change, symptom, fix. +- **T13. Discontinued lines.** If a release line is discontinued, add a page in that version's docs folder and point to the replacement package. Read the replacement's source or listing first. +- **T14. README, `docs/book/index.md`, `SECURITY.md` and `mkdocs.yml`.** Version table rows, badges, the supported versions table, `current_version`, `versions` and the navigation. Check whether `docs/book/index.md` is a symlink to the README. +- **T15. `phpunit.xml` and CI flags.** Fail on notices, warnings, deprecations and risky tests. Plan for deprecations raised in vendor code on the newest PHP version. +- **T16. Test quality.** Prefer fixtures and a real collaborator over mocks. Check for traps, for example an annotation reader parsing an `@Inject` mentioned in prose inside a docblock. List coverage gaps by branch, and suggest a coverage driver and mutation testing if none is installed. +- **T17. Documentation examples.** Run every PHP snippet and check every link and navigation entry. Fix examples that never worked. +- **T18. Integration check** outside the repository with the real dependencies (for example a SQLite entity manager and a PSR-6 pool), in a scratch directory. +- **T19. Lifecycle metadata.** Check `OSSMETADATA`, badges and branch names for the new version. +- **T20. Remove `laminas/laminas-servicemanager` when it is a runtime requirement.** Check the `require` section of `composer.json` (a `require-dev` entry or an absence means skip this item). If it is there, implement the removal as `dot-dependency-injection` does, and put each step in the plan with before/after sections: + - Find every use: `grep -rni "laminas\|ServiceManager" src test`. Read `dot-dependency-injection` (`src/Factory`, `src/ConfigProvider.php`, `composer.json`) from its source, not from memory. + - Make the factories plain classes with `__invoke(ContainerInterface $container, string $requestedName)` and only `Psr\Container` imports, so they work with any PSR-11 container that accepts a factory per service key. + - Remove the classes that implement a Laminas interface, normally the abstract factory and its marker annotation. This is a breaking change: list it under Removed in the CHANGELOG and give a "replacing it" section in the upgrade guide, with before and after code. + - Make `ConfigProvider` return `[]` instead of registering `abstract_factories`. Keep the class so applications that list it do not break. + - Replace `ServiceManager` in the tests with a minimal PSR-11 fixture container (`get(string $id): mixed`, `has(string $id): bool`) and exception fixtures that implement `NotFoundExceptionInterface` and `ContainerExceptionInterface`. Class names must end in `Exception` for the coding standard. + - Update the docs, README, version table and CHANGELOG. Say the factories work with any PSR-11 container, and that applications using Laminas Service Manager require it themselves. + - Allow `psr/container` as `^1.1 || ^2.0`, and give the maintainer the `composer.json` edit: remove the requirement and reword the `description`. + - Verify: no `Laminas` or `ServiceManager` left in `src` or `test`, and `composer check` passes. State that the lowest `psr/container` version is unverified unless it was installed. +- **T21. Unverified list.** End the plan with what could not be tested here and how the maintainer can test it in CI. + +## Workflow + +1. Read the repository: `src/`, `test/`, `composer.json`, `phpstan.neon`, `phpunit.xml`, `.github/workflows`, `.laminas-ci.json`, `docs/book`, `README.md`, `CHANGELOG.md`, `SECURITY.md`, `mkdocs.yml`. +2. Run the baseline (T9). +3. Review the code and reproduce each suspected bug (T1 and T2). Use scratch files outside the repository. +4. Run PHPStan at the target level (T3). +5. Review dependencies, workflows and documentation (T4 to T6, T10 to T15 and T20). +6. Write the plan with the structure below. +7. Lint the plan, then tell the maintainer what they have to do by hand. +8. On request, implement the plan in the rollout order, run `composer check` after each step, and update the plan's status table. After every `composer.json` change by the maintainer, re-run the checks and update the docs and CHANGELOG. + +## Plan structure + +Use these headings, in this order. + +1. `# Plan: ` with one paragraph of context (branch, version, date). +2. `## Implementation status`: a table of item, state and notes. Update it as work lands. +3. `## Decision: version `: why this number, and how it relates to other release lines. +4. `## Baseline`: results of the commands you ran, and what you could not run. +5. `## Done by the maintainer`: the edits that were made by hand, and the exact edits still needed. +6. `## Findings`: one section per finding, each with Location, Evidence, Before, After and Why. Group as V1..Vn for version and tooling items, F1..Fn for code and test items. +7. `## Documentation`: a table of page and required change. +8. `## CHANGELOG`: the entries to add, by version. +9. `## Rollout order`: numbered steps, smallest safe change first. +10. `## Verification checklist`: checkboxes for every command and manual check, including the unverified list. + +Use `Before` and `After` as fenced code blocks (`php`, `diff`, `yaml`, `json` or `text`), never an untagged fence. + +## Checklist before reporting done + +- Every finding has a reproduction or is marked unverified. +- Every dependency claim was read from `vendor/` or `composer.json`. +- The plan file passes markdownlint. +- The final message lists what the maintainer must do by hand and what could not be tested here. diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0fbc53..9652006 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -50,6 +50,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..b428224 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -4,7 +4,7 @@ on: name: Run PHPStan checks jobs: - mutation: + static-analysis: name: PHPStan ${{ matrix.php }}-${{ matrix.os }} runs-on: ${{ matrix.os }} @@ -15,20 +15,20 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" - coverage: pcov + coverage: none ini-values: assert.exception=1, zend.assertions=1, error_reporting=-1, log_errors_max_len=0, display_errors=On tools: composer:v2, cs2pr @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} diff --git a/.gitignore b/.gitignore index 948af93..bf3f030 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ composer.phar .phpcs-cache .idea composer.lock +.phpunit.cache .phpunit.result.cache diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..efdd72e 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { - "backwardCompatibilityCheck": true + "ignore_php_platform_requirements": { + "8.6": true + }, + "backwardCompatibilityCheck": false } diff --git a/CHANGELOG.md b/CHANGELOG.md index d3870ad..d09f5df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,34 +1,334 @@ -## 3.0.0 - 2021-05-14 +# Changelog + +## 4.0.0 - TBD + +### Changed + +- PHP requirement is now `~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0` +- `mezzio/mezzio-router` requirement is now `^3.16 || ^4.0` +- The header configuration is validated when the middleware is created; a wrong type throws `Dot\ResponseHeader\Exception\InvalidConfigException` naming the key +- `overwrite` must be a `bool`; `value` must be a string, a number or a non-empty list of strings +- `ResponseHeaderMiddlewareFactory` throws `InvalidConfigException` instead of `Exception` (the messages are unchanged) +- `ConfigProvider` and `ResponseHeaderMiddlewareFactory` are now `final` +- PHPUnit `^12.5`, PHPStan level 8, PHPUnit fails on deprecations, notices, warnings and risky tests +- Tests use real PSR-7 objects and fixtures instead of mocks +- CI: GitHub Actions bumped to `actions/checkout@v7`, `actions/cache@v6`, `codecov/codecov-action@v7`; coverage runs on PHP 8.5 only + +### Added + +- Support for PHP 8.6 +- Support for `mezzio/mezzio-router` 4 +- `Dot\ResponseHeader\Exception\InvalidConfigException` +- Explicit `psr/container`, `psr/http-server-handler` and `psr/http-server-middleware` requirements +- `v4` documentation and the "Upgrading to 4.x" guide + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.2 +- `psr/http-client` requirement (it was never used) + +### Fixed + +- An empty `dot_response_headers` array no longer throws in the factory +- A `config` service that is not an array no longer throws a `TypeError` +- Invalid header entries no longer raise PHP warnings or errors on every request + +## 3.6.0 - 2025-10-30 + +### Changed + +- Nothing + +### Added + +- Support for PHP 8.4 and 8.5 + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.1 + +### Fixed + +- Nothing + +## 3.5.0 - 2025-03-12 ### Changed -* Nothing + +- Replaced Psalm with PHPStan ### Added -* Everything + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- `vimeo/psalm` ### Fixed -* Nothing -## 3.0.1 - 2021-01-18 +- Nothing + +## 3.4.1 - 2025-01-28 ### Changed -* README.md -* src/Middleware/ResponseHeaderMiddleware.php + +- Bumped `vimeo/psalm` to `^6.0` +- "DotKernel" spelled "Dotkernel" in `composer.json` ### Added -* CHANGELOG.md + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing + +## 3.4.0 - 2024-10-22 + +### Changed + +- Bumped `laminas/laminas-coding-standard` to `^3.0` + +### Added + +- Support for PHP 8.4 + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.3.1 - 2024-05-27 + +### Changed + +- `psr/http-message` requirement back to `^1.0 || ^2.0` + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.3.0 - 2024-05-03 + +### Changed + +- `psr/http-message` requirement is now `^2.0` + +### Added + +- Documentation for v3 +- Unsupported versions in `SECURITY.md` + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- `mkdocs.yml` navigation and README examples + +## 3.2.3 - 2023-11-30 + +### Changed + +- Nothing + +### Added + +- Support for PHP 8.3 + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.2.2 - 2023-08-22 + +### Changed + +- README badges + +### Added + +- Codecov workflow and badge + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.2.1 - 2023-08-16 + +### Changed + +- `psr/http-message` requirement is now `^1.0 || ^2.0` +- `laminas/laminas-diactoros` dev requirement is now `^3.1` + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.2.0 - 2023-07-28 + +### Changed + +- PHP requirement is now `~8.1.0 || ~8.2.0` +- Directory structure and namespaces +- PHPUnit `^10.2` + +### Added + +- Support for PHP 8.2 +- Explicit `mezzio/mezzio-router`, `psr/http-client` and `psr/http-message` requirements +- Unit tests, `laminas/laminas-coding-standard` and Psalm static analysis +- `composer check` script + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 7.4 and 8.0 + +### Fixed + +- Nothing + +## 3.1.0 - 2022-04-06 + +### Changed + +- PHP requirement is now `~7.4.0 || ~8.0.0 || ~8.1.0` +- PHPUnit `^9.5.20` + +### Added + +- Support for PHP 8.0 and 8.1 + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.0.1 - 2021-05-18 + +### Changed + +- README.md +- src/Middleware/ResponseHeaderMiddleware.php + +### Added + +- CHANGELOG.md + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.0.0 - 2021-05-14 + +### Changed + +- Nothing + +### Added + +- Everything + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing diff --git a/README.md b/README.md index f70b795..a22f07e 100644 --- a/README.md +++ b/README.md @@ -6,23 +6,33 @@ Documentation is available at: https://docs.dotkernel.org/dot-response-header/. +## Versions + +| Version | Supported | PHP | +| --- | --- | --- | +| 4.x | :white_check_mark: | 8.3 to 8.6 | +| 3.x | Security fixes only | 8.2 to 8.5 | +| <= 2.x | :x: | | + +Upgrading from 3.x? See [Upgrading to 4.x](https://docs.dotkernel.org/dot-response-header/v4/upgrading/). + ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-response-header) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/3.6.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/4.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/blob/3.0/LICENSE) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/blob/4.0/LICENSE) -[![Build Static](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-response-header/graph/badge.svg?token=NNRZN0FBF2)](https://codecov.io/gh/dotkernel/dot-response-header) -[![PHPStan](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml) ## Requirements -- **PHP**: 8.2, 8.3, 8.4 or 8.5 +- **PHP**: 8.3, 8.4, 8.5 or 8.6 ## Installation @@ -72,7 +82,7 @@ return [ 'login' => [ 'LoginHeader' => [ 'value' => 'LoginHeader-Value', - 'overwrite' => false + 'overwrite' => false, ], ], ], @@ -83,7 +93,7 @@ Because headers are matched with route names, we can have custom response header All headers under `*` will be set for every response. -To add response headers for a specific set of routes, define a new array using the route name as the array key. +To add response headers for a specific route, define a new array using the exact route name as the array key. Example: @@ -93,11 +103,13 @@ Example: 'UserCustomHeader' => [ 'value' => 'UserCustomHeader-Value', 'overwrite' => false, - ] + ], ], -] +], -// This will set a new header named UserCustomHeader with the UserCustomHeader-Value value for any route name matching 'user' +// This will set a new header named UserCustomHeader with the UserCustomHeader-Value value for the route named 'user' ``` -To overwrite an existing header use `overwrite => true`. +To overwrite an existing header use `overwrite => true`. The `*` headers are applied before the route headers, so a route header replaces a `*` header with the same name only when it sets `overwrite => true`. + +An invalid configuration throws `Dot\ResponseHeader\Exception\InvalidConfigException` when the middleware is created, with a message naming the key. diff --git a/SECURITY.md b/SECURITY.md index 197e900..96b6390 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,10 +2,11 @@ ## Supported Versions -| Version | Supported | PHP Version | -|---------|--------------------|---------------------------------------------------------------------------------------------------------------------| -| 3.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/3.6.0) | -| <= 2.x | :x: | | +| Version | Supported | PHP Version | +|---------|---------------------|---------------------------------------------------------------------------------------------------------------------| +| 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/4.0.0) | +| 3.x | Security fixes only | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/3.6.0) | +| <= 2.x | :x: | | ## Reporting Potential Security Issues @@ -20,12 +21,11 @@ When reporting issues, please provide the following information: - A summary of the security vulnerability and impact We request that you contact us via the email address above and give the -project contributors a chance to resolve the vulnerability and issue a newc +project contributors a chance to resolve the vulnerability and issue a new release prior to any public exposure; this helps protect the project's users, and provides them with a chance to upgrade and/or update in order to protect their applications. - ## Policy If we verify a reported security vulnerability, our policy is: diff --git a/composer.json b/composer.json index 0ad6170..b35f7b2 100644 --- a/composer.json +++ b/composer.json @@ -19,17 +19,19 @@ "mezzio" ], "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", - "mezzio/mezzio-router": "^3.16", - "psr/http-client": "^1.0", - "psr/http-message": "^1.0 || ^2.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "mezzio/mezzio-router": "^3.16 || ^4.0", + "psr/container": "^1.1 || ^2.0", + "psr/http-message": "^1.0 || ^2.0", + "psr/http-server-handler": "^1.0", + "psr/http-server-middleware": "^1.0" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0", - "laminas/laminas-diactoros": "^3.1", + "laminas/laminas-diactoros": "^3.10", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12.5" }, "autoload": { "psr-4": { diff --git a/docs/book/v4/configuration.md b/docs/book/v4/configuration.md new file mode 100644 index 0000000..7881160 --- /dev/null +++ b/docs/book/v4/configuration.md @@ -0,0 +1,79 @@ +# Configuration + +## Requirements + +- **PHP**: 8.3, 8.4, 8.5 or 8.6 +- **mezzio/mezzio-router**: 3.x or 4.x (PHP 8.6 needs 4.3 or newer) + +## Register ConfigProvider + +Next, register the package's `ConfigProvider` to your application config. + +```php +Dot\ResponseHeader\ConfigProvider::class, +``` + +> Make sure to register the package under the `// DK packages` section. + +## Add the package to the middleware stack + +After registering the package, add it to the middleware stack in `config/pipeline.php` after `$app->pipe(RouteMiddleware::class);` + +```php +$app->pipe(RouteMiddleware::class); +$app->pipe(\Dot\ResponseHeader\Middleware\ResponseHeaderMiddleware::class); +``` + +> If the middleware is piped before `RouteMiddleware`, no route is known yet and only the `*` headers are added. + +## Add configuration in autoload + +Create a new file `response-header.global.php` in `config/autoload` with the below configuration array: + +```php + [ + '*' => [ + 'CustomHeader1' => [ + 'value' => 'CustomHeader1-Value', + 'overwrite' => true, + ], + 'CustomHeader2' => [ + 'value' => 'CustomHeader2-Value', + 'overwrite' => false, + ], + ], + 'home' => [ + 'CustomHeader' => [ + 'value' => 'header3', + ], + ], + 'login' => [ + 'LoginHeader' => [ + 'value' => 'LoginHeader-Value', + 'overwrite' => false, + ], + ], + ], +]; +``` + +## Configuration keys + +| Key | Type | Default | Meaning | +| --- | --- | --- | --- | +| `dot_response_headers` | array | required | Route name (or `*`) to headers. An empty array is allowed and adds no headers | +| `.
.value` | string, int, float or a non-empty list of strings | none | Header value. Numbers are sent as strings; a list sends one header with several values. An entry without `value` is skipped | +| `.
.overwrite` | bool | `false` | Replace the header if the response already has it | + +## Invalid configuration + +The configuration is checked once, when the container creates the middleware. A wrong type throws `Dot\ResponseHeader\Exception\InvalidConfigException` with a message naming the key, for example: + +```text +dot_response_headers.*.X-Frame-Options.overwrite must be a bool, int given. +``` + +A missing `config` service or a missing `dot_response_headers` key also throws `InvalidConfigException`. diff --git a/docs/book/v4/installation.md b/docs/book/v4/installation.md new file mode 100644 index 0000000..0d6bf2c --- /dev/null +++ b/docs/book/v4/installation.md @@ -0,0 +1,9 @@ +# Installation + +Install dotkernel/dot-response-header by executing the following Composer command in your project directory: + +```shell +composer require dotkernel/dot-response-header:^4.0 +``` + +Upgrading from 3.x? Read [Upgrading to 4.x](upgrading.md) first. diff --git a/docs/book/v4/overview.md b/docs/book/v4/overview.md new file mode 100644 index 0000000..a839362 --- /dev/null +++ b/docs/book/v4/overview.md @@ -0,0 +1,19 @@ +# Overview + +`dot-response-header` is Dotkernel's middleware for setting and overwriting custom response headers. + +Headers are configured per route name, plus a `*` group that applies to every response. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-response-header) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/4.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/blob/4.0/LICENSE) + +[![Build Static](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-response-header/graph/badge.svg?token=NNRZN0FBF2)](https://codecov.io/gh/dotkernel/dot-response-header) +[![PHPStan](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml) diff --git a/docs/book/v4/upgrading.md b/docs/book/v4/upgrading.md new file mode 100644 index 0000000..b423a37 --- /dev/null +++ b/docs/book/v4/upgrading.md @@ -0,0 +1,28 @@ +# Upgrading to 4.x + +`dot-response-header` 4.x keeps the 3.x configuration format. A valid 3.x configuration sends the same headers in 4.x. Most applications only need to bump the version constraint. + +```shell +composer require dotkernel/dot-response-header:^4.0 +``` + +## Changes that can break your code + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 support dropped | Composer refuses to install | Upgrade to PHP 8.3 or newer | +| `overwrite` must be a `bool` | `InvalidConfigException: dot_response_headers..
.overwrite must be a bool, int given.` | Use `true` or `false`. In 3.x, `1` or `'true'` were silently treated as `false` | +| Route and header entries must be arrays | `InvalidConfigException` naming the key | In 3.x a string route entry was ignored with a PHP warning, and a string header entry threw a `TypeError` on every request | +| `value` must be a string, a number or a non-empty list of strings | `InvalidConfigException` naming the key | In 3.x `null` threw from the PSR-7 implementation on every request | +| The factory throws `Dot\ResponseHeader\Exception\InvalidConfigException` instead of `Exception` | Code that catches `Exception` still works; code that compares the exact class does not | Catch `InvalidArgumentException` or `InvalidConfigException` | +| `ConfigProvider` and `ResponseHeaderMiddlewareFactory` are `final` | `Class ... cannot extend final class` | Decorate them or write your own factory. `ResponseHeaderMiddleware` is not `final` | + +## Changes in behaviour + +| Change | Effect | What to do | +| --- | --- | --- | +| Configuration is checked when the middleware is created | Errors appear once, with the key in the message, instead of on each request | Nothing | +| `'dot_response_headers' => []` is allowed | In 3.x it threw `Unable to find dot-response-header config.`; now no headers are added | Nothing | +| A `config` service that implements `ArrayAccess` is accepted | In 3.x it threw a `TypeError` | Nothing | +| Numeric values are sent as strings | `3600` becomes `"3600"`, as before with Laminas Diactoros | Nothing | +| `mezzio/mezzio-router` 4.x is allowed | PHP 8.6 installs router 4.3 or newer | Nothing | diff --git a/docs/book/v4/usage.md b/docs/book/v4/usage.md new file mode 100644 index 0000000..73e7df4 --- /dev/null +++ b/docs/book/v4/usage.md @@ -0,0 +1,69 @@ +# Usage + +Because headers are matched with route names, we can have custom response headers for every request, by defining new headers under the `*` key, in the configuration file `response-header.global.php`. + +All headers under `*` will be set for every response, including 404 and 405 responses. + +To add response headers for a specific route, define a new array using the route name as the array key. The key must be the exact route name; it is not a pattern. + +## Example + +```php +'dot_response_headers' => [ + 'user' => [ + 'UserCustomHeader' => [ + 'value' => 'UserCustomHeader-Value', + 'overwrite' => false, + ], + ], +], + +// This will set a new header named UserCustomHeader with the UserCustomHeader-Value value for the route named 'user' +``` + +## Overwriting headers + +Headers are applied in this order: + +1. The response returned by the handler. +2. The `*` headers. +3. The headers of the matched route. + +A header that already exists is only replaced when its entry has `'overwrite' => true`. This also applies between steps 2 and 3: a route header replaces a `*` header with the same name only when it sets `'overwrite' => true`. + +```php +'dot_response_headers' => [ + '*' => [ + 'Cache-Control' => [ + 'value' => 'no-store', + ], + ], + 'image' => [ + 'Cache-Control' => [ + 'value' => 'public, max-age=86400', + 'overwrite' => true, + ], + ], +], + +// The 'image' route gets "Cache-Control: public, max-age=86400", every other route gets "Cache-Control: no-store" +``` + +Header names are case-insensitive, so `x-custom` set by a handler counts as an existing `X-Custom` header. + +## Header values + +A value can be a string, a number or a list of strings: + +```php +'dot_response_headers' => [ + '*' => [ + 'Access-Control-Max-Age' => [ + 'value' => 3600, + ], + 'Vary' => [ + 'value' => ['Accept', 'Origin'], + ], + ], +], +``` diff --git a/mkdocs.yml b/mkdocs.yml index 346f66c..485fe96 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,11 +2,18 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v3 + current_version: v4 versions: + - v4 - v3 nav: - Home: index.md + - v4: + - Overview: v4/overview.md + - Installation: v4/installation.md + - Configuration: v4/configuration.md + - Usage: v4/usage.md + - Upgrading: v4/upgrading.md - v3: - Overview: v3/overview.md - Installation: v3/installation.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index cf5ba32..85a997a 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,14 +1,28 @@ - + - - ./test + + test - - + - ./src + src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index aa45e00..f36a711 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -7,8 +7,11 @@ use Dot\ResponseHeader\Factory\ResponseHeaderMiddlewareFactory; use Dot\ResponseHeader\Middleware\ResponseHeaderMiddleware; -class ConfigProvider +final class ConfigProvider { + /** + * @return array{dependencies: array{factories: array}} + */ public function __invoke(): array { return [ @@ -16,6 +19,9 @@ public function __invoke(): array ]; } + /** + * @return array{factories: array} + */ public function getDependencies(): array { return [ diff --git a/src/Exception/InvalidConfigException.php b/src/Exception/InvalidConfigException.php new file mode 100644 index 0000000..f0cbfdd --- /dev/null +++ b/src/Exception/InvalidConfigException.php @@ -0,0 +1,52 @@ +has('config')) { - throw new Exception(self::MESSAGE_MISSING_CONFIG); + throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); } + $config = $container->get('config'); + if (! is_array($config) && ! $config instanceof ArrayAccess) { + throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); + } - if ( - ! array_key_exists('dot_response_headers', $config) - || ! is_array($config['dot_response_headers']) - || empty($config['dot_response_headers']) - ) { - throw new Exception(self::MESSAGE_MISSING_PACKAGE_CONFIG); + $headers = $config['dot_response_headers'] ?? null; + if (! is_array($headers)) { + throw new InvalidConfigException(self::MESSAGE_MISSING_PACKAGE_CONFIG); } - return new ResponseHeaderMiddleware($container->get('config')['dot_response_headers'] ?? []); + return new ResponseHeaderMiddleware($headers); } } diff --git a/src/Middleware/ResponseHeaderMiddleware.php b/src/Middleware/ResponseHeaderMiddleware.php index 3f3d6ca..3edafc6 100644 --- a/src/Middleware/ResponseHeaderMiddleware.php +++ b/src/Middleware/ResponseHeaderMiddleware.php @@ -4,56 +4,132 @@ namespace Dot\ResponseHeader\Middleware; +use Dot\ResponseHeader\Exception\InvalidConfigException; use Mezzio\Router\RouteResult; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +use function array_is_list; use function array_key_exists; +use function is_array; +use function is_bool; +use function is_float; +use function is_int; +use function is_string; +/** + * @phpstan-type HeaderConfig array{value: string|non-empty-list, overwrite: bool} + * @phpstan-type ResponseHeadersConfig array> + */ class ResponseHeaderMiddleware implements MiddlewareInterface { private const ALL_ROUTES = '*'; - private array $config; + /** @var ResponseHeadersConfig */ + private readonly array $config; + /** + * @param array $config + * @throws InvalidConfigException + */ public function __construct(array $config) { - $this->config = $config; + $this->config = self::normalize($config); } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = $handler->handle($request); - if (empty($this->config)) { + if ($this->config === []) { return $response; } $response = $this->addHeaders($response, self::ALL_ROUTES); $routeResult = $request->getAttribute(RouteResult::class); - if ($routeResult instanceof RouteResult && $routeResult->isSuccess()) { - $response = $this->addHeaders($response, $routeResult->getMatchedRouteName()); + if (! $routeResult instanceof RouteResult) { + return $response; } - return $response; + + $routeName = $routeResult->getMatchedRouteName(); + if ($routeName === false) { + return $response; + } + + return $this->addHeaders($response, $routeName); } public function addHeaders(ResponseInterface $response, string $route): ResponseInterface { - if (array_key_exists($route, $this->config)) { - foreach ($this->config[$route] as $header => $data) { + foreach ($this->config[$route] ?? [] as $header => $data) { + if ($response->hasHeader($header) && ! $data['overwrite']) { + continue; + } + $response = $response->withHeader($header, $data['value']); + } + + return $response; + } + + /** + * @param array $config + * @return ResponseHeadersConfig + * @throws InvalidConfigException + */ + private static function normalize(array $config): array + { + $normalized = []; + foreach ($config as $route => $headers) { + if (! is_array($headers)) { + throw InvalidConfigException::routeNotArray($route, $headers); + } + foreach ($headers as $header => $data) { + if (! is_array($data)) { + throw InvalidConfigException::headerNotArray($route, $header, $data); + } if (! array_key_exists('value', $data)) { continue; } - $addHeader = true; - if ($response->hasHeader($header)) { - $addHeader = isset($data['overwrite']) && $data['overwrite'] === true; - } - if ($addHeader === true) { - $response = $response->withHeader($header, $data['value']); + $overwrite = $data['overwrite'] ?? false; + if (! is_bool($overwrite)) { + throw InvalidConfigException::invalidOverwrite($route, $header, $overwrite); } + + $normalized[(string) $route][(string) $header] = [ + 'value' => self::normalizeValue($route, $header, $data['value']), + 'overwrite' => $overwrite, + ]; } } - return $response; + + return $normalized; + } + + /** + * @return string|non-empty-list + * @throws InvalidConfigException + */ + private static function normalizeValue(int|string $route, int|string $header, mixed $value): string|array + { + if (is_string($value)) { + return $value; + } + if (is_int($value) || is_float($value)) { + return (string) $value; + } + if (! is_array($value) || $value === [] || ! array_is_list($value)) { + throw InvalidConfigException::invalidValue($route, $header, $value); + } + + $values = []; + foreach ($value as $item) { + if (! is_string($item)) { + throw InvalidConfigException::invalidValue($route, $header, $value); + } + $values[] = $item; + } + + return $values; } } diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index c0d57d4..480385d 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -5,28 +5,26 @@ namespace DotTest\ResponseHeader; use Dot\ResponseHeader\ConfigProvider; +use Dot\ResponseHeader\Factory\ResponseHeaderMiddlewareFactory; +use Dot\ResponseHeader\Middleware\ResponseHeaderMiddleware; use PHPUnit\Framework\TestCase; -class ConfigProviderTest extends TestCase +final class ConfigProviderTest extends TestCase { - private ConfigProvider $configProvider; - - public function setUp(): void - { - $this->configProvider = new ConfigProvider(); - } - - public function testInvoke(): void + public function testInvokeReturnsDependencies(): void { - $data = $this->configProvider->__invoke(); + $config = (new ConfigProvider())(); - $this->assertIsArray($data); + $this->assertSame(['dependencies' => (new ConfigProvider())->getDependencies()], $config); } - public function testGetDependencies(): void + public function testMiddlewareIsRegisteredWithItsFactory(): void { - $data = $this->configProvider->getDependencies(); + $dependencies = (new ConfigProvider())->getDependencies(); - $this->assertIsArray($data); + $this->assertSame( + [ResponseHeaderMiddleware::class => ResponseHeaderMiddlewareFactory::class], + $dependencies['factories'] + ); } } diff --git a/test/Factory/ResponseHeaderMiddlewareFactoryTest.php b/test/Factory/ResponseHeaderMiddlewareFactoryTest.php index 7995468..3a7c9be 100644 --- a/test/Factory/ResponseHeaderMiddlewareFactoryTest.php +++ b/test/Factory/ResponseHeaderMiddlewareFactoryTest.php @@ -4,57 +4,83 @@ namespace DotTest\ResponseHeader\Factory; +use ArrayObject; +use Dot\ResponseHeader\Exception\InvalidConfigException; use Dot\ResponseHeader\Factory\ResponseHeaderMiddlewareFactory; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\ResponseHeader\Fixture\ArrayContainer; +use DotTest\ResponseHeader\Fixture\FixedResponseHandler; +use Laminas\Diactoros\ServerRequest; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; -class ResponseHeaderMiddlewareFactoryTest extends TestCase +final class ResponseHeaderMiddlewareFactoryTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateApplicationWithoutConfig(): void + public function testThrowsWhenConfigServiceIsMissing(): void { - $container = $this->createMock(ContainerInterface::class); + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_CONFIG); - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); + (new ResponseHeaderMiddlewareFactory())(new ArrayContainer()); + } - $this->expectException(\Exception::class); + public function testThrowsWhenConfigServiceIsNotAnArray(): void + { + $this->expectException(InvalidConfigException::class); $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_CONFIG); - (new ResponseHeaderMiddlewareFactory())($container); + + (new ResponseHeaderMiddlewareFactory())(new ArrayContainer(['config' => null])); } /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface + * @return iterable}> */ - public function testWillNotCreateApplicationWithoutPackageConfig(): void + public static function missingPackageConfigProvider(): iterable { - $container = $this->createMock(ContainerInterface::class); + yield 'key missing' => [['other' => []]]; + yield 'key is a string' => [['dot_response_headers' => 'X-Header']]; + yield 'key is null' => [['dot_response_headers' => null]]; + } - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); + /** + * @param array $config + */ + #[DataProvider('missingPackageConfigProvider')] + public function testThrowsWhenPackageConfigIsMissing(array $config): void + { + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_PACKAGE_CONFIG); - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn([ - 'test', - ]); + (new ResponseHeaderMiddlewareFactory())(new ArrayContainer(['config' => $config])); + } - $this->expectException(\Exception::class); - $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_PACKAGE_CONFIG); - (new ResponseHeaderMiddlewareFactory())($container); + public function testEmptyPackageConfigCreatesMiddlewareThatAddsNothing(): void + { + $middleware = (new ResponseHeaderMiddlewareFactory())( + new ArrayContainer(['config' => ['dot_response_headers' => []]]) + ); + + $response = $middleware->process(new ServerRequest(), new FixedResponseHandler()); + + $this->assertSame([], $response->getHeaders()); + } + + public function testAcceptsArrayAccessConfig(): void + { + $config = new ArrayObject(['dot_response_headers' => ['*' => ['X-All' => ['value' => 'all']]]]); + $middleware = (new ResponseHeaderMiddlewareFactory())(new ArrayContainer(['config' => $config])); + + $response = $middleware->process(new ServerRequest(), new FixedResponseHandler()); + + $this->assertSame('all', $response->getHeaderLine('X-All')); + } + + public function testInvalidPackageConfigFailsWhenTheMiddlewareIsCreated(): void + { + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage('dot_response_headers.* must be an array of headers, string given.'); + + (new ResponseHeaderMiddlewareFactory())( + new ArrayContainer(['config' => ['dot_response_headers' => ['*' => 'X-All']]]) + ); } } diff --git a/test/Fixture/ArrayContainer.php b/test/Fixture/ArrayContainer.php new file mode 100644 index 0000000..bfa608c --- /dev/null +++ b/test/Fixture/ArrayContainer.php @@ -0,0 +1,37 @@ + $services + */ + public function __construct( + private array $services = [], + ) { + } + + public function get(string $id): mixed + { + if (! $this->has($id)) { + throw new ServiceNotFoundException('Service not found: ' . $id); + } + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/Fixture/FixedResponseHandler.php b/test/Fixture/FixedResponseHandler.php new file mode 100644 index 0000000..0241a24 --- /dev/null +++ b/test/Fixture/FixedResponseHandler.php @@ -0,0 +1,35 @@ + $headers + */ + public function __construct(array $headers = []) + { + $response = new Response(); + foreach ($headers as $name => $value) { + $response = $response->withHeader($name, $value); + } + $this->response = $response; + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return $this->response; + } +} diff --git a/test/Fixture/ServiceNotFoundException.php b/test/Fixture/ServiceNotFoundException.php new file mode 100644 index 0000000..d00bc33 --- /dev/null +++ b/test/Fixture/ServiceNotFoundException.php @@ -0,0 +1,12 @@ + [ + 'X-All' => ['value' => 'all', 'overwrite' => false], + 'X-Overwrite' => ['value' => 'all', 'overwrite' => true], + ], + 'home' => [ + 'X-Home' => ['value' => 'home'], + 'X-All' => ['value' => 'home', 'overwrite' => true], + 'X-Overwrite' => ['value' => 'home', 'overwrite' => false], + ], + ]; + + public function testEmptyConfigReturnsTheHandlerResponseUnchanged(): void { - $this->responseHeader = new ResponseHeaderMiddleware([]); - $this->serverRequest = $this->createMock(ServerRequestInterface::class); - $this->requestHandler = $this->createMock(RequestHandlerInterface::class); + $handler = new FixedResponseHandler(['X-Existing' => 'kept']); + $response = (new ResponseHeaderMiddleware([]))->process(new ServerRequest(), $handler); + + $this->assertSame($handler->handle(new ServerRequest()), $response); } - public function testProcess(): void + public function testWithoutRouteResultOnlyCommonHeadersAreAdded(): void { - $data = $this->responseHeader->process($this->serverRequest, $this->requestHandler); + $response = (new ResponseHeaderMiddleware(self::CONFIG)) + ->process(new ServerRequest(), new FixedResponseHandler()); - $this->assertContainsOnlyInstancesOf(ResponseInterface::class, [$data]); + $this->assertSame(['X-All' => ['all'], 'X-Overwrite' => ['all']], $response->getHeaders()); } - public function testWillNotAddHeadersWithoutCommonWithoutRouteSpecificHeadersConfigured(): void + public function testRouteFailureOnlyAddsCommonHeaders(): void { - $responseHeader = new ResponseHeaderMiddleware([]); + $request = (new ServerRequest())->withAttribute(RouteResult::class, RouteResult::fromRouteFailure(null)); + $response = (new ResponseHeaderMiddleware(self::CONFIG))->process($request, new FixedResponseHandler()); - $response = new Response(); - $response = $responseHeader->addHeaders($response, 'test'); + $this->assertSame(['X-All' => ['all'], 'X-Overwrite' => ['all']], $response->getHeaders()); + } - $this->assertEmpty($response->getHeaders()); + public function testMatchedRouteAddsRouteHeadersAfterCommonHeaders(): void + { + $response = (new ResponseHeaderMiddleware(self::CONFIG)) + ->process($this->requestForRoute('home'), new FixedResponseHandler()); + + $this->assertSame('home', $response->getHeaderLine('X-Home')); + $this->assertSame('home', $response->getHeaderLine('X-All'), 'route header with overwrite replaces *'); + $this->assertSame('all', $response->getHeaderLine('X-Overwrite'), 'route header without overwrite keeps *'); } - public function testWillAddHeadersWithCommonWithoutRouteSpecificHeadersConfigured(): void + public function testRouteWithoutConfigOnlyAddsCommonHeaders(): void { - $config = [ - '*' => [ - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Value', - 'overwrite' => false, - ], - ], - ]; - $responseHeader = new ResponseHeaderMiddleware($config); + $response = (new ResponseHeaderMiddleware(self::CONFIG)) + ->process($this->requestForRoute('login'), new FixedResponseHandler()); - $response = new Response(); + $this->assertSame(['X-All' => ['all'], 'X-Overwrite' => ['all']], $response->getHeaders()); + } - $response = $responseHeader->addHeaders($response, 'test'); - $this->assertEmpty($response->getHeaders()); - $this->assertFalse($response->hasHeader('CustomHeader1')); - $this->assertFalse($response->hasHeader('CustomHeader2')); + public function testHeaderSetByTheHandlerIsKeptUnlessOverwriteIsTrue(): void + { + $handler = new FixedResponseHandler(['x-all' => 'handler', 'x-overwrite' => 'handler']); + $response = (new ResponseHeaderMiddleware(self::CONFIG))->process(new ServerRequest(), $handler); - $response = $responseHeader->addHeaders($response, '*'); - $this->assertCount(2, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['*']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); + $this->assertSame('handler', $response->getHeaderLine('X-All')); + $this->assertSame('all', $response->getHeaderLine('X-Overwrite')); } - public function testWillAddHeadersWithCommonWithRouteSpecificHeadersConfiguredWhenNoRouteMatched(): void + public function testHeaderWithoutValueIsSkipped(): void { - $config = [ - '*' => [ - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Value', - 'overwrite' => false, - ], - ], - 'home' => [ - 'CustomHeader' => [ - 'value' => 'header3', - ], - ], - ]; - $responseHeader = new ResponseHeaderMiddleware($config); + $response = (new ResponseHeaderMiddleware(['*' => ['X-Empty' => ['overwrite' => true]]])) + ->process(new ServerRequest(), new FixedResponseHandler()); - $response = new Response(); + $this->assertFalse($response->hasHeader('X-Empty')); + } - $response = $responseHeader->addHeaders($response, 'test'); - $this->assertFalse($response->hasHeader('CustomHeader')); - $this->assertEmpty($response->getHeaders()); + /** + * @return iterable}> + */ + public static function validValueProvider(): iterable + { + yield 'string' => ['text', ['text']]; + yield 'int' => [3600, ['3600']]; + yield 'float' => [1.5, ['1.5']]; + yield 'list of strings' => [['Accept', 'Origin'], ['Accept', 'Origin']]; + } + + /** + * @param list $expected + */ + #[DataProvider('validValueProvider')] + public function testAcceptedValueTypes(mixed $value, array $expected): void + { + $response = (new ResponseHeaderMiddleware(['*' => ['X-Value' => ['value' => $value]]])) + ->addHeaders(new Response(), '*'); - $response = $responseHeader->addHeaders($response, '*'); - $this->assertCount(2, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['*']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); + $this->assertSame($expected, $response->getHeader('X-Value')); } - public function testWillAddHeadersWithCommonWithRouteSpecificHeadersConfiguredWhenRouteMatched(): void + /** + * @return iterable, string}> + */ + public static function invalidConfigProvider(): iterable { - $config = [ - '*' => [ - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Value', - 'overwrite' => true, - ], - ], - 'home' => [ - 'CustomHeader' => [ - 'value' => 'header3', - ], - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Overwritten-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Overwritten-Value', - 'overwrite' => false, - ], - ], + yield 'route is a string' => [ + ['*' => 'X-All'], + 'dot_response_headers.* must be an array of headers, string given.', + ]; + yield 'header is a string' => [ + ['home' => ['X-Home' => 'home']], + 'dot_response_headers.home.X-Home must be an array with a "value" key, string given.', + ]; + yield 'value is null' => [ + ['*' => ['X-All' => ['value' => null]]], + 'dot_response_headers.*.X-All.value must be a string, a number or a list of strings, null given.', + ]; + yield 'value is an empty array' => [ + ['*' => ['X-All' => ['value' => []]]], + 'dot_response_headers.*.X-All.value must be a string, a number or a list of strings, array given.', + ]; + yield 'value list holds a non-string' => [ + ['*' => ['X-All' => ['value' => ['a', 1]]]], + 'dot_response_headers.*.X-All.value must be a string, a number or a list of strings, array given.', + ]; + yield 'overwrite is an int' => [ + ['*' => ['X-All' => ['value' => 'a', 'overwrite' => 1]]], + 'dot_response_headers.*.X-All.overwrite must be a bool, int given.', ]; - $responseHeader = new ResponseHeaderMiddleware($config); - - $response = new Response(); - - $this->assertFalse($response->hasHeader('CustomHeader1')); - $this->assertFalse($response->hasHeader('CustomHeader2')); - $this->assertFalse($response->hasHeader('CustomHeader')); - $this->assertEmpty($response->getHeaders()); - - $response = $responseHeader->addHeaders($response, '*'); - $this->assertCount(2, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['*']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); - - $response = $responseHeader->addHeaders($response, 'home'); - $this->assertCount(3, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader')); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['home']['CustomHeader']['value'], $response->getHeaderLine('CustomHeader')); - $this->assertSame($config['home']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); - $this->assertNotSame($config['home']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); + } + + /** + * @param array $config + */ + #[DataProvider('invalidConfigProvider')] + public function testInvalidConfigIsRejectedOnConstruction(array $config, string $message): void + { + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage($message); + + new ResponseHeaderMiddleware($config); + } + + private function requestForRoute(string $name): ServerRequestInterface + { + $middleware = new class implements MiddlewareInterface { + public function process( + ServerRequestInterface $request, + RequestHandlerInterface $handler + ): ResponseInterface { + return $handler->handle($request); + } + }; + + return (new ServerRequest())->withAttribute( + RouteResult::class, + RouteResult::fromRoute(new Route('/' . $name, $middleware, ['GET'], $name)) + ); } } From 0cf561189ba5d2238e12955cbd466bc72ca9563b Mon Sep 17 00:00:00 2001 From: bidi Date: Thu, 12 Nov 2026 16:47:46 +0200 Subject: [PATCH 2/3] updated based on review Signed-off-by: bidi --- .claude/hooks/guard-bash.sh | 246 ------- .claude/hooks/guard-protected-paths.sh | 57 -- .claude/hooks/markdown-lint.sh | 49 -- .claude/hooks/normalize-file.sh | 91 --- .claude/hooks/php-lint.sh | 35 - .claude/hooks/session-start.sh | 89 --- .claude/plan-code-review.md | 767 --------------------- .claude/skills/plan-major-upgrade/SKILL.md | 102 --- .laminas-ci.json | 2 +- 9 files changed, 1 insertion(+), 1437 deletions(-) delete mode 100644 .claude/hooks/guard-bash.sh delete mode 100644 .claude/hooks/guard-protected-paths.sh delete mode 100644 .claude/hooks/markdown-lint.sh delete mode 100644 .claude/hooks/normalize-file.sh delete mode 100644 .claude/hooks/php-lint.sh delete mode 100644 .claude/hooks/session-start.sh delete mode 100644 .claude/plan-code-review.md delete mode 100644 .claude/skills/plan-major-upgrade/SKILL.md diff --git a/.claude/hooks/guard-bash.sh b/.claude/hooks/guard-bash.sh deleted file mode 100644 index e84159b..0000000 --- a/.claude/hooks/guard-bash.sh +++ /dev/null @@ -1,246 +0,0 @@ -#!/usr/bin/env bash -# PreToolUse guard for Bash commands in Dotkernel projects. -# Catches installs and destructive git even when hidden inside compound commands -# ("cd x && composer require y"), which path-based permission rules cannot see. -# Quoted arguments, comments and heredoc bodies are data and are not matched, so -# grep "rm -rf" docs/ is allowed. Quoted code is still checked: the script after a -c -# option (sh -c "..."), the arguments of eval, ssh and watch, and a heredoc or -# here-string fed to a shell. -# This matches text, not a parsed shell: an unusual spelling can still get past it. -# bash, sed and awk; jq is used for the payload when installed. -# Exit 0 = allow, exit 2 = block. - -set -u -export LC_ALL=C - -payload=$(cat) - -# Print tool_input.command with its JSON escapes decoded. -extract_command() { - if command -v jq >/dev/null 2>&1 \ - && printf '%s' "$payload" | jq -r '.tool_input.command // empty' 2>/dev/null; then - return - fi - # No jq: park the two escapes that can hide a quote (\\ and \") on control bytes, - # which valid JSON never contains raw, so [^"]* ends exactly at the closing quote. - local bs='\' sl='/' esc_bs=$'\002' esc_q=$'\001' s - s=$(printf '%s' "$payload" | tr -d '\n' | sed -n \ - -e 's/\\\\/'"$esc_bs"'/g' \ - -e 's/\\"/'"$esc_q"'/g' \ - -e 's/.*"command"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') - s=${s//"${bs}n"/$'\n'} - s=${s//"${bs}t"/$'\t'} - s=${s//"${bs}r"/$'\r'} - s=${s//"$bs$sl"/$sl} - s=${s//"$esc_q"/\"} - s=${s//"$esc_bs"/$bs} - printf '%s' "$s" -} - -cmd=$(extract_command) -[ -z "$cmd" ] && exit 0 - -# Reduce the command to the text that would run. Quoted strings, comments and heredoc -# bodies become the placeholder Q, and ; & | ( ) ` and newlines become separate words. -# Code inside quotes or a heredoc (the script after a -c option, the arguments of eval, -# ssh or watch, a heredoc or here-string fed to a shell) is reduced the same way and -# appended after a " ; ". An unterminated quote leaves the rest of the command unmasked. -IFS= read -r -d '' SHELL_VIEW <<'AWK' || true -{ src = (NR == 1) ? $0 : src "\n" $0 } -END { printf "%s", scan(src, 0) } - -# out: the reduced command; seg0: where the current simple command starts in out; -# ws: the next character starts a word (so # opens a comment). -function scan(s, depth, n, i, c, j, out, seg0, ws, extra, body, q, seg, code, strip, - d, nd, hd, hs, hf, h, lines, nl, ln, pos, found, cmp, start) { - n = length(s); i = 1; out = ""; seg0 = 1; ws = 1; extra = ""; nd = 0 - while (i <= n) { - if (match(substr(s, i, 512), /^[^\\'"$#<;&|()`\n]+/)) { # ordinary text, in runs - out = out substr(s, i, RLENGTH); i += RLENGTH - ws = (substr(out, length(out), 1) ~ /[ \t]/); continue - } - c = substr(s, i, 1) - - if (c == "\\") { # escaped character, or line continuation - if (substr(s, i + 1, 1) != "\n") { out = out substr(s, i + 1, 1); ws = 0 } - i += 2; continue - } - - if (c == "'" || c == "\"" || (c == "$" && substr(s, i + 1, 1) == "'")) { - q = c; j = i + 1 - if (c == "$") { q = "'"; j = i + 2 } - if (c == "'") { - j = index(substr(s, j), "'"); if (j) j += i - } else { # "..." and $'...' honour backslash escapes - while (j <= n && substr(s, j, 1) != q) j += (substr(s, j, 1) == "\\") ? 2 : 1 - if (j > n) j = 0 - } - if (!j) { out = out substr(s, i); break } - body = substr(s, i + 1, j - i - 1) - seg = substr(out, seg0); code = 0 - if (seg ~ /(^|[ \t])-[a-z]*c[ \t]*$/ || seg ~ /(^|[ \t\/])(eval|ssh|watch)[ \t]/) code = 1 - else if (sub(/<<<[ \t]*$/, "", seg)) code = feeds_shell(seg) - if (code && c != "$") extra = extra " ; " nested((c == "\"") ? undq(body) : body, depth) - out = out "Q"; i = j + 1; ws = 0; continue - } - - if (c == "#" && ws) { # comment, up to the end of the line - j = index(substr(s, i), "\n") - if (!j) break - i += j - 1; continue - } - - if (c == "<" && substr(s, i, 3) == "<<<") { out = out "<<<"; i += 3; ws = 1; continue } - if (c == "<" && substr(s, i, 2) == "<<") { # heredoc - j = i + 2; strip = 0 - if (substr(s, j, 1) == "-") { strip = 1; j++ } - while (substr(s, j, 1) == " " || substr(s, j, 1) == "\t") j++ - d = ""; q = substr(s, j, 1) - if (q == "'" || q == "\"") { - c = index(substr(s, j + 1), q) - if (c) { d = substr(s, j + 1, c - 1); j += c + 1 } - } else { - while (j <= n && substr(s, j, 1) !~ /[ \t\n;&|()<>'"]/) { - if (substr(s, j, 1) == "\\") j++ - d = d substr(s, j, 1); j++ - } - } - if (d == "") { out = out "<<"; i += 2; ws = 1; continue } - nd++; hd[nd] = d; hs[nd] = strip; hf[nd] = feeds_shell(substr(out, seg0)) - out = out " << Q "; i = j; ws = 0; continue - } - - if (c == "\n") { - out = out " ; "; seg0 = length(out) + 1; ws = 1; i++ - if (nd) { # bodies of the heredocs opened on that line - nl = split(substr(s, i), lines, "\n"); ln = 1; pos = i - for (h = 1; h <= nd; h++) { - start = pos; found = 0 - for (; ln <= nl; ln++) { - cmp = lines[ln] - if (hs[h]) sub(/^\t+/, "", cmp) - if (cmp == hd[h]) { found = 1; break } - pos += length(lines[ln]) + 1 - } - if (!found) { pos = start; break } # no terminator: scan it as commands - if (hf[h]) extra = extra " ; " nested(substr(s, start, pos - start), depth) - pos += length(lines[ln]) + 1; ln++ - } - i = pos; nd = 0 - } - continue - } - - if (index(";&|()`", c)) { out = out " " c " "; seg0 = length(out) + 1; ws = 1; i++; continue } - out = out c; ws = 0; i++ - } - return out extra -} - -# The command so far ends with a shell that reads its script from stdin. -function feeds_shell(seg) { return seg ~ /(^|[ \t\/])(ba|z|da|k|a)?sh([ \t]+-[a-z]+)*[ \t]*$/ } - -function nested(s, depth) { return (depth < 4) ? scan(s, depth + 1) : s } - -function undq(s, r, i, n, c, nx) { # remove the escapes "..." honours - r = ""; n = length(s) - for (i = 1; i <= n; i++) { - c = substr(s, i, 1) - if (c == "\\" && i < n) { - nx = substr(s, i + 1, 1) - if (nx == "\n") { i++; continue } - if (index("\"\\$`", nx)) { r = r nx; i++; continue } - } - r = r c - } - return r -} -AWK - -lc=$(printf '%s' "$cmd" | tr '[:upper:]' '[:lower:]') -view=$(printf '%s' "$lc" | awk "$SHELL_VIEW") || view=$lc -norm=$(printf '%s' "$view" | tr '\t\r\n' ' ' | tr -s ' ') - -block() { - local shown=$cmd - [ ${#shown} -gt 500 ] && shown="${shown:0:500}..." - printf 'BLOCKED command: %s\n%s\n' "$shown" "$1" >&2 - exit 2 -} - -set -f -# shellcheck disable=SC2206 # word splitting is the point; globbing is off -words=($norm) -set +f -nw=${#words[@]} - -# composer [options] [global] . Composer resolves any unambiguous prefix of a -# command name (req, upd, inst, rem) and the aliases r, i, u, upgrade, rm, uninstall. -for ((i = 0; i < nw; i++)); do - case ${words[i]} in - composer|composer.phar|*/composer|*/composer.phar) ;; - *) continue ;; - esac - j=$((i + 1)) - while ((j < nw)); do - case ${words[j]} in - -d|--working-dir) j=$((j + 2)) ;; - -*) j=$((j + 1)) ;; - *) [[ global == "${words[j]}"* ]] && j=$((j + 1)) || break ;; - esac - done - sub=${words[j]:-} - [[ $sub =~ ^[a-z]+$ ]] || continue - for name in require remove update upgrade install uninstall rm; do - [[ $name == "$sub"* ]] \ - && block "Dependency changes need my explicit approval. Tell me the package and why, and I will run it." - done -done - -case " $norm " in - *"npm install"*|*"npm i "*|*"npm uninstall"*|*"npm update"*|*"npm ci"*|\ - *"yarn add"*|*"yarn remove"*|*"pnpm add"*|*"pnpm remove"*|*"pip install"*) - block "Package installs need my explicit approval." ;; -esac - -case " $norm " in - *"git push"*|*"git reset --hard"*|*"git clean -"*|*"git checkout -- "*|\ - *"git submodule"*|*"git filter-branch"*|*"git rebase"*) - block "Destructive or publishing git operations are mine to run." ;; -esac - -# rm with both a recursive and a force flag, in any spelling: -rf, -fr, -r -f, -Rf, -# --recursive --force. Its arguments end at a separator, at -- and at find's "{} +". -for ((i = 0; i < nw; i++)); do - case ${words[i]} in rm|*/rm) ;; *) continue ;; esac - rec=0 force=0 - for ((j = i + 1; j < nw; j++)); do - w=${words[j]} - case $w in - ';'|'&'|'|'|'('|')'|'`'|--|+) break ;; - --?*) [[ recursive == "${w#--}"* ]] && rec=1 - [[ force == "${w#--}"* ]] && force=1 ;; - -?*) [[ $w == *r* ]] && rec=1 - [[ $w == *f* ]] && force=1 ;; - esac - done - ((rec && force)) && block "Refusing destructive filesystem command." -done - -case " $norm " in - *"mkfs"*|*"chmod -r 777"*) - block "Refusing destructive filesystem command." ;; -esac - -case " $norm " in - *"doctrine-migrations migrate"*|*"doctrine-migrations execute"*|\ - *"fixtures:execute"*|*"schema:drop"*|*"schema:update"*) - block "Database-mutating commands need my approval. Show me the command and what it will change." ;; -esac - -case " $norm " in - *"development-enable"*|*"development-disable"*) - block "Toggling development mode changes committed config state. Ask me first." ;; -esac - -exit 0 diff --git a/.claude/hooks/guard-protected-paths.sh b/.claude/hooks/guard-protected-paths.sh deleted file mode 100644 index 6dcb4fa..0000000 --- a/.claude/hooks/guard-protected-paths.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -# PreToolUse guard for Dotkernel projects. -# Blocks writes to vendored, generated, secret or dependency-manifest files. -# Pure bash, no jq — works in Git Bash on Windows. -# Exit 0 = allow, exit 2 = block (stderr is shown to Claude). - -set -u - -payload=$(cat) - -# Pull the target path out of tool_input without a JSON parser: "file_path" for -# Edit, Write and MultiEdit, "notebook_path" for NotebookEdit. -path_field() { - printf '%s' "$payload" \ - | tr -d '\n' \ - | sed -n 's/.*"'"$1"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' -} -raw_path=$(path_field file_path) -[ -z "$raw_path" ] && raw_path=$(path_field notebook_path) - -[ -z "$raw_path" ] && exit 0 - -# Normalise: unescape JSON backslashes, turn \ into /, drop a drive prefix, lowercase. -path=${raw_path//\\\\/\\} -path=${path//\\//} -path=${path#[A-Za-z]:} -lower=$(printf '%s' "$path" | tr '[:upper:]' '[:lower:]') - -block() { - printf 'BLOCKED: %s\n%s\n' "$raw_path" "$1" >&2 - exit 2 -} - -case "$lower" in - */vendor/*|vendor/*) - block "vendor/ is Composer-managed. Change the dependency or your own code instead." ;; - */node_modules/*|node_modules/*) - block "node_modules/ is npm-managed." ;; - */migration/*|*/migrations/*) - block "Migrations are generated. Adjust the entity and regenerate with 'doctrine-migrations diff'." ;; - */data/cache/*|*/data/lock/*|*/data/oauth/*|data/cache/*|data/lock/*|data/oauth/*) - block "data/ holds generated cache, locks and keys. Never hand-edit." ;; - */log/*|log/*) - block "log/ is runtime output." ;; - */public/uploads/*|public/uploads/*) - block "public/uploads/ is user-uploaded content." ;; - *composer.json|*composer.lock|*package.json|*package-lock.json|*yarn.lock|*pnpm-lock.yaml) - block "Dependency manifests require explicit user approval. Propose the change in chat first." ;; - *.local.php|*/local.php|local.php|*/local.test.php|local.test.php) - block "Local config holds environment secrets and is git-ignored. Edit the .dist template and let the user apply it." ;; - *.phpcs-cache|*.phpunit.result.cache|*/.git/*) - block "Tool cache / git internals." ;; - *.png|*.jpg|*.jpeg|*.gif|*.svg|*.ico|*.zip|*.phar|*.key|*.pem) - block "Binary or key material." ;; -esac - -exit 0 diff --git a/.claude/hooks/markdown-lint.sh b/.claude/hooks/markdown-lint.sh deleted file mode 100644 index 84f3c8c..0000000 --- a/.claude/hooks/markdown-lint.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash -# PostToolUse: markdownlint a .md file right after it is written. -# Report-only by design — it does NOT run --fix. Reformatting a file that Claude -# just wrote invalidates its in-memory copy and breaks the next targeted edit, -# so bulk fixing stays a deliberate end-of-task action. -# Exit 2 surfaces the violations to Claude immediately. -# Silent exit 0 when markdownlint-cli2 is not installed, so .claude/ stays -# drop-in with no npm requirement. - -set -u - -payload=$(cat) - -raw_path=$(printf '%s' "$payload" | tr -d '\n' \ - | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') - -[ -z "$raw_path" ] && exit 0 - -path=${raw_path//\\\\/\\} -path=${path//\\//} - -lower=$(printf '%s' "$path" | tr '[:upper:]' '[:lower:]') - -case "$lower" in - *.md|*.markdown) ;; - *) exit 0 ;; -esac -case "$lower" in - */vendor/*|*/node_modules/*|*/.git/*|*/data/*|*/log/*) exit 0 ;; -esac -[ -f "$path" ] || exit 0 - -config="${CLAUDE_PROJECT_DIR:-.}/.claude/markdownlint.jsonc" -[ -f "$config" ] || exit 0 - -bin="" -if [ -x ./node_modules/.bin/markdownlint-cli2 ]; then - bin=./node_modules/.bin/markdownlint-cli2 -elif command -v markdownlint-cli2 >/dev/null 2>&1; then - bin=markdownlint-cli2 -fi -[ -z "$bin" ] && exit 0 - -if ! output=$("$bin" --config "$config" "$path" 2>&1); then - printf 'markdownlint violations in %s\n%s\n' "$path" "$output" >&2 - exit 2 -fi - -exit 0 diff --git a/.claude/hooks/normalize-file.sh b/.claude/hooks/normalize-file.sh deleted file mode 100644 index e436548..0000000 --- a/.claude/hooks/normalize-file.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env bash -# PostToolUse normaliser for Dotkernel projects. -# Enforces: UTF-8 without BOM, LF line endings, no trailing whitespace, -# exactly one trailing newline. Pure bash + sed + awk, no jq. -# Rewrites the file in place, so its permissions, owner and links survive. -# Exit 0 always — this fixes silently rather than blocking. - -set -u - -payload=$(cat) - -raw_path=$(printf '%s' "$payload" | tr -d '\n' \ - | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') - -[ -z "$raw_path" ] && exit 0 - -path=${raw_path//\\\\/\\} -path=${path//\\//} - -[ -f "$path" ] || exit 0 - -lower=$(printf '%s' "$path" | tr '[:upper:]' '[:lower:]') - -# Skip binaries and anything not ours. -case "$lower" in - *.png|*.jpg|*.jpeg|*.gif|*.ico|*.svg|*.zip|*.phar|*.pdf|*.woff|*.woff2|*.ttf|*.eot|*.key|*.pem) - exit 0 ;; - */vendor/*|*/node_modules/*|*/.git/*|*/data/*|*/log/*) - exit 0 ;; -esac - -# Text files only. -case "$lower" in - *.php|*.phtml|*.twig|*.md|*.json|*.xml|*.neon|*.yml|*.yaml|*.sh|*.txt|*.dist|*.html|*.css|*.js|*.sql|*.editorconfig|*.gitattributes|*.gitignore) ;; - *) exit 0 ;; -esac - -changed="" -tmp=$(mktemp "${TMPDIR:-/tmp}/dk-normalize.XXXXXX") || exit 0 -trap 'rm -f "$tmp"' EXIT - -# Copy the fixed text back over the original. Writing through the existing file, rather -# than moving a new one into place, keeps its mode (an executable script stays -# executable), its owner, and any symlink or hard link to it. -write_back() { { cat "$tmp" > "$path"; } 2>/dev/null; } - -# 1. Strip UTF-8 BOM. -bom=$(printf '\357\273\277') -if [ "$(head -c 3 "$path" 2>/dev/null)" = "$bom" ]; then - tail -c +4 "$path" > "$tmp" && write_back && changed="${changed} BOM-removed" -fi - -# 2. CRLF -> LF, then a lone CR (classic Mac line ending) -> LF. -if LC_ALL=C grep -qU $'\r' "$path" 2>/dev/null; then - LC_ALL=C sed $'s/\r$//' "$path" | tr '\r' '\n' > "$tmp" && write_back \ - && changed="${changed} CRLF->LF" -fi - -# 3. Trailing whitespace (skip markdown: two trailing spaces are a hard line break). -case "$lower" in - *.md) ;; - *) - if LC_ALL=C grep -q '[[:space:]]$' "$path"; then - sed 's/[[:space:]]*$//' "$path" > "$tmp" && write_back \ - && changed="${changed} trailing-ws-stripped" - fi - ;; -esac - -# 4. Exactly one trailing newline: add a missing one, drop blank or whitespace-only lines -# at the end. A file with nothing but whitespace is left alone. -if [ -s "$path" ]; then - LC_ALL=C awk ' - /^[ \t\f\v]*$/ { held = held $0 "\n"; next } # blank: hold until a line follows - { printf "%s%s\n", held, $0; held = "" } # still held at the end: dropped - ' "$path" > "$tmp" - if [ -s "$tmp" ] && ! cmp -s "$tmp" "$path"; then - if [ "$(wc -c < "$tmp")" -gt "$(wc -c < "$path")" ]; then - fix=newline-added - else - fix=trailing-blank-lines-removed - fi - write_back && changed="${changed} ${fix}" - fi -fi - -if [ -n "$changed" ]; then - printf 'File hygiene applied to %s:%s\n' "$path" "$changed" >&2 -fi - -exit 0 diff --git a/.claude/hooks/php-lint.sh b/.claude/hooks/php-lint.sh deleted file mode 100644 index d902a12..0000000 --- a/.claude/hooks/php-lint.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# PostToolUse: syntax-check a PHP file right after it is written. -# Report-only by design — it does NOT reformat. Reformatting a file that Claude -# just wrote invalidates its in-memory copy and breaks the next targeted edit, -# so phpcbf is deliberately left to `composer cs-fix` / /dk-check at the end. -# Exit 2 surfaces the parse error to Claude immediately. - -set -u - -payload=$(cat) - -raw_path=$(printf '%s' "$payload" | tr -d '\n' \ - | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') - -[ -z "$raw_path" ] && exit 0 - -path=${raw_path//\\\\/\\} -path=${path//\\//} - -case "$path" in - *.php) ;; - *) exit 0 ;; -esac -case "$path" in - */vendor/*|*/node_modules/*) exit 0 ;; -esac -[ -f "$path" ] || exit 0 -command -v php >/dev/null 2>&1 || exit 0 - -if ! output=$(php -l "$path" 2>&1); then - printf 'PHP syntax error in %s\n%s\n' "$path" "$output" >&2 - exit 2 -fi - -exit 0 diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh deleted file mode 100644 index fbcf056..0000000 --- a/.claude/hooks/session-start.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bash -# SessionStart: print a short briefing that becomes part of Claude's context. -# Detects which Dotkernel project this is and what is not set up yet. -# Everything here is read-only. Keep the output compact. - -set -u -cd "${CLAUDE_PROJECT_DIR:-.}" 2>/dev/null || exit 0 - -echo "## Project state" - -# --- which Dotkernel project? --- -if [ -f composer.json ]; then - pkg=$(sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' composer.json | head -1) - ns=$(grep '": "src/' composer.json 2>/dev/null | grep -v '"Core' | head -1 \ - | sed 's/^[^"]*"\([A-Za-z]*\).*/\1/') - variant="unknown" - case "$pkg" in - */api) variant="API (REST/HAL)" ;; - */admin) variant="Admin (templated, forms)" ;; - */frontend) variant="Frontend (templated, forms)" ;; - */light) variant="Light (minimal starter)" ;; - */queue) variant="Queue (CLI/worker)" ;; - esac - if [ "$variant" = "unknown" ]; then - hal=0 form=0 - grep -q 'mezzio/mezzio-hal' composer.json && hal=1 - grep -q 'laminas/laminas-form' composer.json && form=1 - case "$hal$form" in - 10) variant="API-style (has mezzio-hal)" ;; - 01) variant="templated-style (has laminas-form)" ;; - 11) variant="unclear (has mezzio-hal and laminas-form; infer the parent from the PSR-4 roots)" ;; - esac - fi - echo "- package: ${pkg:-unknown} | variant: ${variant}" - [ -n "$ns" ] && echo "- root namespace: ${ns}" - guards=config/autoload/authorization-guards.global.php - if [ -f "$guards" ]; then - policy=$(sed -n "s/.*protection_policy.*\(POLICY_[A-Z]*\).*/\1/p" "$guards" | head -1) - echo "- authorization: guards + RBAC (${guards##*/}${policy:+, $policy})" - [ "$policy" = POLICY_ALLOW ] && echo " unlisted routes are PUBLIC — every new route needs a guard rule" - elif [ -f config/autoload/authorization.global.php ]; then - echo "- authorization: RBAC (authorization.global.php) — unlisted routes are denied" - fi -fi - -# --- git --- -# Ask git rather than test for a .git directory: in a worktree or a submodule checkout -# .git is a file. -if command -v git >/dev/null 2>&1 \ - && [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = true ]; then - eol_bad=$(git ls-files --eol 2>/dev/null | grep -c 'w/crlf' || true) - [ "${eol_bad:-0}" -gt 0 ] && echo "- WARNING: ${eol_bad} tracked file(s) have CRLF in the worktree; run /dk-hygiene" - top=$(git rev-parse --show-toplevel 2>/dev/null) - if [ -f "$top/.gitmodules" ]; then - subs=$(git config -f "$top/.gitmodules" --get-regexp '^submodule\..*\.path$' 2>/dev/null \ - | cut -d' ' -f2- | tr '\n' ' ') - subs=${subs% } - case " $subs " in - *" src/Core "*) echo "- git submodules: ${subs}. Core is one: commit inside src/Core, then bump the pointer here" ;; - " ") ;; - *) echo "- git submodules: ${subs}" ;; - esac - fi -fi - -# --- setup completeness --- -[ -f composer.json ] && [ ! -d vendor ] \ - && echo "- vendor/ missing — dependencies are not installed (run /dk-bootstrap)" - -for d in config/autoload/*.dist config/*.dist; do - [ -e "$d" ] || continue - target=${d%.dist} - [ -f "$target" ] && continue - case "$target" in - config/development.config.php) continue ;; # managed by development-mode, not copied by hand - esac - echo "- missing ${target} (copy from ${d})" -done - -for d in docs/features documentation/features; do - [ -d "$d" ] || continue - n=$(ls -1 "$d"/*.md 2>/dev/null | grep -vc '/README\.md$' || true) - echo "- ${d}/: ${n:-0} feature doc(s) — read the relevant one before adding behaviour there" -done - -[ -f config/development.config.php ] && echo "- development mode is ENABLED" -[ -f data/cache/config-cache.php ] && echo "- config cache present; clear it after config edits" - -exit 0 diff --git a/.claude/plan-code-review.md b/.claude/plan-code-review.md deleted file mode 100644 index d2096f2..0000000 --- a/.claude/plan-code-review.md +++ /dev/null @@ -1,767 +0,0 @@ -# Plan: dotkernel/dot-response-header 4.0.0 - -Plan for the next major release of `dotkernel/dot-response-header`, written on 2026-11-11 on the `upgrade` branch (cut from `3.0` at tag `3.6.0`). The target is `4.0.0`, supporting PHP 8.3 to 8.6, PHPUnit 12, PHPStan level 8, and `mezzio/mezzio-router` 3.x and 4.x. The work is on `upgrade` and will be merged into a new `4.0` branch after review. Re-checked on 2026-11-11 after the maintainer's `composer.json` edits and `composer update`, then implemented the same day (rollout steps 2 to 8). `composer check` passes. Nothing is committed. - -## Implementation status - -| Item | State | Notes | -| --- | --- | --- | -| V1 PHP range in `composer.json` | Done by the maintainer | `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.6.0`; `composer why-not php 8.6.0` and `8.3.0` find no blocker | -| V2 `phpunit/phpunit` to 12 | Done by the maintainer | `^12.5`; 12.5.43 installed | -| V3 Remaining `composer.json` edits | Done by the maintainer | Exactly as planned; `composer validate --strict` passes. Optional: router floor `^3.17` (see V3) | -| V4 Workflows and `.laminas-ci.json` | Done | Maintainer: versions and actions. Me: `codecov.yml` on 8.5 only; `static-analysis.yml` job id `static-analysis`, `coverage: none`. All 4 workflow files parse as YAML; not run in CI yet. `.laminas-ci.json` unchanged | -| V5 `phpstan.neon` level 8 | Done | Level 8 and `--level max` both clean in the repository, no ignores | -| V6 `phpunit.xml` and `.gitignore` | Done | Local schema, `failOn*` flags (confirmed: the 5 old notices made PHPUnit exit 1). `.gitignore` has `.phpunit.cache` and keeps `.phpunit.result.cache` for 3.x checkouts | -| F1 to F6 code fixes | Done | Code as in the findings; `src/Exception/InvalidConfigException.php` added | -| F7 to F9 tests | Done | 27 tests, 42 assertions; fixtures `ArrayContainer`, `ServiceNotFoundException`, `FixedResponseHandler`. 14 failed against the 3.6.0 `src/` before step 5 (7 errors, 7 failures). No mocks left | -| D1 docs `v4`, README, SECURITY, mkdocs | Done | New `docs/book/v4/` (overview, installation, configuration, usage, upgrading). All 10 nav targets exist; `mkdocs build` not run (not installed). Badges and the license link in README and `v4/overview.md` point at branch `4.0`; `v3/overview.md` keeps `3.0` | -| D2 CHANGELOG | Done | `3.0.0` to `4.0.0`, newest first, `3.0.1` date fixed to 2021-05-18; lint-clean | -| D3 Upgrade guide | Done | `docs/book/v4/upgrading.md`; the error message it quotes was produced at runtime | -| Release | Waiting for the maintainer | Review, merge `upgrade` into `4.0`, tag `4.0.0`, CHANGELOG date, re-enable the BC check after release | - -## Decision: version 4 - -- `4.0.0` is a major release because it drops PHP 8.2, and the recommended fixes (F2, F3, F5) change behaviour for misconfigured applications and make two classes `final`. -- Release lines in the repository: branches `3.0` (default), `upgrade` (this work) and `gh-pages`; tags `3.0.0` to `3.6.0`. There is no `4.x` branch and no parallel line, so 4.x is the direct successor of 3.x. No discontinued-line page is needed (T13 does not apply). -- The work is on `upgrade` and will be merged into `4.0` after review (decided by the maintainer on 2026-11-11). Badges and links that name a branch (`?branch=`, `blob//LICENSE`) in README and `v4/overview.md` use `4.0`; `v3/overview.md` keeps `3.0`. `3.0` stays for security fixes. -- After release, `3.0` should be marked "security fixes only" in `SECURITY.md` and the README. - -## Baseline - -Run on 2026-11-11, first in scratch (before `vendor/` existed), then re-run in the repository after the maintainer's `composer update`. - -| Check | Result | -| --- | --- | -| `git describe --tags` | `3.6.0` (HEAD is exactly the tag) | -| PHP available locally | 8.5.12 only. No pcov or Xdebug | -| Installed in the repository | PHPUnit 12.5.43, PHPStan 2.3.5, phpstan-phpunit 2.1.1, mezzio-router 4.3.0, diactoros 3.10.0, laminas-coding-standard 3.1.0, psr/container 2.0.2, psr/http-message 2.0, psr/http-server-handler 1.0.2, psr/http-server-middleware 1.0.2 | -| `composer validate --strict` | Valid | -| `composer check` in the repository | **Fails at PHPStan**: phpcs clean; PHPUnit 9 tests, 45 assertions, OK with 5 PHPUnit notices; PHPStan level 8 the same 7 errors as in V5. Identical to scratch A | -| `composer why-not php 8.6.0` / `8.3.0` | No installed package blocks either version | -| `composer show -l --direct` | All direct dependencies at their latest allowed version. PHPUnit 13.4.6 exists (requires PHP `>=8.4.1`), so 12 stays the right major while 8.3 is supported | -| Scratch runs (before `vendor/` existed) | Against two sibling `vendor/` directories (read-only symlinks) with a bootstrap that adds this package's PSR-4 namespaces; see below | -| Scratch A: `dot-errorhandler/vendor` | PHPUnit 12.5.43, PHPStan 2.3.5, phpstan-phpunit 2.1.1, mezzio-router **4.3.0**, diactoros 3.10.0, laminas-coding-standard 3.1.0 | -| Scratch B: `admin/vendor` | PHPUnit 12.5.38, PHPStan 2.2.17, mezzio-router **3.20.0**, diactoros 3.8.0, mezzio 3.x with FastRoute and laminas-servicemanager | -| phpcs | Clean (A) | -| PHPUnit 12, current tests | 9 tests, 45 assertions, OK **with 5 PHPUnit notices** (A and B): mock objects without expectations | -| PHPStan level 5 (old level) | Clean (B) | -| PHPStan level 8 | 7 errors (A and B), listed in V5 | -| Laminas BC check | Disabled by the maintainer (`backwardCompatibilityCheck: false`). Enabled, it would compare against `3.6.0` and report the intended breaks (F5 `final`, F2 validation). Re-enable after `4.0.0` is tagged so 4.x minors are checked against `4.0.0` | - -## Done by the maintainer - -Uncommitted edits found in the working tree: - -| File | Edit | Status | -| --- | --- | --- | -| `composer.json` | `php`: first `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.2.0`, corrected to `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.6.0` | Correct after the re-check | -| `composer.json` | `phpunit/phpunit`: `^10.2` to `^12.5` | Correct | -| `composer.json` | V3 edits: router `^3.16 \|\| ^4.0`, `psr/container`, `psr/http-server-handler`, `psr/http-server-middleware` added, `psr/http-client` removed, diactoros `^3.10` | Correct, matches the diff below | -| `phpstan.neon` | `level: 5` to `level: 8` | Correct | -| `codecov.yml`, `static-analysis.yml` | PHP matrix 8.3 to 8.6; `actions/checkout@v7`, `actions/cache@v6`, `codecov/codecov-action@v7` | Correct, see V4 for the rest | -| `.laminas-ci.json` | `ignore_php_platform_requirements` for 8.6; `backwardCompatibilityCheck: false` | Correct for the major | - -The `composer.json` edits that were requested (all applied by the maintainer and installed): - -```diff - "require": { -- "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.2.0", -- "mezzio/mezzio-router": "^3.16", -- "psr/http-client": "^1.0", -- "psr/http-message": "^1.0 || ^2.0" -+ "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", -+ "mezzio/mezzio-router": "^3.16 || ^4.0", -+ "psr/container": "^1.1 || ^2.0", -+ "psr/http-message": "^1.0 || ^2.0", -+ "psr/http-server-handler": "^1.0", -+ "psr/http-server-middleware": "^1.0" - }, - "require-dev": { - "laminas/laminas-coding-standard": "^3.0", -- "laminas/laminas-diactoros": "^3.1", -+ "laminas/laminas-diactoros": "^3.10", - "phpstan/phpstan": "^2.1", - "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^12.5" - }, -``` - -Optional follow-up (see V3): `"mezzio/mezzio-router": "^3.17 || ^4.0"`, because no `3.16.x` release can install on PHP 8.3 or newer. - -## Findings - -### V1. PHP range - -- Status: fixed by the maintainer on 2026-11-11; the "After" below is now in `composer.json`. -- Location: `composer.json:22`. -- Evidence (before the fix): the constraint read `~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.2.0`. 8.2 is still allowed and 8.6 is missing. PHPUnit 12 requires `php >=8.3` (read from `vendor/phpunit/phpunit/composer.json`), so a PHP 8.2 install cannot resolve dev dependencies. The custom workflows run 8.6, where `composer install` refuses the root package. Laminas CI builds its matrix from this constraint, so it never runs 8.6. - -Before: - -```json -"php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.2.0", -``` - -After: - -```json -"php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", -``` - -- Why: matches the agreed range (8.3 to 8.6), the workflows and PHPUnit 12. - -### V2. PHPUnit 12 (T5) - -- Done by the maintainer in `composer.json`. What the tests and config need: - - `phpunit.xml` schema points at 10.2 (V6). - - Annotations: none are used, so nothing to convert. New data providers must be `public static` and attached with `#[DataProvider]` (F8 does this). - - Mock rules: PHPUnit 12 raises a notice for a mock with no expectations. The current `ResponseHeaderMiddlewareTest::setUp()` creates two mocks for every test, which gives the 5 notices in the baseline. F8 replaces them with real objects and a fixture handler; `createStub()` would be the fallback. - - `PHPUnit\Framework\MockObject\Exception` in `@throws` tags disappears with the mocks. - - `failOn*` flags: V6. - -### V3. Undeclared and unused dependencies (T10, T11) - -Imports in `src/` (from `grep -rn "^use " src`) against `require`: - -| Package | Used in `src/` | Declared | Action | -| --- | --- | --- | --- | -| `mezzio/mezzio-router` | `RouteResult` (middleware) | `^3.16` | Widen to `^3.16 \|\| ^4.0` | -| `psr/container` | Factory | No (comes via `mezzio-router`) | Add `^1.1 \|\| ^2.0` | -| `psr/http-message` | Middleware | `^1.0 \|\| ^2.0` | Keep | -| `psr/http-server-middleware` | `MiddlewareInterface` | No | Add `^1.0` | -| `psr/http-server-handler` | `RequestHandlerInterface` | No | Add `^1.0` | -| `psr/http-client` | Nowhere in `src/` or `test/` | `^1.0` | Remove | - -- `mezzio-router` 4.x: `4.3.0` (read from `dot-errorhandler/vendor`) declares `php: ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0`; `3.20.0` (from `admin/vendor`) declares `~8.2.0 || ... || ~8.5.0`. So **PHP 8.6 needs router 4.x**. `RouteResult::getMatchedRouteName(): false|string` and `isSuccess()` are the same in both. The full suite and PHPStan pass against both (Baseline A and B). `mezzio/mezzio` 3.29.0 accepts `^3.15.0 || ^4.0.0`. -- Lowest installable router per PHP version, from Packagist metadata (`composer show --all mezzio/mezzio-router `): - -| PHP | Lowest router allowed by `^3.16 \|\| ^4.0` | Why | -| --- | --- | --- | -| 8.3 | 3.17.0 | 3.16.x declares `~8.1.0 \|\| ~8.2.0` only | -| 8.4 | 3.18.0 | | -| 8.5 | 3.19.0 | | -| 8.6 | 4.3.0 | No 3.x release and no 4.0 to 4.2 release declares 8.6 (4.0.x stops at 8.4, 4.1 and 4.2 at 8.5) | - -- So the `3.16` floor is unreachable on every supported PHP version. It does no harm (Composer filters by platform), but `^3.17 || ^4.0` states the real floor. Optional; not needed for correctness. -- Removal evaluation for `mezzio-router` (T11): it is needed for one class, `RouteResult`, which is how the middleware finds the matched route name. There is no PSR interface for a matched route. Options: (a) keep it, (b) read a configurable request attribute instead, which breaks every existing config and loses the type check. Recommendation: **keep it**; the package is Mezzio middleware by design. -- `laminas/laminas-diactoros` (dev): `3.10.0` declares 8.6; `3.8.0` and `3.9.0` stop at 8.5. Raise to `^3.10` so lowest-dependency CI on 8.6 does not need the platform override for it. -- `suggest` and `conflict`: none needed. -- `laminas/laminas-servicemanager` is not a runtime requirement, so T20 does not apply. - -### V4. Workflows (T4) - -Checked every file in `.github/workflows` and `.laminas-ci.json`. - -| File | State | Change | -| --- | --- | --- | -| `continuous-integration.yml` | Uses `laminas/workflow-continuous-integration@1.x` | None. Its matrix follows the `composer.json` PHP range (V1) | -| `docs-build.yml` | Uses `dotkernel/documentation-theme/...@main` | None | -| `codecov.yml` | Bumped by the maintainer | Run on one PHP version only | -| `static-analysis.yml` | Bumped by the maintainer | `coverage: none`; rename job id `mutation` | -| `.laminas-ci.json` | Edited by the maintainer | None now; re-enable BC check after `4.0.0` | - -`codecov.yml` uploads four coverage reports per push, and pcov for PHP 8.6 may not exist yet (unverified). - -Before (`codecov.yml`): - -```yaml - php: - - "8.3" - - "8.4" - - "8.5" - - "8.6" -``` - -After: - -```yaml - php: - - "8.5" -``` - -`static-analysis.yml` loads pcov although PHPStan never uses it, and the job id says `mutation`. - -Before: - -```yaml -jobs: - mutation: - name: PHPStan ${{ matrix.php }}-${{ matrix.os }} -... - coverage: pcov -``` - -After: - -```yaml -jobs: - static-analysis: - name: PHPStan ${{ matrix.php }}-${{ matrix.os }} -... - coverage: none -``` - -- Why: the 8.6 row in both custom workflows can install now that V1 is in. `composer why-not php 8.6.0` finds no blocker in the installed (latest) tree, so no `--ignore-platform-req` is needed for latest dependencies. -- `.laminas-ci.json` `ignore_php_platform_requirements` for 8.6: likely no longer needed for direct dependencies (router 4.3.0 and diactoros 3.10.0 both declare 8.6). Keep it until a CI run on lowest dependencies for 8.6 is green without it, then remove it. - -### V5. PHPStan level 8 (T3) - -Current level was 5 (clean). At level 8, identical on router 3.20 and 4.3: - -| # | Location | Identifier | Fix | -| --- | --- | --- | --- | -| 1 | `src/ConfigProvider.php:12` | `missingType.iterableValue` | Array shape `@return` (F6) | -| 2 | `src/ConfigProvider.php:19` | `missingType.iterableValue` | Array shape `@return` (F6) | -| 3 | `src/Middleware/ResponseHeaderMiddleware.php:19` | `missingType.iterableValue` | Typed config property (F2) | -| 4 | `src/Middleware/ResponseHeaderMiddleware.php:21` | `missingType.iterableValue` | `@param array`, normalised into the typed property (F2) | -| 5 | `src/Middleware/ResponseHeaderMiddleware.php:36` | `argument.type` (`string\|false` given) | Check `getMatchedRouteName() !== false` (F1) | -| 6 | `test/Middleware/ResponseHeaderMiddlewareTest.php:34` | `argument.type` (`MockObject\|ServerRequestInterface`) | Real `ServerRequest`, no mocks (F8) | -| 7 | `test/Middleware/ResponseHeaderMiddlewareTest.php:34` | `argument.type` (`MockObject\|RequestHandlerInterface`) | Fixture handler (F8) | - -No ignores, baseline, `assert()` or `@var` overrides are used. The prototype is clean at level 8 and at `max`. - -### V6. `phpunit.xml` and `.gitignore` (T5, T15) - -Before: - -```xml - - - - ./test - - - - - - ./src - - - -``` - -After (validated by PHPUnit 12.5.38 and 12.5.43 in scratch): - -```xml - - - - - test - - - - - src - - - -``` - -`.gitignore`: add `.phpunit.cache`; keep `.phpunit.result.cache`, which PHPUnit still writes on a 3.x checkout. - -- Why: the local schema follows the installed PHPUnit; the flags turn the 5 current notices (and any future deprecation) into failures. Deprecations raised inside vendor code on PHP 8.6 would also fail the build; if that happens, the fix is a dependency bump, or `` already limits deprecation reporting to `src`, so first-party code stays strict (unverified on 8.6). - -### F1. Matched route name is `false|string` - -- Severity: low (type safety; no runtime failure found). -- Location: `src/Middleware/ResponseHeaderMiddleware.php:35-36`. -- Evidence: PHPStan error V5 #5. `isSuccess()` makes it safe today, but the type is not narrowed. - -Before: - -```php -$routeResult = $request->getAttribute(RouteResult::class); -if ($routeResult instanceof RouteResult && $routeResult->isSuccess()) { - $response = $this->addHeaders($response, $routeResult->getMatchedRouteName()); -} -return $response; -``` - -After: - -```php -$routeResult = $request->getAttribute(RouteResult::class); -if (! $routeResult instanceof RouteResult) { - return $response; -} - -$routeName = $routeResult->getMatchedRouteName(); -if ($routeName === false) { - return $response; -} - -return $this->addHeaders($response, $routeName); -``` - -- Why: `getMatchedRouteName()` returns `false` exactly when the result is a failure in both router 3.20 and 4.3, so this is the same behaviour with a checked type. - -### F2. Invalid header config fails on every request, or is silently ignored - -- Severity: medium. -- Location: `src/Middleware/ResponseHeaderMiddleware.php:41-58`. -- Evidence (scratch script `repro.php`, same result on router 3.20 and 4.3): - -| Config | Result today | -| --- | --- | -| `'*' => 'oops'` (route not an array) | PHP warning `foreach() argument must be of type array\|object`, headers silently dropped | -| `'*' => ['X-A' => 'v']` (shorthand) | `TypeError: array_key_exists(): Argument #2 ($array) must be of type array, string given` on every request | -| `'value' => null` | `Laminas\Diactoros\Exception\InvalidArgumentException` on every request | -| `'overwrite' => 1` on an existing header | Silently treated as `false` | -| `'value' => 3600` | Works with Diactoros, but PSR-7 `withHeader()` only promises `string\|string[]` | - -The errors surface per request, inside the response, after the handler already ran, and the message never names the config key. - -Before: - -```php -private array $config; - -public function __construct(array $config) -{ - $this->config = $config; -} -``` - -After (full class, verified): - -```php -/** - * @phpstan-type HeaderConfig array{value: string|non-empty-list, overwrite: bool} - * @phpstan-type ResponseHeadersConfig array> - */ -class ResponseHeaderMiddleware implements MiddlewareInterface -{ - private const ALL_ROUTES = '*'; - - /** @var ResponseHeadersConfig */ - private readonly array $config; - - /** - * @param array $config - * @throws InvalidConfigException - */ - public function __construct(array $config) - { - $this->config = self::normalize($config); - } - - public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface - { - // as in F1 - } - - public function addHeaders(ResponseInterface $response, string $route): ResponseInterface - { - foreach ($this->config[$route] ?? [] as $header => $data) { - if ($response->hasHeader($header) && ! $data['overwrite']) { - continue; - } - $response = $response->withHeader($header, $data['value']); - } - - return $response; - } - - /** - * @param array $config - * @return ResponseHeadersConfig - * @throws InvalidConfigException - */ - private static function normalize(array $config): array - { - $normalized = []; - foreach ($config as $route => $headers) { - if (! is_array($headers)) { - throw InvalidConfigException::routeNotArray($route, $headers); - } - foreach ($headers as $header => $data) { - if (! is_array($data)) { - throw InvalidConfigException::headerNotArray($route, $header, $data); - } - if (! array_key_exists('value', $data)) { - continue; - } - $overwrite = $data['overwrite'] ?? false; - if (! is_bool($overwrite)) { - throw InvalidConfigException::invalidOverwrite($route, $header, $overwrite); - } - - $normalized[(string) $route][(string) $header] = [ - 'value' => self::normalizeValue($route, $header, $data['value']), - 'overwrite' => $overwrite, - ]; - } - } - - return $normalized; - } - - /** - * @return string|non-empty-list - * @throws InvalidConfigException - */ - private static function normalizeValue(int|string $route, int|string $header, mixed $value): string|array - { - if (is_string($value)) { - return $value; - } - if (is_int($value) || is_float($value)) { - return (string) $value; - } - if (! is_array($value) || $value === [] || ! array_is_list($value)) { - throw InvalidConfigException::invalidValue($route, $header, $value); - } - - $values = []; - foreach ($value as $item) { - if (! is_string($item)) { - throw InvalidConfigException::invalidValue($route, $header, $value); - } - $values[] = $item; - } - - return $values; - } -} -``` - -New `src/Exception/InvalidConfigException.php`: - -```php - []` throws `Exception: Unable to find dot-response-header config.`, although the middleware handles an empty config as a no-op (`process()` returns early). A `config` service that is an `ArrayObject` or `null` gives a `TypeError` from `array_key_exists()`. `$container->get('config')` is called twice, and the `?? []` is dead code. - -Before: - -```php -class ResponseHeaderMiddlewareFactory -{ - // constants unchanged - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws Exception - */ - public function __invoke(ContainerInterface $container): ResponseHeaderMiddleware - { - if (! $container->has('config')) { - throw new Exception(self::MESSAGE_MISSING_CONFIG); - } - $config = $container->get('config'); - - if ( - ! array_key_exists('dot_response_headers', $config) - || ! is_array($config['dot_response_headers']) - || empty($config['dot_response_headers']) - ) { - throw new Exception(self::MESSAGE_MISSING_PACKAGE_CONFIG); - } - - return new ResponseHeaderMiddleware($container->get('config')['dot_response_headers'] ?? []); - } -} -``` - -After: - -```php -final class ResponseHeaderMiddlewareFactory -{ - public const MESSAGE_MISSING_CONFIG = 'Unable to find config.'; - public const MESSAGE_MISSING_PACKAGE_CONFIG = 'Unable to find dot-response-header config.'; - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws InvalidConfigException - */ - public function __invoke(ContainerInterface $container): ResponseHeaderMiddleware - { - if (! $container->has('config')) { - throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); - } - - $config = $container->get('config'); - if (! is_array($config) && ! $config instanceof ArrayAccess) { - throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); - } - - $headers = $config['dot_response_headers'] ?? null; - if (! is_array($headers)) { - throw new InvalidConfigException(self::MESSAGE_MISSING_PACKAGE_CONFIG); - } - - return new ResponseHeaderMiddleware($headers); - } -} -``` - -- Why: an empty array is a valid way to turn all headers off (for example per environment). A missing key still throws, so a forgotten config file is still reported. `InvalidConfigException` extends `InvalidArgumentException`, which extends `Exception`, so `catch (Exception)` keeps working and the message constants are unchanged. - -### F4. Route headers cannot replace `*` headers unless `overwrite` is `true` - -- Severity: documentation only (behaviour kept). -- Evidence: with `'*' => ['X-All' => ['value' => 'a']]` and `'home' => ['X-All' => ['value' => 'route']]`, a request to `home` gets `X-All: a`. `*` headers are applied first, so a route header is an "existing header" and needs `overwrite => true`. The existing test `testWillAddHeadersWithCommonWithRouteSpecificHeadersConfiguredWhenRouteMatched` asserts this, so it is intended. -- Change: say it in `usage.md` (D1). Also say that route keys match the **exact** route name; the README's "any route name matching 'user'" reads like a pattern. - -### F5. `ConfigProvider` and the factory are not `final` - -- Severity: low (API hygiene). -- Before: `class ConfigProvider`, `class ResponseHeaderMiddlewareFactory`. -- After: `final class ...` for both. `ResponseHeaderMiddleware` stays non-final and `addHeaders()` stays public, since applications may extend or call it. -- Why: same choice as `dot-cache` 5.0. Breaking for anyone extending them; listed in the upgrade guide. - -### F6. `ConfigProvider` return types - -- Location: `src/ConfigProvider.php:12,19` (V5 #1 and #2). - -Before: - -```php -public function __invoke(): array -``` - -After: - -```php -/** - * @return array{dependencies: array{factories: array}} - */ -public function __invoke(): array -``` - -and `@return array{factories: array}` on `getDependencies()`. - -### F7. Coverage gaps (T16) - -Measured by reading the tests (no coverage driver here, so line numbers are not from a report): - -- `process()` is only called with an empty config, so lines 33-38 (common headers, route lookup) never run. -- The factory success path is never tested; neither is a non-array `config`. -- `ConfigProviderTest` only asserts `assertIsArray`, which is always true. -- `addHeaders()` on a missing `value` key (line 45-47) is not tested. -- Route failure (404/405 `RouteResult`) is not tested. - -### F8. Rewrite the tests (T8, T16) - -- Replace mocks with real collaborators: `Laminas\Diactoros\ServerRequest`, a real `RouteResult::fromRoute()` / `fromRouteFailure()`, and three fixtures in `test/Fixture/`: - - `ArrayContainer` (`final readonly`, PSR-11 `get()` / `has()` over an array; same as `dot-cache`). - - `ServiceNotFoundException extends RuntimeException implements NotFoundExceptionInterface`. - - `FixedResponseHandler` (`RequestHandlerInterface` returning one `Response`, optionally with pre-set headers). -- Data providers are `public static` with `#[DataProvider]`; test classes are `final`. -- Prototype: 27 tests, 42 assertions, OK on PHPUnit 12.5.38 and 12.5.43, phpcs clean, PHPStan level 8 and `max` clean. **14 of the 27 fail against the current `src/`** (the bug tests for F2 and F3). - -| Test class | Cases | -| --- | --- | -| `ConfigProviderTest` | `__invoke()` wraps `getDependencies()`; the middleware maps to its factory | -| `ResponseHeaderMiddlewareFactoryTest` | Missing `config`; non-array `config`; package key missing / string / null (provider); empty package config is a no-op; `ArrayObject` config; invalid package config fails at creation | -| `ResponseHeaderMiddlewareTest` | Empty config returns the handler response unchanged; no `RouteResult`; route failure; matched route with `overwrite` true/false against `*`; route without config; handler header kept unless `overwrite`; header without `value` skipped; valid values string / int / float / list (provider); 6 invalid configs with exact messages (provider) | - -Before (excerpt): - -```php -public function setUp(): void -{ - $this->responseHeader = new ResponseHeaderMiddleware([]); - $this->serverRequest = $this->createMock(ServerRequestInterface::class); - $this->requestHandler = $this->createMock(RequestHandlerInterface::class); -} -``` - -After (excerpt): - -```php -public function testMatchedRouteAddsRouteHeadersAfterCommonHeaders(): void -{ - $response = (new ResponseHeaderMiddleware(self::CONFIG)) - ->process($this->requestForRoute('home'), new FixedResponseHandler()); - - $this->assertSame('home', $response->getHeaderLine('X-Home')); - $this->assertSame('home', $response->getHeaderLine('X-All'), 'route header with overwrite replaces *'); - $this->assertSame('all', $response->getHeaderLine('X-Overwrite'), 'route header without overwrite keeps *'); -} -``` - -- Coverage driver: none installed here. CI already uses pcov in `codecov.yml`. Mutation testing (`infection/infection`) is optional for a package this size; not recommended as a new dev dependency now. - -### F9. Integration check (T18) - -- Scratch Mezzio 3 application (laminas-servicemanager, FastRoute, router 3.20) with `RouteMiddleware`, this middleware, `DispatchMiddleware`, `NotFoundHandler`, and the README config pasted verbatim. -- Result, old and new code identical: `/` gets `CustomHeader1` overwritten, `CustomHeader2` kept from the handler, `CustomHeader` added; `/login` gets `LoginHeader`; `/missing` (404) gets only the `*` headers. -- Not run against router 4.x with a real router implementation (no FastRoute in the 4.x vendor here). - -## Documentation - -`docs/book/index.md` is a symlink to `../../README.md`, so README edits are the docs home page. - -| Page | Required change | -| --- | --- | -| `docs/book/v3/*` | Unchanged | -| `docs/book/v4/` | New folder, copied from `v3` | -| `v4/overview.md` | Badge `php-v/.../3.6.0` to `4.0.0`; `?branch=4.0` and `blob/4.0/LICENSE` | -| `v4/installation.md` | `composer require dotkernel/dot-response-header:^4.0` | -| `v4/configuration.md` | PHP 8.3 to 8.6; `value` accepts string, number or list of strings; `overwrite` must be a bool; empty `dot_response_headers` is allowed; invalid config throws `InvalidConfigException` naming the key | -| `v4/usage.md` | `*` first, then the exact route name (F4); route header needs `overwrite => true` to replace a `*` header; middleware must be piped after `RouteMiddleware` or route headers never apply; example of a multi-value header | -| `v4/upgrading.md` | New, content below | -| `README.md` | Versions table (below); "PHP: 8.3, 8.4, 8.5 or 8.6"; badge `3.6.0` to `4.0.0`; "matching 'user'" wording (F4); missing trailing comma in the `LoginHeader` example | -| `SECURITY.md` | Rows below; fix the double blank line (MD012) and the typo "newc" | -| `mkdocs.yml` | `current_version: v4`; `versions: [v4, v3]`; `v4` nav first with Overview, Installation, Configuration, Usage, Upgrading | -| `CHANGELOG.md` | D2 | - -README and `SECURITY.md` versions table: - -| Version | Supported | PHP | -| --- | --- | --- | -| 4.x | :white_check_mark: | 8.3 to 8.6 | -| 3.x | Security fixes only | 8.2 to 8.5 | -| <= 2.x | :x: | | - -All existing PHP snippets in README, `v3` docs and `config/response-header.global.php.dist` pass `php -l` (the fragment in `usage.md` was wrapped in an array to lint it). The README config example runs unchanged in the integration check. - -### D3. Upgrade guide (`v4/upgrading.md`) - -| Change | Symptom | Fix | -| --- | --- | --- | -| PHP 8.2 dropped | Composer refuses to install | PHP 8.3 or newer | -| `overwrite` must be a `bool` | `InvalidConfigException: dot_response_headers..
.overwrite must be a bool, int given.` | Use `true` / `false`. In 3.x, `1` or `'true'` were silently treated as `false` | -| Route and header entries must be arrays | `InvalidConfigException` naming the key | In 3.x a string route entry was ignored with a PHP warning, and a string header entry threw `TypeError` per request | -| `value` must be a string, number or non-empty list of strings | `InvalidConfigException` | In 3.x `null` threw from the PSR-7 implementation on every request | -| Factory throws `InvalidConfigException` | Code catching `Exception` still works; code checking `get_class()` or the exact class does not | Catch `InvalidArgumentException` or `InvalidConfigException` | -| `ConfigProvider` and factory are `final` | `Class ... cannot extend final class` | Decorate or write your own factory | - -Changes in behaviour: empty `dot_response_headers` now creates a no-op middleware; numeric values are sent as strings; invalid config fails when the middleware is created instead of on each request. - -## CHANGELOG - -The file has only `3.0.0` and `3.0.1`, oldest first, with `3.0.1` dated `2021-01-18` (the tag is `2021-05-18`). It fails markdownlint (MD041, MD022, MD032). Rewrite newest first, add `# Changelog`, blank lines around headings and lists, `-` bullets, and keep the Changed / Added / Deprecated / Removed / Fixed sections with "Nothing" where empty. Entries from the git history between tags: - -| Version | Date | Content | -| --- | --- | --- | -| 4.0.0 | TBD | Changed: PHP `~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0 \|\| ~8.6.0`; `mezzio-router` `^3.16 \|\| ^4.0`; config validated on construction (F2); factory throws `InvalidConfigException`; `ConfigProvider` and factory `final`; PHPUnit 12, PHPStan level 8, `failOn*`; actions v7/v6/v7. Added: PHP 8.6, router 4, `InvalidConfigException`, explicit `psr/container` and `psr/http-server-*` requirements, `v4` docs and upgrade guide. Removed: PHP 8.2, `psr/http-client` (unused). Fixed: empty config throwing (F3), `TypeError` for non-array `config`, warnings and per-request errors for bad config | -| 3.6.0 | 2025-10-30 | Removed PHP 8.1; added PHP 8.4 and 8.5 | -| 3.5.0 | 2025-03-12 | Replaced Psalm with PHPStan | -| 3.4.1 | 2025-01-28 | Psalm 6; "DotKernel" spelled "Dotkernel" | -| 3.4.0 | 2024-10-22 | PHP 8.4; laminas-coding-standard 3 | -| 3.3.1 | 2024-05-27 | `psr/http-message` back to `^1.0 \|\| ^2.0` | -| 3.3.0 | 2024-05-03 | v3 documentation; `psr/http-message` `^2.0` only; SECURITY unsupported versions | -| 3.2.3 | 2023-11-30 | PHP 8.3 | -| 3.2.2 | 2023-08-22 | Codecov workflow and badges | -| 3.2.1 | 2023-08-16 | `psr/http-message` `^1.0 \|\| ^2.0`; diactoros `^3.1` | -| 3.2.0 | 2023-07-28 | PHP `~8.1.0 \|\| ~8.2.0`; required `mezzio-router`, `psr/http-client`, `psr/http-message`; tests, laminas-coding-standard, Psalm; `DotTest` autoload | -| 3.1.0 | 2022-04-06 | PHP `~7.4.0 \|\| ~8.0.0 \|\| ~8.1.0`; PHPUnit 9.5 | -| 3.0.1 | 2021-05-18 | CHANGELOG added; README and middleware changes | -| 3.0.0 | 2021-05-14 | Initial release | - -## Rollout order - -1. ~~Maintainer: apply the `composer.json` edits (V1, V3) and run `composer update`.~~ Done; baseline re-run in the repository on 2026-11-11. -2. ~~`phpunit.xml` and `.gitignore` (V6).~~ Done: PHPUnit exits 1 on the 5 old notices. -3. ~~`ConfigProvider` types and `final` (F5, F6).~~ Done: PHPStan 7 to 5 errors, phpcs clean. -4. ~~Tests rewritten with fixtures (F8), first against the current `src/`.~~ Done: 14 expected failures confirmed. -5. ~~`InvalidConfigException`, middleware (F1, F2), factory (F3).~~ Done: `composer check` passes. -6. ~~Workflows (V4).~~ Done. -7. ~~Docs `v4`, README, SECURITY, mkdocs (D1, D3).~~ Done; lint-clean. -8. ~~CHANGELOG (D2).~~ Done; lint-clean. -9. Maintainer: review, merge `upgrade` into `4.0`, tag `4.0.0`, CHANGELOG date; then re-enable `backwardCompatibilityCheck` in `.laminas-ci.json`. - -## Verification checklist - -- [x] `composer validate --strict` (valid after the maintainer's edits) -- [x] `composer why-not php 8.6.0` and `8.3.0`: no blocker -- [x] `composer check` (phpcs, PHPUnit, PHPStan) passes in the repository: 27 tests, 42 assertions, PHPStan level 8 clean -- [x] `vendor/bin/phpstan analyse --level max`: clean -- [x] No `MockObject` left in `test/`: `grep -rn "createMock\|MockObject" test` finds nothing -- [x] Every new bug test fails on the 3.6.0 code and passes after the fix (14 failed before step 5) -- [x] `php -l` on every PHP snippet in README and `docs/book/v4` (the one-line `ConfigProvider::class,` fragment linted inside an array) -- [x] Every v4 usage and configuration example run through the middleware; output matches what the docs say -- [x] Every `mkdocs.yml` nav target exists -- [ ] `mkdocs build --strict` (not installed here) -- [x] markdownlint passes on README, SECURITY, CHANGELOG, `docs/book/v4/*.md` and this plan with `~/.claude/.markdownlint.jsonc` -- [x] No CRLF line endings; every changed file ends with a newline -- [ ] CI green on 8.3, 8.4, 8.5 and 8.6, lowest and latest dependencies -- [ ] Unverified here, to confirm in CI: - - [ ] PHP 8.3, 8.4 and 8.6 (only 8.5.12 is installed locally) - - [ ] Lowest dependencies: `mezzio-router` 3.17.0 (8.3), 3.18.0 (8.4), 3.19.0 (8.5), 4.3.0 (8.6); `psr/container` 1.1; `psr/http-message` 1.0; diactoros 3.10.0 - - [x] Which `mezzio-router` release first declares PHP 8.6: 4.3.0 (Packagist metadata; 4.0.x stops at 8.4) - - [ ] Whether `ignore_php_platform_requirements` for 8.6 can be removed from `.laminas-ci.json` - - [ ] pcov availability for PHP 8.6 on `setup-php` (only matters if codecov keeps 8.6) - - [ ] Line coverage numbers (no pcov or Xdebug locally) - - [ ] Integration with router 4.x and a real router implementation - - [ ] Vendor deprecations on PHP 8.6 with `failOnDeprecation` diff --git a/.claude/skills/plan-major-upgrade/SKILL.md b/.claude/skills/plan-major-upgrade/SKILL.md deleted file mode 100644 index 541cb38..0000000 --- a/.claude/skills/plan-major-upgrade/SKILL.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -name: plan-major-upgrade -description: Build the written plan for the next major version of a Dotkernel PHP package, saved in `.claude/plan-code-review.md`. Use when asked to review a package and plan its next major release - code review with before/after fixes, phpstan level, workflow and PHP version bumps, PHPUnit upgrade, new docs folder, CHANGELOG and tests. Also use to re-check or update that plan after the maintainer changes `composer.json`. ---- - -# Plan a major upgrade - -Produce one plan file, `.claude/plan-code-review.md`, and keep it current while the work is done. -The plan is the deliverable of the first pass. Make no other changes until the maintainer asks you to implement it. - -## Ground rules - -- **Measure before you claim.** Run the checks and reproduce each suspected bug with a failing test or a small script before it goes in the plan as a bug. Mark anything you could not run as "unverified" and say why (PHP version not installed, no coverage driver, lowest dependencies not installed). -- **Do not edit `composer.json` or install packages.** Edits are denied by the permission settings and the guard hooks block installs. Give the exact lines to change and ask the maintainer to apply them and run the install. Re-check the plan after every such change. -- **Do not circumvent a hook.** If a guard blocks a command, adapt (use the Edit and Write tools, a scratch directory) or ask. -- **Verify facts about other packages from the source**, for example `vendor/` or the published package listing, never from memory. A wrong claim in the plan becomes wrong docs. -- **Markdown is lint-clean.** Every `.md` file you write or edit must pass the maintainer's markdownlint config before you report it as done. - -## Inputs to settle first - -Ask only what you cannot determine from the repository. - -| Item | How to find it | -| --- | --- | -| Next major version number and branch | Ask. Use the current branch name for the plan. Check `git tag`, `git describe --tags` and the remote branches for existing lines | -| Whether other release lines exist | Check branches and tags. A separate line (for example an attribute-based `5.x`) changes the upgrade guide and the README | -| Target PHP versions | From the maintainer or the CI workflow. Note which are installed locally | -| What the maintainer does by hand | Typically `composer.json`, `phpstan.neon` level and the workflow versions. Do not redo or revert them | - -## Task list - -The first eight items (T1 to T8) are the requested tasks. The rest were missed in the original list and should be part of every plan. - -### Requested - -- **T1. Recommend fixes for issues and bugs in the codebase.** Review `src/` for correctness, robustness, types and style. Give each finding an id (F1, F2, ...), a severity, a location and evidence from a reproduction. -- **T2. Add before/after sections** for every recommended update: current code or behaviour, recommended code or behaviour, and why. Cover code, config, docs and tests. -- **T3. `phpstan.neon` to level 8.** Record the current level, run PHPStan at level 8 and list every error with its identifier and fix. Do not propose ignores, baselines or `assert()` workarounds. -- **T4. Workflow versions.** Remove the old PHP version, add the new one, and set the action versions the maintainer named (for example `actions/checkout@v7`, `actions/cache@v6`, `codecov/codecov-action@v7`). Check every file in `.github/workflows` and `.laminas-ci.json`. -- **T5. `phpunit/phpunit` to the new major.** Say whether the maintainer has to do it (it edits `composer.json`) and list the PHPUnit changes the tests need: configuration schema, attributes instead of annotations, static data providers, mock and stub rules, `failOn*` flags. -- **T6. New docs folder for the next major version** in `docs/book`, copied from the most recent version. Keep the old version folders unchanged. List every page that needs content changes. -- **T7. CHANGELOG.md** with all missing releases and the new major release, following the file's section convention. -- **T8. Update the tests**, including new tests for each fixed bug. - -### Recommended additions - -- **T9. Baseline.** Before planning, run `composer check` and record the result, the PHP versions available locally, and the nearest reachable tag (`git describe --tags`). State what the Laminas backward-compatibility check will compare against. -- **T10. Dependency review** of `composer.json`: PHP constraint, each runtime requirement and its range, requirements that are used but undeclared, requirements that are declared but unused, dev dependencies, `suggest` and `conflict`. List exact edits for the maintainer. -- **T11. Dependency removal evaluation.** For any dependency that exists for one import, check whether a PSR interface can replace it and what that would break. Give options and a recommendation. -- **T12. Upgrade guide** (`upgrading.md`) for each older line, with a table of changes that can break code: change, symptom, fix. -- **T13. Discontinued lines.** If a release line is discontinued, add a page in that version's docs folder and point to the replacement package. Read the replacement's source or listing first. -- **T14. README, `docs/book/index.md`, `SECURITY.md` and `mkdocs.yml`.** Version table rows, badges, the supported versions table, `current_version`, `versions` and the navigation. Check whether `docs/book/index.md` is a symlink to the README. -- **T15. `phpunit.xml` and CI flags.** Fail on notices, warnings, deprecations and risky tests. Plan for deprecations raised in vendor code on the newest PHP version. -- **T16. Test quality.** Prefer fixtures and a real collaborator over mocks. Check for traps, for example an annotation reader parsing an `@Inject` mentioned in prose inside a docblock. List coverage gaps by branch, and suggest a coverage driver and mutation testing if none is installed. -- **T17. Documentation examples.** Run every PHP snippet and check every link and navigation entry. Fix examples that never worked. -- **T18. Integration check** outside the repository with the real dependencies (for example a SQLite entity manager and a PSR-6 pool), in a scratch directory. -- **T19. Lifecycle metadata.** Check `OSSMETADATA`, badges and branch names for the new version. -- **T20. Remove `laminas/laminas-servicemanager` when it is a runtime requirement.** Check the `require` section of `composer.json` (a `require-dev` entry or an absence means skip this item). If it is there, implement the removal as `dot-dependency-injection` does, and put each step in the plan with before/after sections: - - Find every use: `grep -rni "laminas\|ServiceManager" src test`. Read `dot-dependency-injection` (`src/Factory`, `src/ConfigProvider.php`, `composer.json`) from its source, not from memory. - - Make the factories plain classes with `__invoke(ContainerInterface $container, string $requestedName)` and only `Psr\Container` imports, so they work with any PSR-11 container that accepts a factory per service key. - - Remove the classes that implement a Laminas interface, normally the abstract factory and its marker annotation. This is a breaking change: list it under Removed in the CHANGELOG and give a "replacing it" section in the upgrade guide, with before and after code. - - Make `ConfigProvider` return `[]` instead of registering `abstract_factories`. Keep the class so applications that list it do not break. - - Replace `ServiceManager` in the tests with a minimal PSR-11 fixture container (`get(string $id): mixed`, `has(string $id): bool`) and exception fixtures that implement `NotFoundExceptionInterface` and `ContainerExceptionInterface`. Class names must end in `Exception` for the coding standard. - - Update the docs, README, version table and CHANGELOG. Say the factories work with any PSR-11 container, and that applications using Laminas Service Manager require it themselves. - - Allow `psr/container` as `^1.1 || ^2.0`, and give the maintainer the `composer.json` edit: remove the requirement and reword the `description`. - - Verify: no `Laminas` or `ServiceManager` left in `src` or `test`, and `composer check` passes. State that the lowest `psr/container` version is unverified unless it was installed. -- **T21. Unverified list.** End the plan with what could not be tested here and how the maintainer can test it in CI. - -## Workflow - -1. Read the repository: `src/`, `test/`, `composer.json`, `phpstan.neon`, `phpunit.xml`, `.github/workflows`, `.laminas-ci.json`, `docs/book`, `README.md`, `CHANGELOG.md`, `SECURITY.md`, `mkdocs.yml`. -2. Run the baseline (T9). -3. Review the code and reproduce each suspected bug (T1 and T2). Use scratch files outside the repository. -4. Run PHPStan at the target level (T3). -5. Review dependencies, workflows and documentation (T4 to T6, T10 to T15 and T20). -6. Write the plan with the structure below. -7. Lint the plan, then tell the maintainer what they have to do by hand. -8. On request, implement the plan in the rollout order, run `composer check` after each step, and update the plan's status table. After every `composer.json` change by the maintainer, re-run the checks and update the docs and CHANGELOG. - -## Plan structure - -Use these headings, in this order. - -1. `# Plan: ` with one paragraph of context (branch, version, date). -2. `## Implementation status`: a table of item, state and notes. Update it as work lands. -3. `## Decision: version `: why this number, and how it relates to other release lines. -4. `## Baseline`: results of the commands you ran, and what you could not run. -5. `## Done by the maintainer`: the edits that were made by hand, and the exact edits still needed. -6. `## Findings`: one section per finding, each with Location, Evidence, Before, After and Why. Group as V1..Vn for version and tooling items, F1..Fn for code and test items. -7. `## Documentation`: a table of page and required change. -8. `## CHANGELOG`: the entries to add, by version. -9. `## Rollout order`: numbered steps, smallest safe change first. -10. `## Verification checklist`: checkboxes for every command and manual check, including the unverified list. - -Use `Before` and `After` as fenced code blocks (`php`, `diff`, `yaml`, `json` or `text`), never an untagged fence. - -## Checklist before reporting done - -- Every finding has a reproduction or is marked unverified. -- Every dependency claim was read from `vendor/` or `composer.json`. -- The plan file passes markdownlint. -- The final message lists what the maintainer must do by hand and what could not be tested here. diff --git a/.laminas-ci.json b/.laminas-ci.json index efdd72e..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -2,5 +2,5 @@ "ignore_php_platform_requirements": { "8.6": true }, - "backwardCompatibilityCheck": false + "backwardCompatibilityCheck": true } From 0940ccd4e898b664d40151ad8f12852b1b4d61a0 Mon Sep 17 00:00:00 2001 From: bidi Date: Mon, 16 Nov 2026 15:57:14 +0200 Subject: [PATCH 3/3] updated based on review Signed-off-by: bidi --- src/Middleware/ResponseHeaderMiddleware.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Middleware/ResponseHeaderMiddleware.php b/src/Middleware/ResponseHeaderMiddleware.php index 3edafc6..687e6b0 100644 --- a/src/Middleware/ResponseHeaderMiddleware.php +++ b/src/Middleware/ResponseHeaderMiddleware.php @@ -77,7 +77,7 @@ public function addHeaders(ResponseInterface $response, string $route): Response * @return ResponseHeadersConfig * @throws InvalidConfigException */ - private static function normalize(array $config): array + private function normalize(array $config): array { $normalized = []; foreach ($config as $route => $headers) { @@ -110,7 +110,7 @@ private static function normalize(array $config): array * @return string|non-empty-list * @throws InvalidConfigException */ - private static function normalizeValue(int|string $route, int|string $header, mixed $value): string|array + private function normalizeValue(int|string $route, int|string $header, mixed $value): string|array { if (is_string($value)) { return $value;