talira

Webmozart Assert

Assertions to validate PHP method input and output with clear error messages

open sourceMITfree

Webmozart Assert is a PHP library of assertions for checking the input and output of your methods: each assertion in its Assert class throws an InvalidArgumentException with a usable error message when it fails, and you can give your own messages with consistent placeholders. Every assertion also has nullOr and all variants. Its assertions are annotated for Psalm's assertion syntax, it ships a native Psalm plugin for return-type inference, and PHPStan needs a separate plugin. It was inspired by beberlei/assert and fixes that package's inconsistent error-message placeholders.

Problems it solves

  • validate method arguments in PHP with readable error messages
  • check preconditions in PHP code without writing if-throw boilerplate
  • narrow types for Psalm or PHPStan after runtime checks in PHP

Features

  • Assertions that throw InvalidArgumentException with readable messages
  • Custom error messages with consistent placeholder ordering
  • nullOr and all variants of every assertion
  • Psalm assertion annotations and a native Psalm plugin for type inference
  • Overridable hooks for value formatting and failure reporting

Limitations

  • Needs PHP 8.2 or later with the ctype, date and filter extensions1

Alternatives

The same job

These do what Webmozart Assert does.

  1. Assert (beberlei/assert) Thin assertion library for input validation in PHP business models and libraries
  2. Respect\Validation Fluent validation engine for PHP with more than 150 validators

Compare Webmozart Assert with the top 3