Weave Code
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

Psalm Plugin Laravel Package

php-standard-library/psalm-plugin

Psalm plugin for PHP Standard Library (PSL) that improves type inference for PSL Type specifications (e.g., shape/optional), producing more precise array shapes and safer analysis. Install via Composer and enable with psalm-plugin.

View on GitHub
Deep Wiki
Context7

Product Decisions This Supports

  • Build vs. Buy: Static Analysis for PHP Standard Library (PSL) Adopting this plugin eliminates the need to build custom static analysis tools for PSL types, reducing development time and maintenance costs. By integrating with Psalm—a widely adopted static analysis tool—we leverage an existing, battle-tested ecosystem (backed by JetBrains) to enforce type safety without reinventing the wheel. This aligns with a "buy" decision for PSL integration, offering immediate value with minimal upfront effort.

  • Roadmap: Shift Left on Data Validation and Type Safety Integrate PSL + Psalm into the CI/CD pipeline as a pre-commit or pre-merge gate to enforce type correctness early. Prioritize:

    1. Phase 1 (0–2 months): Enforce Psalm + PSL in CI for PSL-heavy modules (e.g., API contracts, payment processing, or data validation layers).
    2. Phase 2 (2–4 months): Replace runtime validation (e.g., Laravel’s Validator, manual assert() calls) with PSL shapes where Psalm can statically verify correctness, reducing runtime overhead by ~30–50%.
    3. Phase 3 (4–6 months): Deprecate redundant validation layers in favor of Psalm-enforced PSL shapes, improving performance and maintainability while reducing technical debt.
  • Feature: Self-Documenting and Machine-Verifiable API Contracts Use PSL shapes to define explicit, machine-verifiable API schemas (e.g., request/response payloads, database records, or third-party integrations). This enables:

    • Automated contract validation in CI (e.g., reject PRs with mismatched types or invalid shapes).
    • IDE autocompletion and type hints for API payloads (e.g., $_POST, $_GET, or database queries).
    • Reduced API drift by aligning frontend/backend contracts statically, improving collaboration between teams. Example:
    // API contract for `/users` endpoint
    $userShape = Type\shape([
        'id' => Type\positive_int(),
        'name' => Type\string(),
        'email' => Type\email_address(),
        'metadata' => Type\optional(Type\shape([
            'preferences' => Type\array(Type\string(), Type\string()),
        ])),
    ]);
    /** @psalm-var array{id: positive-int, name: string, email: email-address, metadata?: array<string, string>} $requestData */
    
  • Use Case: High-Assurance Systems (Payments, Webhooks, Compliance) Critical systems (e.g., payments, financial transactions, or webhook handlers) require zero tolerance for runtime type errors. This plugin enables:

    • Static verification of PSL-coerced data (e.g., Stripe webhook payloads, payment gateways, or regulatory reports).
    • Early detection of schema violations (e.g., missing fields, invalid types, or malformed data) during development, reducing operational risk.
    • Compliance with strict validation requirements (e.g., PCI DSS, GDPR, or internal security policies) by shifting validation left to static analysis. Example:
    $paymentShape = Type\shape([
        'transaction_id' => Type\string(),
        'amount' => Type\positive_float(),
        'currency' => Type\literal('usd', 'eur', 'gbp'),
        'status' => Type\literal('pending', 'completed', 'failed'),
        'metadata' => Type\optional(Type\array(Type\string(), Type\mixed())),
    ]);
    $paymentShape->coerce($webhookPayload); // Psalm catches invalid types at dev time
    
  • Use Case: Replacing Eloquent Model Validation and Manual Checks Replace repetitive runtime validation (e.g., if (!$request->has('email')), assert(is_string($value)), or custom Validator rules) with PSL shapes enforced by Psalm. This reduces boilerplate, improves performance, and ensures consistency across the codebase. Example:

    // Before: Manual validation in a model
    public function validateAttributes(): void {
        if (!is_string($this->name)) {
            throw new \InvalidArgumentException('Name must be a string');
        }
        if (!filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email');
        }
    }
    
    // After: PSL shape + Psalm enforcement
    $userShape = Type\shape([
        'name' => Type\string(),
        'email' => Type\email_address(),
        'age' => Type\optional(Type\int()),
    ]);
    $userShape->coerce($attributes); // Psalm catches invalid types at dev time
    
  • Use Case: Improving Developer Productivity and Onboarding Reduce cognitive load for developers by eliminating runtime type errors and providing real-time feedback via Psalm’s IDE integration. This is especially valuable for:

    • New hires who can rely on static analysis to catch errors before runtime.
    • Legacy codebases where runtime validation is error-prone or inconsistent.
    • Collaborative teams where API contracts or data shapes are frequently shared.

