Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpstan Safe Rule Laravel Package

thecodingmachine/phpstan-safe-rule

PHPStan rule that detects calls to unsafe core PHP functions and suggests the thecodingmachine/safe variants, which throw exceptions instead of returning false on error. Helps catch unsafe function usage during static analysis.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture fit

  • Dev-time only. This is a PHPStan extension — a rule plus a set of DynamicReturnTypeExtensions (preg_match, preg_replace_callback, json_decode, ReplaceSafeFunctions) — shipped as a Composer package. It contributes zero code to the application runtime, which makes it one of the lowest-blast-radius dependencies a TPM can approve: nothing ships, nothing executes in production, rollback is deleting a line from phpstan.neon.
  • It is a companion, not a standalone capability. The rule detects calls to native functions whose failure mode is false and suggests the Safe\* equivalent. Without thecodingmachine/safe installed and adopted, the findings have no remediation path and the package is pure noise. Treat "adopt Safe" and "adopt this rule" as a single decision.
  • Its real architectural value is enforcement, not detection: it converts an error-handling convention into a CI gate with a countable backlog ("N unsafe call sites in the import service, M in the reporting jobs"), which is what makes Safe adoption survive contact with a real Laravel codebase.

Integration feasibility

  • Mechanically trivial: composer require --dev thecodingmachine/phpstan-safe-rule, then include extension.neon in phpstan.neon (or rely on phpstan/extension-installer). v0.1.4 onward supports the installer.
  • Hard constraints to verify before committing: PHP 8.1+ (v1.4 dropped EOL PHP), PHPStan 2.x (v1.3 dropped PHPStan 1.x), and safe at ^1.2/^2/^3 (v1.4 explicitly flags compatibility with Safe v3). The PHPStan 2 requirement is usually the largest hidden cost in a Laravel estate, because it drags Larastan along with it.
  • Already handles the common "legitimate exception" cases that otherwise generate noise: JSON_THROW_ON_ERROR (including as a named argument, v1.4.1), typed $matches for preg_match, json_decode return types, and first-class callables. new DateTime / new DateTimeImmutable detection has existed since v1.0.

Technical risk

  • Version coupling is the dominant risk. PHPStan ships majors aggressively and this extension has historically followed by dropping the previous major. That means an analyzer upgrade and a rule upgrade are the same ticket — plan them together, never independently.
  • Silent no-op. A misordered or un-included extension.neon produces a clean, green build that enforces nothing. This is worse than not adopting the tool, because it manufactures false confidence in a control you told stakeholders you have. Verify with a deliberate unsafe call in a throwaway file.
  • Community/maintenance signal is modest (63 stars, 0 dependents, small maintainer pool). Mitigations are cheap and sufficient: pin an exact version, keep a fork as a credible fallback (the codebase is small), and don't let anything depend on this package's API surface.
  • False positives around first-class callables, variadic arguments, and logically-guaranteed-null cases; expect an ongoing suppression-hygiene cost.

Key questions

  1. Which PHPStan and Larastan versions are we on today, and is the PHPStan 2 upgrade a prerequisite project or already done?
  2. Is safe actually adopted, in evaluation, or aspirational? If aspirational, this is a two-part commitment, not a one-line install.
  3. Do the functions the rule flags (file_get_contents, fopen, JSON without JSON_THROW_ON_ERROR, preg_*, DateTime) map to our real incident history, or is this generic hygiene?
  4. Who owns suppression triage, and what's the policy for @phpstan-ignore creep?
  5. Does a CI diff/changed-files gate exist, or would we need to build one to avoid an overnight red build?

Integration Approach

Stack fit

  • Fits a standard Laravel setup cleanly: Composer, PHPUnit/Pest already present, GitHub Actions or similar running phpstan analyse. The only structural interaction is with Larastan — both are PHPStan extensions, so include ordering and version alignment must be explicit.
  • Works only if the team's error-handling strategy is "throw and handle exceptions." If the org has standardized on Result/Either types or domain-specific exceptions at the boundary, the rule's suggested remediation (Safe\*) may not match house style, and the value proposition weakens.

Migration path

  1. Spike (1–2 days): install in one representative service, include extension.neon, run a full analysis without failing the build, and count findings by directory and by function. That count is your business case and your schedule input.
  2. Install safe alongside it in the same service; remediate one or two modules by hand to validate that the Safe\* replacements actually fit the codebase's error handling.
  3. Baseline, then gate forward. Generate a PHPStan baseline for existing violations (or restrict the rule to changed paths), so the gate applies to new code immediately without a big-bang rewrite. This is the only realistic path for a mature Laravel codebase.
  4. Burn down by domain slice (file/URL I/O, JSON parsing, regex-heavy logic), removing baseline entries as each slice completes.
  5. Flip to blocking once the baseline is small enough that a red build means a real regression.

Compatibility and sequencing

  • Recommended order: PHPStan 2 / Larastan upgrade → adopt safe → adopt this rule with baseline → burn down. Adopting the rule before the analyzer upgrade forces a version of the rule that will be immediately obsoleted.
  • Align on safe v3, which the rule explicitly supports from v1.4; mixing a Safe v2 runtime with assumptions from v3 docs (or vice versa) is a needless source of confusion.
  • Pin the rule ("thecodingmachine/phpstan-safe-rule": "1.4.3" or exact-current) and upgrade it in lockstep with PHPStan via the same dependency-bot PR group.

Operational Impact

Maintenance

  • Two dev dependencies to keep current instead of one (safe + the rule), plus their coupling to PHPStan's major version cadence. Budget a recurring line item: one upgrade ticket per PHPStan major, owner-named.
  • The package is small and the fallback fork is a day's work; this is not a strategic-vendor dependency. Pin it, don't extend it, don't build internal tooling on its internals.

Support

  • Community-supported via GitHub issues, small maintainer pool, no commercial SLA. Escalation path is "patch our fork" — acceptable given the surface area, but it must be written down, not assumed.
  • One named owner for triage and suppression hygiene. Without this, the rule gets globally muted within a quarter and delivers nothing.

Scaling

  • Analysis-time cost is the only scaling dimension that matters, and it is real: the rule adds reflection processing and several dynamic return-type extensions that affect inference across the whole codebase. v1.4.3 specifically made reflection processing lazy to reduce overhead — take that as evidence the cost was noticed.
  • Measure PHPStan wall-clock time before and after on the largest service. For monorepos, prefer analysing changed paths in PRs and the full tree nightly rather than paying the cost on every push.

Failure modes

  1. Silent no-op (extension not loaded / wrong order) — green build, zero enforcement. Detect with a canary commit.
  2. Analyzer upgrade breaks the extension — CI is blocked or the rule is disabled "temporarily," which becomes permanent. Mitigate by upgrading in lockstep and keeping the rule out of the critical path of unrelated releases.
  3. Baseline rot — suppressed findings accumulate and nobody burns them down. Track baseline entry count as a metric with a downward target.
  4. Ignore creep — false positives get blanket-suppressed, including true positives. Review suppressions in PR, not just findings.
  5. Behavioral change on remediation — this is the one that reaches production. Safe\* converts a silent false into a thrown exception; code that previously limped through a failed file_get_contents now fails loudly. That is the desired outcome, but it means every remediation is a behavior change that needs a handler and, where it matters, an alert. Sequence remediations with normal change control rather than bundling them into a lint cleanup.

Ramp-up

  • Installation and configuration: under half a day for an engineer already comfortable with PHPStan.
  • Full rollout including baseline generation, triage, first module remediation, and a short team note ("use Safe\*, here's why, here's how to suppress legitimately"): roughly 2–5 engineer-days for a mid-sized Laravel codebase, plus ongoing triage.
  • Onboarding cost for new developers is a paragraph in the contributing guide. Runtime overhead is zero.
  • Success metrics to report: unsafe-call count trending to zero, baseline entry count, suppression count, PHPStan CI duration delta, and incident tickets in the flagged I/O paths. The last one is the metric stakeholders actually care about; the others are the leading indicators that the gate is real rather than decorative.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator