Webmozart Assert

repository·master·Indexed 27 days ago

https://github.com/webmozarts/assert

A PHP library providing efficient, high-quality assertions to validate method inputs and outputs. It includes a wide range of type, comparison, string, file, object, and array assertions, throwing a Webmozart\Assert\InvalidArgumentException upon failure. Features include custom error messages with placeholders, lazy assertion messages via callables, and prefixes like all*() for collections and nullOr*() for nullable values.

Tokens
6K
Snippets
5
Records
35
Agent score
88%

What's inside webmozarts/assert

  1. Perform nullable assertions

    master

    You can prefix any assertion with nullOr*() to run the assertion only if the value is not null. This is useful for optional parameters.

    Assert::nullOrString($middleName, 'The middle name must be a string or null. Got: %s');
  2. Customize assertion error messages with placeholders

    master

    You can provide custom error messages to assertions. The library uses consistent placeholder ordering:

    • %s: The tested value as a string (e.g., "/foo/bar").
    • %2$s, %3$s, etc.: Additional assertion-specific values, such as minimum/maximum length or allowed values.

    Example:

    Assert::string($path, 'The path is expected to be a string. Got: %s');
  3. Enable Psalm static analysis support

    master

    Webmozart Assert functions are annotated to support Psalm's assertion syntax. To enable type inference for return types in Psalm (available in version 2.x), you must enable the native Psalm plugin.

    vendor/bin/psalm-plugin enable webmozart/assert
  4. Use lazy assertion messages

    master

    To avoid unnecessary computation when an assertion passes, you can provide a callable as the message argument. The callable is only executed if the assertion fails.

    Assert::string($value, fn() => expensiveMessage());
  5. Use Webmozart Assert in your code

    master

    Import the Webmozart\\Assert\\\Assert class to perform assertions. If an assertion fails, a Webmozart\\Assert\\\InvalidArgumentException is thrown.

    use Webmozart\\Assert\\\Assert;
    
    class Employee
    {
        public function __construct($id)
        {
            Assert::integer($id, 'The employee ID must be an integer. Got: %s');
            Assert::greaterThan($id, 0, 'The employee ID must be a positive integer. Got: %s');
        }
    }
  6. Extend the Assert class

    master

    You can extend the Assert class to change its behavior or add your own assertions by overriding specific protected or public methods.

    Methods you can override:

    • public static function __callStatic($name, $arguments): Used to 'create' the nullOr and all versions of assertions.
    • protected static function valueToString($value): Used for error messages to convert a value to a string.
    • protected static function typeToString($value): Used for error messages to convert a value to a string representing its type.
    • protected static function strlen($value): Used to calculate string length (uses mb_strlen if available).
    • protected static function reportInvalidArgument($message): Called when an assertion fails. You can use this to throw custom exceptions or log errors.
  7. Reference: Function Assertions

    master
    MethodDescription
    throws($closure, $class, $message = '')Check that a function throws a certain exception. Subclasses of the exception class will be accepted.
    isStatic($closure, $message = '')Check that a function is static.
    notStatic($closure, $message = '')Check that a function is not static.
  8. Reference: Comparison Assertions

    master

    The Assert class provides methods to compare values.

    MethodDescription
    true($value, $message = '')Check that a value is true
    false($value, $message = '')Check that a value is false
    notFalse($value, $message = '')Check that a value is not false
    null($value, $message = '')Check that a value is null
    notNull($value, $message = '')Check that a value is not null
    isEmpty($value, $message = '')Check that a value is empty()
    notEmpty($value, $message = '')Check that a value is not empty()
    eq($value, $value2, $message = '')Check that a value equals another (==)
    notEq($value, $value2, $message = '')Check that a value does not equal another (!=)
    same($value, $value2, $message = '')Check that a value is identical to another (===)
    notSame($value, $value2, $message = '')Check that a value is not identical to another (!==)
    greaterThan($value, $value2, $message = '')Check that a value is greater than another
    greaterThanEq($value, $value2, $message = '')Check that a value is greater than or equal to another
    lessThan($value, $value2, $message = '')Check that a value is less than another
    lessThanEq($value, $value2, $message = '')Check that a value is less than or equal to another
    range($value, $min, $max, $message = '')Check that a value is within a range
    inArray($value, array $values, $message = '')Check that a value is one of a list of values
    notInArray($value, array $values, $message = '')Check that a value is not one of a list of values
    oneOf($value, array $values, $message = '')Check that a value is one of a list of values (alias of inArray)
    notOneOf($value, array $values, $message = '')Check that a value is not one of a list of values (alias of notInArray)
  9. Reference: File Assertions

    master
    MethodDescription
    fileExists($value, $message = '')Check that a value is an existing path
    file($value, $message = '')Check that a value is an existing file
    directory($value, $message = '')Check that a value is an existing directory
    readable($value, $message = '')Check that a value is a readable path
    writable($value, $message = '')Check that a value is a writable path