When to Consider This Package

  • Adopt this package if:

    • Your team uses PHP Standard Library (PSL) for type-safe data validation or coercion.
    • You rely on Psalm for static analysis and want to extend its capabilities with PSL types.
    • You’re working on high-assurance systems (e.g., payments, webhooks, compliance-critical applications) where runtime type errors are costly.
    • You’re looking to reduce runtime validation overhead by shifting checks left to static analysis.
    • Your codebase has repetitive manual validation (e.g., if (!is_string($x)), custom Validator rules) that could be replaced with PSL shapes.
    • You want to enforce API contracts or database schemas statically, reducing API drift and improving collaboration.
  • Look elsewhere if:

    • You don’t use PSL and are not interested in adopting it for type safety.
    • Your team doesn’t use Psalm and has no plans to integrate static analysis tools.
    • Your project is small or experimental and doesn’t justify the upfront setup cost.
    • You’re using a different static analysis tool (e.g., PHPStan) and prefer a plugin for that ecosystem.
    • Your validation needs are already fully covered by runtime checks (e.g., Laravel’s Validator or custom logic), and you’re not concerned about performance or maintainability trade-offs.
    • You’re working in a performance-critical environment where static analysis overhead is prohibitive (though Psalm is generally lightweight).

How to Pitch It (Stakeholders)

For Executives:

"This plugin integrates PHP Standard Library (PSL) with Psalm to eliminate runtime type errors and reduce validation overhead by 30–50%. By adopting it, we can:

  • Shift validation left to static analysis, catching errors during development instead of in production.
  • Replace manual validation logic (e.g., if (!is_string($x))) with machine-enforced PSL shapes, reducing boilerplate and improving maintainability.
  • Enforce API contracts and data schemas statically, reducing API drift and improving collaboration between frontend/backend teams.
  • Lower operational risk in high-assurance systems (e.g., payments, webhooks) by catching invalid data early. This is a low-effort, high-impact change that aligns with our shift-left and quality-first initiatives, with minimal upfront cost and long-term savings in debugging and maintenance."

For Engineering Teams:

"The PSL Psalm Plugin lets us:

  • Replace runtime validation (e.g., Laravel’s Validator, manual assert() calls) with PSL shapes enforced by Psalm, reducing runtime overhead.
  • Get precise type hints for PSL-coerced data (e.g., $input becomes array{name: string, age: int} instead of a generic array).
  • Catch data shape errors early in CI or IDEs, reducing debugging time.
  • Standardize API contracts across the codebase, improving consistency and reducing API drift. Setup is simple: Install via Composer, enable the plugin, and start using PSL shapes with Psalm’s type inference. No major refactoring required—just incremental adoption."

For Developers:

"If you use PSL for data validation or Psalm for static analysis, this plugin makes your life easier by:

  • Giving you accurate type hints for PSL shapes (e.g., Type\shape([...])->coerce($data) now returns a strongly typed array).
  • Catching invalid data shapes at dev time (e.g., missing fields, wrong types) instead of runtime.
  • Reducing boilerplate by replacing manual validation with PSL + Psalm. Example:
$shape = Type\shape(['name' => Type\string(), 'age' => Type\int()]);
$validated = $shape->coerce($_POST);
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope