westonruter / phpstan-diff
Run PHPStan and report only the errors on lines changed relative to a base branch.
Requires
- php: >=8.2
Requires (Dev)
Suggests
- ext-pcntl: So that, when phpstan-diff is sent SIGTERM, it stops the git and PHPStan processes it started.
Provides
None
Conflicts
None
Replaces
None
README
Run PHPStan and show only the errors on lines you changed relative to a base
branch (by default, the repository's default branch, e.g. trunk or main), instead
of burying them under every pre-existing error in the codebase. This is handy when you
run PHPStan at a stricter rule level
locally than the project's committed baseline.
There is no native "diff mode" in PHPStan itself; its baseline feature is a
snapshot, not a git diff. Other diff filters exist (see Alternatives below), but
they treat PHPStan as just another linter: you run it over the whole project, and
they throw away whatever falls outside the diff. The phpstan-diff tool runs PHPStan itself,
so it can analyze just the changed files, work out the base branch, and handle
staged-only and whitespace-only changes. It also knows how PHPStan's rule levels and
ignores interact. With --level, PHPStan runs at a level other than the configured
one. At a lower level, the baseline and ignoreErrors entries written for the
configured level stop matching, and phpstan-diff drops the errors PHPStan reports
about them, which a plain filter would pass on as errors. It's a small
self-contained PHP tool:
| Script | What it is |
|---|---|
bin/phpstan-diff |
The thing you normally run. Works out the base, runs PHPStan with --error-format=json on the changed files, keeps only messages on changed lines, prints a PHPStan-style table (or JSON), and exits 1 if anything remains. |
bin/phpstan-diff-filter |
Just the filtering, for when you run PHPStan some other way: reads a PHPStan JSON report on stdin and diffs against the merge-base with --base (without looking at its remote-tracking counterparts). |
src/ |
The code both of them use: the functions in phpstan-diff.php and a few enums, loaded by load.php. |
Install
Install it with Composer, either into a project or globally. It has no dependencies of its own, so neither way can conflict with a project's packages.
As a dev dependency of a project, which pins its version in composer.lock and makes
it available in CI too:
composer require --dev westonruter/phpstan-diff vendor/bin/phpstan-diff
Or globally, to use it in any project without adding it to the project's
composer.json:
composer global require westonruter/phpstan-diff phpstan-diff
For that, Composer's global bin directory must be on your $PATH;
composer global config bin-dir --absolute prints it (usually
~/.composer/vendor/bin, or ~/.config/composer/vendor/bin on Linux).
Or, without Composer, download the PHAR from the
latest release, check
it, and put it on your $PATH (here ~/bin, which has to be on it):
cd "$(mktemp -d)" curl -fLO https://github.com/westonruter/phpstan-diff/releases/latest/download/phpstan-diff.phar curl -fLO https://github.com/westonruter/phpstan-diff/releases/latest/download/SHA256SUMS sha256sum -c --ignore-missing SHA256SUMS # on older macOS: shasum -a 256 -c --ignore-missing SHA256SUMS gh attestation verify phpstan-diff.phar --repo westonruter/phpstan-diff # optional: check it was built by this repo's release workflow mkdir -p ~/bin install -m 755 phpstan-diff.phar ~/bin/phpstan-diff
The checksums are checked before the PHAR is renamed, since SHA256SUMS lists it as
phpstan-diff.phar. phpstan-diff-filter.phar is in the release too. Running a PHAR
needs PHP's phar extension, which PHP includes by default, but some minimal builds
package separately (e.g. Alpine's php-phar). (To build the PHARs yourself from a
checkout, run tools/build-phar; they're written to build/.)
Or, to run it from a checkout (e.g. to work on it):
git clone https://github.com/westonruter/phpstan-diff.git ~/repos/phpstan-diff ln -s ~/repos/phpstan-diff/bin/phpstan-diff ~/bin/phpstan-diff # or add bin/ to $PATH
Requirements: git, php (CLI, 8.2 or later), and PHPStan reachable from the project
directory (see Locating PHPStan below). It runs on macOS and Linux, including
WSL, as long as git, php and PHPStan
are the Linux ones installed inside WSL rather than Windows executables (which
report C:\… paths that won't match git's). Native Windows isn't supported, since
paths are assumed to use / throughout.
Usage
Run it from the project root, just like phpstan analyse:
phpstan-diff # analyze the .php files changed vs the default branch, show errors on the changed lines phpstan-diff --whole-project # slower: analyze the whole configured project (still only reports changed lines) phpstan-diff --exclude=tests # the changed files, minus anything under tests/ phpstan-diff --include=src # only changed files under src/ phpstan-diff -- src/wp-includes/rest-api.php # restrict PHPStan (and the diff) to given paths phpstan-diff --base=6.7-branch # diff against a different base ref phpstan-diff --staged # like the default, but exclude unstaged edits (committed + staged vs the base) phpstan-diff --staged --base=HEAD # only the staged changes (pre-commit-hook scope) phpstan-diff --no-ignore-whitespace # also count lines whose only changes are in whitespace phpstan-diff --level=max # hold the changed lines to the strictest rule level phpstan-diff --format=json | jq '.files | keys'
Options:
-
--base=<ref>— base ref to diff against. Default:$PHPSTAN_DIFF_BASE; else, in a GitHub Actions run for a pull request, the branch it targets ($GITHUB_BASE_REF); else the repository's default branch: the branch thatorigin/HEAD(orupstream/HEAD) points to, asgit clonerecords it; or else the first ofdevelop(git-flow's integration branch),main,masterandtrunkthat exists locally or onoriginorupstream(a stale branch on some other remote isn't picked). With neither of those remotes, as in a fork whose main remote has another name, the remote that the checked-out branch tracks stands in for them. (Iforigin/HEADis missing,git remote set-head origin --autosets it.) When it names a local branch, its remote-tracking counterparts are considered too — see Choosing the base below. -
--staged— diff the staged snapshot (the git index) against the base instead of the working tree: errors on committed + staged changes, with unstaged edits ignored. Add--base=HEADto narrow it to staged changes only (pre-commit-hook scope). (PHPStan still analyzes the working tree, not the staged blob.) -
--no-ignore-whitespace— count lines whose only changes are in the amount of whitespace (re-indentation, trailing spaces) as changed. By default (--ignore-whitespace) they don't count, as withgit diff -b: re-indenting code (say, to wrap it in a newifblock) doesn't bring its existing errors into the report, and files with only such changes aren't analyzed. Whitespace added where there was none, or removed entirely ("a b"to"ab"), still counts, as does indenting top-level code that had none.Re-indented lines can have new errors all the same: code moved into a closure, say, loses the variables it used. So notes say which files were skipped, and how many errors in the analyzed files are on such lines and aren't shown (
--format=jsonhas the count asphpstan_diff.whitespace_only_errors). Those errors don't affect the exit status, so a check that has to catch them should pass--no-ignore-whitespace. -
--whole-project— when no paths are given, run PHPStan on the whole configured project instead of only the.phpfiles that differ from the base (the default). Errors are still reported only on changed lines, so for most rules the output is identical — just slower. It matters for rules that collect data across files (e.g. dead-code detection), where whether a changed file has an error depends on how other files use it, and for changed files outside the config'spaths:(explicit paths override them, so the default analyzes such files too; a whole-project run doesn't). -
--level=<level>— run PHPStan at this rule level (0to10, ormax;10needs PHPStan 2) instead of the one in its configuration. Default:$PHPSTAN_DIFF_LEVEL, if set. Since only errors on changed lines are reported,--level=maxholds new code to a stricter standard without first fixing (or baselining) the rest of the project. It's passed to PHPStan after the command's own arguments, so it also overrides a--levelin a Composer script or$PHPSTAN_DIFF_ANALYSE_CMD(unless a Composer script puts@additional_argsbefore its own--level). The baseline, otherignoreErrorsentries and@phpstan-ignorecomments were written for the configured level:- At a lower level, PHPStan's errors about ignores that no longer fit
(
ignore.unmatched,ignore.unmatchedLineandignore.unmatchedIdentifier, orignore.countfor acountthat's off) aren't reported. - At a level at least as strict (
max, or a number at least the configured one), every ignore still matches what it was written for, since levels are cumulative, so one that doesn't is stale (e.g. a new comment that ignores nothing), and it's reported. Onlyignore.countisn't, as more errors can match an entry; the errors beyond itscountare reported as usual.
The configured level comes from
phpstan dump-parameters; if it can't be found, any level butmaxcounts as lower. A note says how many errors weren't reported, and in JSON,phpstan_diff.ignore_mismatch_errorscounts them (withphpstan_diff.level). An empty--level=runs at the configured level, overriding$PHPSTAN_DIFF_LEVEL. PHPStan's result cache is for one level at a time, so with--whole-project, switching between--leveland the configured level re-analyzes the whole project each time. - At a lower level, PHPStan's errors about ignores that no longer fit
(
-
--changed— deprecated no-op, accepted for backward compatibility: analyzing only the changed files is now the default. -
--include=<glob>— keep only files matching this repo-relative path or glob, intersected with the files that actually changed. Repeatable (a file is kept if it matches any--include). A bare directory matches everything under it (--include=src⇒src/Foo.php); globs work too (--include='src/*',*.php), and*may span/. -
--exclude=<glob>— drop files matching this repo-relative path or glob (--exclude=tests). Repeatable; applied after--include, and an exclude wins over an include. Unless--whole-projectis given, excluded files aren't handed to PHPStan at all, so the run is faster too. -
--format=table(default) |--format=json—jsonemits the filtered PHPStan JSON document (same shape as--error-format=json, with non-changed files/messages removed), plus aphpstan_diff.baseobject saying what the diff was taken against:{"requested": "trunk", "used": [{"ref": "upstream/trunk", "commit": "<sha>"}], "staged": false}. Eachcommitis what the diff was taken against: the ref's merge-base withHEAD(or the ref itself, if it shares no history withHEAD). Whenusedlists several refs, a line counts as changed only if it changed relative to every one of them (see Choosing the base). -
--version(or-V) — print the version, e.g.phpstan-diff 1.2.3. From a git checkout, it's whatgit describesays (1.2.3-4-g1a2b3c4, four commits after that tag).
Note
--include/--exclude vs the positional <paths>. The positional <paths>
are PHPStan's analysis targets — handed to phpstan analyse verbatim to decide
what it scans. --include/--exclude are filters over the changed files: they
understand globs and, crucially, let you say "everything except tests"
(--exclude=tests) — something a list of paths can't express. They're orthogonal
and stack: phpstan-diff --exclude=tests derives the changed .php files, drops
the test ones (so PHPStan never sees them), then line-filters the rest.
The changed files that are analyzed are those with an extension that PHPStan
analyzes: .php, and any others in its configuration's
fileExtensions (e.g.
.inc or .phtml). The configuration is only asked for (with
phpstan dump-parameters, which takes a moment) when a file other than a .php
one changed, so .php files are always in scope, even if fileExtensions leaves
php out. Where a Composer script runs PHPStan with several configurations, each
is handed the changed .php files and those with its own extensions.
PHPStan analyzes a trait only along with a class that uses it, so a changed trait
handed to PHPStan on its own wouldn't be analyzed at all. For a changed file that
declares a trait, the files that mention the trait's name (tracked, or
untracked and not ignored; except those that --exclude drops) are therefore
analyzed too, as are the files that mention any trait declared in those (a trait
may only be used by another trait). Errors are still reported only on changed
lines, and PHPStan names the class each of the trait's errors is for:
src/T.php (in context of class C). At most 100 files are added this way: if
more mention a trait (one with a common name, say), only those that do so on a
line with use count, and if that's still too many, none are added and a warning
says so, since the trait's errors are then missed (--whole-project finds them).
Changed files that the project's own PHPStan configuration excludes (via
excludePaths, e.g. bundled third-party libraries) are skipped by PHPStan as
usual, and a note lists them so you know they weren't checked. (PHPStan skips
them silently, so phpstan-diff works this out from phpstan dump-parameters,
run alongside the analysis.) If that leaves nothing to analyze — say, a commit
touching only an excluded file — PHPStan itself would fail with "No files found to
analyse"; phpstan-diff instead passes (exit 0) with the note. (Likewise, when
no .php files changed at all, it passes without running PHPStan.)
PHPStan's configuration (excludePaths) excludes 1 of the 3 files in scope, so it was not analyzed:
src/wp-includes/class-IXR.php
[OK] No errors on changed lines (base: trunk)
Choosing the base
There's no need to pull the base branch, or to merge it into your feature branch,
before running phpstan-diff. The diff is always taken from the merge-base —
where your branch last took in the base — so a base branch that has moved on since
doesn't add its changes to yours.
What would add noise is a local base branch that is behind: if your branch
has merged origin/trunk (say, via GitHub's "Update branch" button) but your local
trunk hasn't been pulled, the merge-base with trunk lands too far back and the
upstream commits look like yours. So when --base names a local branch,
phpstan-diff also considers its upstream and <branch> on the origin and
upstream remotes (both, in a fork), and diffs against whichever your branch
merged most recently. Other remotes, such as a collaborator's fork, are left
out, since their branch may have merged yours. A branch that exists only on
remotes, as in a CI clone with origin/trunk but no local trunk, is handled
the same way.
Any of these that already contains HEAD (e.g. a trunk your branch has been
merged into) is skipped too, since it would hide every change, unless all of them
do, or it's the branch you have checked out (on trunk itself, the diff is
against trunk, i.e. your uncommitted changes). A note says when it picked a
remote-tracking ref over the local branch, and the summary line shows the ref
and the merge-base commit actually used:
[OK] No errors on changed lines (base: upstream/trunk @ 1a2b3c4)
If your branch merged several of them and none contains the others (say,
origin/trunk with fork-only commits, and a newer upstream/trunk), a line
counts as changed only if it changed relative to all of their merge-bases, so
neither one's commits count as yours
(base: upstream/trunk + origin/trunk @ 1a2b3c4 + 5d6e7f8).
phpstan-diff never fetches: remote-tracking refs are only as fresh as your last
fetch. That's usually fresh enough, since git pull on your branch (to take in an
"Update branch" merge, say) fetches every branch of that remote, origin/trunk
included. But in a fork, if your branch merged upstream/trunk and you haven't
fetched upstream since, run git fetch upstream first; otherwise upstream's
newer commits look like yours.
In a shallow clone (e.g. actions/checkout with its default fetch-depth: 1)
there may not be enough history to find a merge-base. Then the diff is against
the base itself, so its newer changes count too, and a note says so. Fetch more
history (fetch-depth: 0, or git fetch --unshallow) to avoid that.
To use a local branch exactly as-is, spell out its full ref:
--base=refs/heads/trunk. Any base that isn't a local branch name (origin/trunk,
HEAD, a tag or commit) is also used as-is.
Merging the base into your branch still matters for what PHPStan sees — e.g. when upstream changed the signature of a function your branch calls — but not for which lines count as changed.
What counts as a "changed line": every line that differs between
git merge-base <base> HEAD and your working tree — i.e. your branch commits
plus staged and unstaged edits. With --staged, the comparison is against the
git index rather than the working tree, so unstaged edits drop out (committed +
staged only); adding --base=HEAD on top of that leaves just the staged changes.
Exit status: 1 if any errors remain after filtering, 0 if none, 2 on
internal errors (PHPStan didn't produce JSON, not a git repo, bad ref, …).
Locating PHPStan
bin/phpstan-diff runs PHPStan from the project directory: the nearest one, from
the current directory up to the repository's top level, that has a PHPStan
configuration file (phpstan.neon etc.) or can run PHPStan (its composer.json has
a phpstan script, or its Composer bin-dir has phpstan); failing that, the top
level. The PHPStan binary may be in a directory further up. So it works the same
from a subdirectory, or from a package of a monorepo, with the package's own
configuration if it has one. It figures out how to run PHPStan, in this order:
$PHPSTAN_DIFF_ANALYSE_CMDif set — used verbatim, our extra args appended. It runs from the current directory, so relative paths in it mean what they would on the command line. If it runs a Composer script, that's split as below. E.g.PHPSTAN_DIFF_ANALYSE_CMD='composer phpstan --'orPHPSTAN_DIFF_ANALYSE_CMD='vendor/bin/phpstan analyse -c phpstan.neon'.composer phpstan --ifcomposer.json(or the file$COMPOSERnames) has aphpstanscript. If that script only lists other scripts (e.g.["@phpstan:default", "@phpstan:strict"], one per configuration, possibly nested), each is run, one after another, and their reports are merged. (Run as one script, Composer would stop at the first that finds any error.)vendor/bin/phpstan analyse --memory-limit=2G(honors a custom Composerbin-dirandvendor-dir).- A globally-installed
phpstan analyse --memory-limit=2G. - Otherwise it errors and tells you to install PHPStan or set
PHPSTAN_DIFF_ANALYSE_CMD.
PHPStan runs without a terminal: its stdin is /dev/null, as its output is captured.
So a PHPSTAN_DIFF_ANALYSE_CMD that needs one (e.g. docker exec -it …) won't work;
leave out -t (e.g. docker exec app vendor/bin/phpstan analyse).
This means it picks up whatever config composer phpstan already uses — including a
local stricter phpstan.neon that overrides phpstan.neon.dist.
Pre-commit hook
Drop this in .git/hooks/pre-commit (chmod +x it) to block commits that
introduce errors on the lines being committed. It only checks staged .php
files, never touches your working tree, and is bypassable with
git commit --no-verify (or disabled with PHPSTAN_DIFF_PRECOMMIT_SKIP=1).
It runs vendor/bin/phpstan-diff if the repository's top level has one (git runs
hooks from there), or else phpstan-diff from $PATH, and when it finds neither, it
skips the check. So if phpstan-diff is installed somewhere else, such as a
subdirectory's vendor/bin in a monorepo, or a checkout that isn't on the $PATH
your git client or IDE runs hooks with, change the path in the hook:
#!/usr/bin/env bash set -euo pipefail [ -n "${PHPSTAN_DIFF_PRECOMMIT_SKIP:-}" ] && exit 0 if [ -x vendor/bin/phpstan-diff ]; then phpstan_diff=vendor/bin/phpstan-diff elif command -v phpstan-diff >/dev/null 2>&1; then phpstan_diff="$(command -v phpstan-diff)" else echo "pre-commit: phpstan-diff not found — skipping PHPStan check." >&2 exit 0 fi files=() while IFS= read -r f; do [ -n "$f" ] && files+=("$f") done < <(git diff --cached --name-only --diff-filter=ACMR -- '*.php') [ "${#files[@]}" -eq 0 ] && exit 0 # phpstan-diff analyzes files on disk and maps results onto the staged hunks; if # a staged file also has unstaged edits, that mapping is approximate — warn only. git diff --quiet -- "${files[@]}" || \ echo "pre-commit: note — some staged files have unstaged changes; line mapping is approximate." >&2 # --base=HEAD scopes the diff to just the staged changes; without it, --staged # would also report on changes committed earlier in the branch. exec "$phpstan_diff" --staged --base=HEAD -- "${files[@]}"
Warning
Don't git stash in the hook. It's tempting to git stash --keep-index
so PHPStan sees exactly the staged content, but with newly-added or
partially-staged files the matching git stash pop can hit conflicts and
leave your tree in a bad state. The hook above accepts a slightly approximate
line mapping for partially-staged files instead — the common
git add <file> && git commit case (working tree == index) is still exact.
GitHub Actions
A project's CI usually runs phpstan analyse already, with its committed
configuration and baseline, and that's what keeps new errors out. phpstan-diff
doesn't replace that check. It adds a stricter one, on just the lines a pull request
changes, which is useful when:
- New code should meet a stricter standard than the rest of the codebase. Say
the project is at level 5 with a baseline, and changed lines should meet level 8
(
--level=8) or a stricter configuration (PHPSTAN_DIFF_ANALYSE_CMD='vendor/bin/phpstan analyse -c phpstan-strict.neon'), without first fixing or baselining the rest of the project. - The project has no baseline, and would rather not maintain one: PHPStan's errors are then checked only where a pull request makes changes.
- The check should only advise, at least at first: with
continue-on-error: trueon the job, its errors show on the pull request without blocking it.
This workflow runs it on pull requests, holding the changed lines to the strictest level:
name: PHPStan (changed lines) on: pull_request: permissions: contents: read jobs: phpstan-diff: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 with: fetch-depth: 0 # The base branch's history, to find the merge-base. - uses: shivammathur/setup-php@v2 with: php-version: '8.4' coverage: none - run: composer install --no-interaction --no-progress - run: vendor/bin/phpstan-diff --level=max
It assumes phpstan-diff is one of the project's dev dependencies (see Install). The
base needn't be given: in a pull request's run, it's the branch the pull request
targets ($GITHUB_BASE_REF). fetch-depth: 0 matters, since in a shallow clone the
merge-base may be missing (see Choosing the base).
Annotating the pull request
To show each error on its line in the pull request's Files changed tab, add a step
that runs phpstan-diff again when it fails, with --format=json, and turns each
message into an error annotation.
Give the step that runs it an id:
- name: Run phpstan-diff id: phpstan-diff run: vendor/bin/phpstan-diff --level=max - name: Annotate the errors if: failure() && steps.phpstan-diff.outcome == 'failure' run: | vendor/bin/phpstan-diff --level=max --format=json > "$RUNNER_TEMP/phpstan-diff.json" || [ $? -eq 1 ] jq -r --arg root "$(pwd -P)/" ' .files | to_entries[] | (.key | ltrimstr($root)) as $file | .value.messages[] | "::error file=\($file),line=\(.line),title=PHPStan\(if .identifier then " (\(.identifier))" else "" end)::" + (.message | gsub("%"; "%25") | gsub("\r"; "%0D") | gsub("\n"; "%0A")) ' "$RUNNER_TEMP/phpstan-diff.json"
The table from the first run stays in the job's log, so every error is listed there even when there are more than GitHub shows as annotations, as it limits how many a step and a job can have.
Using with Claude / during PR review
Tell Claude: "to check PHPStan, run phpstan-diff and only act on what
it prints — those are the errors this branch introduced." (You may want to add
that to a project note / Claude memory so it's used automatically.)
Contributing
How to run the tests, static analysis and code style checks, and how releases are
made, is in CONTRIBUTING.md.
Alternatives
Other tools that limit linter output to a diff:
reviewdogworks with any linter. It reads checkstyle (PHPStan's--error-format=checkstyle), SARIF, rdjson orerrorformatinput and filters it with-filter-mode=added|diff_context|file|nofilter. It's a Go binary that's mainly used to post PR review comments in CI.exussum12/coverage-checkerhas adiffFiltercommand that reads PHPStan, PHPCS, PHPMD, Psalm and checkstyle output and keeps only the messages on changed lines.- Trunk Check is a commercial tool built around "hold the line": it reports only the issues on changed lines, for any linter.
For PHPCS specifically:
sirbrillig/phpcs-changedruns PHPCS on both the old and new version of each changed file and reports only the messages that are new, so code that just moved isn't reported.- PHPCS's own
--filter=GitModifiedand--filter=GitStagedlimit the run to changed files, not lines.
In other ecosystems: golangci-lint has --new-from-rev, Python has diff-quality
(part of diff-cover) and
darker, and SonarQube and Qodana have
"new code" and baseline modes.
PHPStan's own answer is the baseline: generate it on the base branch and only new errors are reported. That catches what a line filter can't — an error a change causes on a line it didn't touch, such as at the call sites of a function whose signature changed — but it has to be regenerated for each base.
Known limitations
- Messages with no line, or a line outside every changed hunk (some file-level errors like "class not found"), are dropped.
- Truly untracked files aren't part of any diff, so PHPStan errors in them are
dropped —
git addthem (or commit) to have them considered. - Path quoting: paths with unusual characters in
git diffheaders may not be matched perfectly. - The table output approximates
phpstan analyse's table; it isn't pixel-perfect and doesn't emit editor hyperlinks (but relativepath:linestrings are still clickable in most IDE terminals).
AI disclosure
This tool (its code, tests, CI workflows and this README) was written with
Claude Code, at the maintainer's direction and
with the maintainer's review: almost every commit was made with it, and only a few
small edits were made by hand. Each commit's Co-Authored-By trailer names the model
that wrote it (and, since November 2026, the reasoning effort used):
| Model | When | What it wrote |
|---|---|---|
| Claude Opus 4.7 (1M context) | May 2026 | The original version, a bash wrapper around a PHP filter, from the prompt below, checked against a real repository. |
| Claude Opus 4.8 (1M context) | May 2026 | --include and --exclude, and cleanups. |
| Claude Opus 5.5 | October–November 2026 | Analyzing only the changed files; choosing the base among the default branch and its remote counterparts; the test suite and CI; the port of the wrapper from bash to PHP, with PHPStan at level 10 and PHPCS; finding PHPStan as the project runs it; ignoring whitespace-only changes; --level; installation with Composer and as a PHAR; and fixes from several rounds of code review. |
Details
Original prompt used to plan this tool
I have a stricter phpstan.neon compared with phpstan.neon.dist. I always use the former with PhpStorm and it is automatically picked up with
composer phpstan. However, the problem is that it reports many many errors for lines that aren't changed in the current branch compared with trunk. I want to create a command line tool called something like phpstan-diff which analyzes the project (or the supplied file paths) and then filters out anything that isn't among the modified lines in the current branch compared withtrunk. And the base branch could also be configurable. Maybe this should be something which simply takes the output of acomposer phpstan -- --error-format=jsonand then filters out the results (e.g. using jq). if there are errors, then the filter script can have an exit code of 1 or else otherwise an exit code of 0. This filter script I can then use in a pre-commit hook as well as something which I can tell Claude about to use whenever I'm reviewing a PR. So it should be something that I can easily invoke from the command line. Maybe that means one filter command script and then another simple wrapper bash script around that filter command script. The wrapper is what I would normally invoke. The wrapper command can should format the errors in a way likephpstan analyzenormally outputs.An example of something I've used for this in the past:
composer phpstan -- --error-format=json -- src/wp-includes/rest-api.php 2>/dev/null \ | jq '.files["/Users/westonruter/repos/wordpress-develop/src/wp-includes/rest-api.php"].messages | map(select(.line >= 2927 and .line <= 3031) | del(.ignorable))'Is there already a way to get PHPStan to only report errors for lines in a diff? Or do I need to create a new helper? If new helpers are needed, let's put them in the empty repo I just created at
~/repos/phpstan-diff/
License
MIT © Weston Ruter