Convert Figma logo to code with AI

beberlei logoassert

Thin assertion library for use in libraries and business-model

2,402
188
2,402
43

Top Related Projects

7,534

Assertions to validate method input/output with nice error messages.

Data transfer objects with batteries included

PHP getallheaders polyfill

Provides tools to validate values

2,337

All PHP functions, rewritten to throw exceptions instead of returning false

Quick Overview

beberlei/assert is a PHP library that provides a set of assertion methods for input validation. It offers a fluent interface for writing expressive and readable validation checks, helping developers ensure data integrity and catch potential errors early in the development process.

Pros

  • Extensive set of assertion methods covering various data types and validation scenarios
  • Fluent interface allows for chaining multiple assertions, improving code readability
  • Customizable error messages for each assertion
  • Lightweight and easy to integrate into existing projects

Cons

  • Limited to assertion-based validation, may not be suitable for complex validation scenarios
  • Requires manual handling of assertion failures
  • No built-in support for internationalization of error messages
  • Maintenance and updates may be slower compared to more popular validation libraries

Code Examples

  1. Basic string validation:
use Assert\Assertion;

Assertion::string($value);
Assertion::minLength($value, 5);
Assertion::maxLength($value, 20);
  1. Numeric validation with custom error message:
use Assert\Assertion;

Assertion::numeric($value, 'The value must be a number');
Assertion::between($value, 1, 100, 'The value must be between 1 and 100');
  1. Array validation:
use Assert\Assertion;

Assertion::isArray($value);
Assertion::allString($value, 'All array elements must be strings');
Assertion::count($value, 5, 'The array must contain exactly 5 elements');
  1. Object property validation:
use Assert\Assertion;

$user = new User();
Assertion::propertyExists($user, 'email', 'User must have an email property');
Assertion::email($user->email, 'Invalid email address');

Getting Started

To use beberlei/assert in your PHP project, follow these steps:

  1. Install the library using Composer:
composer require beberlei/assert
  1. Include the Composer autoloader in your PHP file:
require_once 'vendor/autoload.php';
  1. Use the assertion methods in your code:
use Assert\Assertion;

// Your validation logic here
Assertion::string($value, 'Value must be a string');
Assertion::email($email, 'Invalid email address');

Remember to handle assertion exceptions (InvalidArgumentException) in your application to provide appropriate error feedback to users.

Competitor Comparisons

7,534

Assertions to validate method input/output with nice error messages.

Pros of Assert (Webmozart)

  • More comprehensive set of assertion methods
  • Better documentation and examples
  • Actively maintained with regular updates

Cons of Assert (Webmozart)

  • Slightly larger package size
  • May have a steeper learning curve due to more extensive API

Code Comparison

Assert (Beberlei):

Assert::integer($value, $message);
Assert::string($value, $message);
Assert::notEmpty($value, $message);

Assert (Webmozart):

Assert::integer($value, $message);
Assert::string($value, $message);
Assert::notEmpty($value, $message);
Assert::allInteger($values, $message);
Assert::keyExists($array, $key, $message);

Both libraries provide similar basic assertion methods, but Webmozart's Assert offers additional methods for more complex validations, such as allInteger for checking all elements in an array and keyExists for verifying array keys.

While the core functionality is similar, Webmozart's Assert generally provides more flexibility and options for developers, making it suitable for projects requiring more extensive validation. However, for simpler projects, Beberlei's Assert might be sufficient and potentially easier to integrate due to its more focused approach.

Data transfer objects with batteries included

Pros of data-transfer-object

  • Focuses on creating structured data objects, enhancing type safety
  • Provides a more object-oriented approach to data handling
  • Offers built-in validation and casting mechanisms

Cons of data-transfer-object

  • Limited to data transfer object creation and validation
  • May require more setup for simple assertion scenarios
  • Less flexibility for general-purpose assertions

Code Comparison

data-transfer-object:

class UserData extends DataTransferObject
{
    public string $name;
    public int $age;
}

$userData = new UserData(['name' => 'John', 'age' => 30]);

