webmozart/assert
webmozart/assert is a lightweight PHP assertion library for validating method input/output. It provides many type and value checks via a single Assert class and throws InvalidArgumentException with consistent, readable default error messages (or custom ones).
Install with composer require webmozart/assert, then import use Webmozart\Assert\Assert;. Begin by validating method inputs—especially in value objects, DTOs, or domain services—to enforce type and value constraints early. Start with basic type checks like Assert::string($name) or Assert::integer($id), and add context with custom messages (e.g., 'User ID must be a positive integer. Got: %s'). The first use case is usually constructor validation in immutable objects to prevent invalid states.
Assert::email($email), Assert::range($age, 0, 120)).if (...) throw ... blocks with concise Assert::notNull($entity), Assert::greaterThan($quantity, 0).Assert::uuid($id), Assert::ip($clientIp)).Assert or create static helpers for domain-specific rules (e.g., EmployeeAssert::validTaxId()).integerish(), scalar(), or isArrayAccessible() when accepting loosely-typed input (e.g., from JSON or legacy systems).InvalidArgumentException, so ensure they’re used where exceptions are acceptable (e.g., not in high-throughput loops without profiling).%s = the tested value; additional args use %2$s, %3$s, etc. Misordering (e.g., mixing up min/max in lengthBetween) breaks custom messages.== comparisons: Use same()/notSame() for strict identity (especially booleans and 0 vs '0')—eq() can be misleading.string() before length(), regex(), etc.—chaining string()->length() is common.'Invoice number must be non-empty string' instead of just 'Invalid'.file(), isStatic()) behind assert_options(ASSERT_ACTIVE, true) in production if used heavily.@phpstan-ignore-line may help for intentionally-loose cases.How can I help you explore Laravel packages today?