assert:

use Assert\Assertion;

Assertion::string($name, 'Name must be a string');
Assertion::integer($age, 'Age must be an integer');

Key Differences

  • assert is primarily focused on assertions and validations
  • data-transfer-object emphasizes structured data objects
  • assert offers a wider range of assertion methods
  • data-transfer-object provides a more object-oriented approach to data handling

Use Cases

  • Use assert for general-purpose assertions and validations
  • Choose data-transfer-object for creating structured data objects with built-in validation

Community and Maintenance

  • Both projects are actively maintained
  • assert has a larger user base and longer history
  • data-transfer-object is part of the Spatie ecosystem, known for high-quality PHP packages

PHP getallheaders polyfill

Pros of getallheaders

  • Focused on a single, specific task: retrieving HTTP headers
  • Lightweight and easy to integrate into existing projects
  • Compatible with various PHP versions and server environments

Cons of getallheaders

  • Limited functionality compared to assert's comprehensive assertion library
  • Less actively maintained, with fewer recent updates
  • Lacks extensive documentation and examples

Code Comparison

getallheaders:

function getallheaders() {
    $headers = [];
    foreach ($_SERVER as $name => $value) {
        if (substr($name, 0, 5) == 'HTTP_') {
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
        }
    }
    return $headers;
}

assert:

public static function that($value, $defaultMessage = null)
{
    return new Assert\AssertionChain($value, $defaultMessage);
}

public static function string($value, $message = null, $propertyPath = null)
{
    static::that($value, $message)->isString($propertyPath);
}

The code comparison shows that getallheaders focuses on retrieving HTTP headers, while assert provides a more extensive set of assertion methods for various data types and conditions. assert offers a fluent interface for chaining assertions, making it more versatile for complex validation scenarios.

Provides tools to validate values

Pros of Symfony Validator

  • More comprehensive validation framework with built-in constraints
  • Integrates seamlessly with Symfony ecosystem and other components
  • Supports custom validation constraints and violation messages

Cons of Symfony Validator

  • Steeper learning curve due to more complex architecture
  • Heavier dependency footprint
  • May be overkill for simple validation tasks

Code Comparison

Symfony Validator:

use Symfony\Component\Validator\Constraints as Assert;

class User
{
    #[Assert\NotBlank]
    #[Assert\Length(min: 2, max: 50)]
    private $name;
}

Assert:

use Assert\Assertion;

$name = 'John';
Assertion::notBlank($name);
Assertion::lengthBetween($name, 2, 50);

Summary

Symfony Validator offers a more robust and feature-rich validation framework, ideal for complex applications and those already using Symfony components. It provides a wide range of built-in constraints and seamless integration with the Symfony ecosystem.

Assert, on the other hand, is a lightweight library focused on simple, straightforward assertions. It's easier to pick up and use in smaller projects or when you need quick, standalone validation without the overhead of a full framework.

Choose Symfony Validator for comprehensive validation in larger projects, especially within the Symfony ecosystem. Opt for Assert when you need a simple, lightweight validation solution for smaller projects or specific use cases.

2,337

All PHP functions, rewritten to throw exceptions instead of returning false

Pros of Safe

  • Provides type-safe wrappers for PHP functions, reducing the risk of type-related errors
  • Offers a more extensive set of assertions and type checks
  • Includes helpful IDE autocompletion support

Cons of Safe

  • May have a steeper learning curve due to its more comprehensive API
  • Potentially slower performance due to additional type checks
  • Requires PHP 7.2 or higher, limiting compatibility with older projects

Code Comparison

Assert:

Assert::string($value);
Assert::notEmpty($value);
Assert::length($value, 5, 10);

Safe:

Safe::strlen($value);
Safe::array_key_exists('key', $array);
Safe::json_decode($jsonString, true);

Summary

Assert focuses on simple, straightforward assertions, while Safe provides a more comprehensive set of type-safe wrappers for PHP functions. Assert is easier to adopt but offers fewer features, whereas Safe provides more robust type checking at the cost of increased complexity and potential performance overhead. The choice between the two depends on project requirements, PHP version compatibility, and the desired level of type safety.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Assert

Build Status Code Coverage GitHub issues

PHP Version Stable Version

Total Downloads Monthly Downloads Daily Downloads

A simple php library which contains assertions and guard methods for input validation (not filtering!) in business-model, libraries and application low-level code. The library can be used to implement pre-/post-conditions on input data.

Idea is to reduce the amount of code for implementing assertions in your model and also simplify the code paths to implement assertions. When assertions fail, an exception is thrown, removing the necessity for if-clauses in your code.

The library is not using Symfony or Zend Validators for a reason: The checks have to be low-level, fast, non-object-oriented code to be used everywhere necessary. Using any of the two libraries requires instantiation of several objects, using a locale component, translations, you name it. Its too much bloat.

Installation

Using Composer:

composer require beberlei/assert

Example usages

<?php
use Assert\Assertion;

function duplicateFile($file, $times)
{
    Assertion::file($file);
    Assertion::digit($times);

    for ($i = 0; $i < $times; $i++) {
        copy($file, $file . $i);
    }
}

Real time usage with Azure Blob Storage:

<?php
public function putBlob($containerName = '', $blobName = '', $localFileName = '', $metadata = array(), $leaseId = null, $additionalHeaders = array())
{
    Assertion::notEmpty($containerName, 'Container name is not specified');
    self::assertValidContainerName($containerName);
    Assertion::notEmpty($blobName, 'Blob name is not specified.');
    Assertion::notEmpty($localFileName, 'Local file name is not specified.');
    Assertion::file($localFileName, 'Local file name is not specified.');
    self::assertValidRootContainerBlobName($containerName, $blobName);

    // Check file size
    if (filesize($localFileName) >= self::MAX_BLOB_SIZE) {
        return $this->putLargeBlob($containerName, $blobName, $localFileName, $metadata, $leaseId, $additionalHeaders);
    }

    // Put the data to Windows Azure Storage
    return $this->putBlobData($containerName, $blobName, file_get_contents($localFileName), $metadata, $leaseId, $additionalHeaders);
}

NullOr helper

A helper method (Assertion::nullOr*) is provided to check if a value is null OR holds for the assertion:

<?php
Assertion::nullOrMax(null, 42); // success
Assertion::nullOrMax(1, 42);    // success
Assertion::nullOrMax(1337, 42); // exception

All helper

The Assertion::all* method checks if all provided values hold for the assertion. It will throw an exception of the assertion does not hold for one of the values:

<?php
Assertion::allIsInstanceOf(array(new \stdClass, new \stdClass), 'stdClass'); // success
Assertion::allIsInstanceOf(array(new \stdClass, new \stdClass), 'PDO');      // exception

Assert::that() Chaining

Using the static API on values is very verbose when checking values against multiple assertions. Starting with 2.6.7 of Assert the Assert class provides a much nicer fluent API for assertions, starting with Assert::that($value) and then receiving the assertions you want to call on the fluent interface. You only have to specify the $value once.

<?php
Assert::that($value)->notEmpty()->integer();
Assert::that($value)->nullOr()->string()->startsWith("Foo");
Assert::that($values)->all()->float();

There are also two shortcut function Assert::thatNullOr() and Assert::thatAll() enabling the "nullOr" or "all" helper respectively.

Lazy Assertions

There are many cases in web development, especially when involving forms, you want to collect several errors instead of aborting directly on the first error. This is what lazy assertions are for. Their API works exactly like the fluent Assert::that() API, but instead of throwing an Exception directly, they collect all errors and only trigger the exception when the method verifyNow() is called on the Assert\SoftAssertion object.

<?php
Assert::lazy()
    ->that(10, 'foo')->string()
    ->that(null, 'bar')->notEmpty()
    ->that('string', 'baz')->isArray()
    ->verifyNow();

The method that($value, $propertyPath) requires a property path (name), so that you know how to differentiate the errors afterwards.

On failure verifyNow() will throw an exception Assert\\LazyAssertionException with a combined message:

The following 3 assertions failed:
1) foo: Value "10" expected to be string, type integer given.
2) bar: Value "<NULL>" is empty, but non empty value was expected.
3) baz: Value "string" is not an array.

You can also retrieve all the AssertionFailedExceptions by calling getErrorExceptions(). This can be useful for example to build a failure response for the user.

For those looking to capture multiple errors on a single value when using a lazy assertion chain, you may follow your call to that with tryAll to run all assertions against the value, and capture all of the resulting failed assertion error messages. Here's an example:

Assert::lazy()
    ->that(10, 'foo')->tryAll()->integer()->between(5, 15)
    ->that(null, 'foo')->tryAll()->notEmpty()->string()
    ->verifyNow();

The above shows how to use this functionality to finely tune the behavior of reporting failures, but to make catching all failures even easier, you may also call tryAll before making any assertions like below. This helps to reduce method calls, and has the same behavior as above.

Assert::lazy()->tryAll()
    ->that(10, 'foo')->integer()->between(5, 15)
    ->that(null, 'foo')->notEmpty()->string()
    ->verifyNow();

Functional Constructors

The following functions exist as aliases to Assert static constructors:

  • Assert\that()
  • Assert\thatAll()
  • Assert\thatNullOr()
  • Assert\lazy()

Using the functional or static constructors is entirely personal preference.

Note: The functional constructors will not work with an Assertion extension. However it is trivial to recreate these functions in a way that point to the extended class.

List of assertions

<?php
use Assert\Assertion;

Assertion::alnum(mixed $value);
Assertion::base64(string $value);
Assertion::between(mixed $value, mixed $lowerLimit, mixed $upperLimit);
Assertion::betweenExclusive(mixed $value, mixed $lowerLimit, mixed $upperLimit);
Assertion::betweenLength(mixed $value, int $minLength, int $maxLength);
Assertion::boolean(mixed $value);
Assertion::choice(mixed $value, array $choices);
Assertion::choicesNotEmpty(array $values, array $choices);
Assertion::classExists(mixed $value);
Assertion::contains(mixed $string, string $needle);
Assertion::count(array|Countable|ResourceBundle|SimpleXMLElement $countable, int $count);
Assertion::date(string $value, string $format);
Assertion::defined(mixed $constant);
Assertion::digit(mixed $value);
Assertion::directory(string $value);
Assertion::e164(string $value);
Assertion::email(mixed $value);
Assertion::endsWith(mixed $string, string $needle);
Assertion::eq(mixed $value, mixed $value2);
Assertion::eqArraySubset(mixed $value, mixed $value2);
Assertion::extensionLoaded(mixed $value);
Assertion::extensionVersion(string $extension, string $operator, mixed $version);
Assertion::false(mixed $value);
Assertion::file(string $value);
Assertion::float(mixed $value);
Assertion::greaterOrEqualThan(mixed $value, mixed $limit);
Assertion::greaterThan(mixed $value, mixed $limit);
Assertion::implementsInterface(mixed $class, string $interfaceName);
Assertion::inArray(mixed $value, array $choices);
Assertion::integer(mixed $value);
Assertion::integerish(mixed $value);
Assertion::interfaceExists(mixed $value);
Assertion::ip(string $value, int $flag = null);
Assertion::ipv4(string $value, int $flag = null);
Assertion::ipv6(string $value, int $flag = null);
Assertion::isArray(mixed $value);
Assertion::isArrayAccessible(mixed $value);
Assertion::isCallable(mixed $value);
Assertion::isCountable(array|Countable|ResourceBundle|SimpleXMLElement $value);
Assertion::isInstanceOf(mixed $value, string $className);
Assertion::isJsonString(mixed $value);
Assertion::isObject(mixed $value);
Assertion::isResource(mixed $value);
Assertion::isTraversable(mixed $value);
Assertion::keyExists(mixed $value, string|int $key);
Assertion::keyIsset(mixed $value, string|int $key);
Assertion::keyNotExists(mixed $value, string|int $key);
Assertion::length(mixed $value, int $length);
Assertion::lessOrEqualThan(mixed $value, mixed $limit);
Assertion::lessThan(mixed $value, mixed $limit);
Assertion::max(mixed $value, mixed $maxValue);
Assertion::maxCount(array|Countable|ResourceBundle|SimpleXMLElement $countable, int $count);
Assertion::maxLength(mixed $value, int $maxLength);
Assertion::methodExists(string $value, mixed $object);
Assertion::min(mixed $value, mixed $minValue);
Assertion::minCount(array|Countable|ResourceBundle|SimpleXMLElement $countable, int $count);
Assertion::minLength(mixed $value, int $minLength);
Assertion::noContent(mixed $value);
Assertion::notBlank(mixed $value);
Assertion::notContains(mixed $string, string $needle);
Assertion::notEmpty(mixed $value);
Assertion::notEmptyKey(mixed $value, string|int $key);
Assertion::notEq(mixed $value1, mixed $value2);
Assertion::notInArray(mixed $value, array $choices);
Assertion::notIsInstanceOf(mixed $value, string $className);
Assertion::notNull(mixed $value);
Assertion::notRegex(mixed $value, string $pattern);
Assertion::notSame(mixed $value1, mixed $value2);
Assertion::null(mixed $value);
Assertion::numeric(mixed $value);
Assertion::objectOrClass(mixed $value);
Assertion::phpVersion(string $operator, mixed $version);
Assertion::propertiesExist(mixed $value, array $properties);
Assertion::propertyExists(mixed $value, string $property);
Assertion::range(mixed $value, mixed $minValue, mixed $maxValue);
Assertion::readable(string $value);
Assertion::regex(mixed $value, string $pattern);
Assertion::same(mixed $value, mixed $value2);
Assertion::satisfy(mixed $value, callable $callback);
Assertion::scalar(mixed $value);
Assertion::startsWith(mixed $string, string $needle);
Assertion::string(mixed $value);
Assertion::subclassOf(mixed $value, string $className);
Assertion::true(mixed $value);
Assertion::uniqueValues(array $values);
Assertion::url(mixed $value);
Assertion::uuid(string $value);
Assertion::version(string $version1, string $operator, string $version2);
Assertion::writeable(string $value);

Remember: When a configuration parameter is necessary, it is always passed AFTER the value. The value is always the first parameter.

Exception & Error Handling

If any of the assertions fails a Assert\AssertionFailedException is thrown. You can pass an argument called $message to any assertion to control the exception message. Every exception contains a default message and unique message code by default.

<?php
use Assert\Assertion;
use Assert\AssertionFailedException;

try {
    Assertion::integer($value, "The pressure of gas is measured in integers.");
} catch(AssertionFailedException $e) {
    // error handling
    $e->getValue(); // the value that caused the failure
    $e->getConstraints(); // the additional constraints of the assertion.
}

Assert\AssertionFailedException is just an interface and the default implementation is Assert\InvalidArgumentException which extends the SPL InvalidArgumentException. You can change the exception being used on a package based level.

Customised exception messages

You can pass a callback as the message parameter, allowing you to construct your own message only if an assertion fails, rather than every time you run the test.

The callback will be supplied with an array of parameters that are for the assertion.

As some assertions call other assertions, your callback will need to example the array to determine what assertion failed.

The array will contain a key called ::assertion that indicates which assertion failed.

The callback should return the string that will be used as the exception message.

Your own Assertion class

To shield your library from possible bugs, misinterpretations or BC breaks inside Assert you should introduce a library/project based assertion subclass, where you can override the exception thrown as well.

In addition, you can override the Assert\Assertion::stringify() method to provide your own interpretations of the types during error handling.

<?php
namespace MyProject;

use Assert\Assertion as BaseAssertion;

class Assertion extends BaseAssertion
{
    protected static $exceptionClass = 'MyProject\AssertionFailedException';
}

As of V2.9.2, Lazy Assertions now have access to any additional assertions present in your own assertion classes.

Contributing

Please see CONTRIBUTING for more details.