• Stars
    star
    2,384
  • Rank 18,513 (Top 0.4 %)
  • Language
    PHP
  • License
    Other
  • Created almost 12 years ago
  • Updated 13 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Thin assertion library for use in libraries and business-model

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.

More Repositories

1

DoctrineExtensions

A set of Doctrine 2 extensions
PHP
1,956
star
2

litecqrs-php

Small convention based CQRS library for PHP
PHP
556
star
3

metrics

Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics (functional) API that doesn't cause vendor lock-in.
PHP
315
star
4

composer-monorepo-plugin

Integrates Composer into monolithic repositories with many packages.
PHP
304
star
5

porpaginas

A simple abstraction for paginated and non-paginated results
PHP
158
star
6

AcmePizzaBundle

Acme Form Experimental Bundle
PHP
132
star
7

php-rfc-watch

Interactive voting results for PHP RFC process.
HTML
128
star
8

zf-doctrine

A Zend Framework 1.x and Doctrine 1.2 Integration - UNMAINTAINED
PHP
102
star
9

netbeans-php-enhancements

Netbeans PHP Enhancements, such as PHP Code Sniffer Support
Java
102
star
10

fastcgi-serve

Small webserver to use in front of fast-cgi servers (php-fpm, hhvm, ...)
Go
91
star
11

symfony-minimal-distribution

This contains the code from my blog post http://whitewashing.de/2014/10/26/symfony_all_the_things_web.html
PHP
68
star
12

bankaccount

Sample application used for PHPUnit training.
PHP
48
star
13

vim-php-refactor

Some simple vim refactoring functions for your PHP code
Vim Script
40
star
14

xdebug-trace-gui

Fork of Trace GUI by Thomas Hambach
PHP
35
star
15

license-manager

License Switch Project - Helping open source projects to switch licenses
CSS
34
star
16

Doctrine-Workflow

A Doctrine 2 persistence layer for ezcWorkflow
PHP
33
star
17

DoctrineCodeGenerator

Prototype of an AST based Event Driven CodeGenerator
PHP
31
star
18

http-client-middleware

Missing interfaces for HTTP-Client middlewares using PSR-7 messages.
PHP
28
star
19

Doctrine-ActiveEntity

ActiveRecord ORM (Mod) on top of Doctrine2
PHP
25
star
20

env

PHP PECL extension for loading 12factor env variables from a file
C
24
star
21

Whitewashing

Symfony2 Bundle that powers the www.whitewashing.de blog
PHP
23
star
22

WhitewashingZFMvcCompatBundle

PHP
21
star
23

azure-blob-storage

Small platform-independent library to access Microsoft Windows Azure Blob Storage with a Service or a StreamWrapper.
PHP
21
star
24

zelten

A social network website based on tent.io protocol
JavaScript
17
star
25

TentPHP

A Tent.io client written in PHP
PHP
16
star
26

githubpr_to_jira

Converts Github PR to Jira Issues
PHP
16
star
27

context

DEPRECATED
PHP
15
star
28

pearanha

Pearanha is deprecated, use Composer intead
PHP
15
star
29

WhitewashingLogglyBundle

loggly.com logger for Monolog integrated into Symfony2 - not really maintained anymore
PHP
15
star
30

php-compiletime-poc

Extension that counts the time spent in PHP file compilation during the execution of a script
C
13
star
31

php-ast-tracer-poc

C
13
star
32

doctrine-example-app

Example App Setup for Training/Workshops
PHP
13
star
33

dbdeploy-php

DBDeploy PHP clone
PHP
12
star
34

ZendNavigationBundle

A Zend Navigation Bundle for Symfony2
PHP
11
star
35

phpricot

A forgiving HTML Parsing library written in PHP
PHP
11
star
36

hdrhistogram-php

A PHP extension wrapper for the C hdrhistogram API.
C
10
star
37

symfony-azure-edition

Symfony2 on Windows Azure Edition
PHP
10
star
38

ReviewSquawkBundle

Symfony2 app that provides a static-code-analysis as a service platform
JavaScript
9
star
39

ZetaBundle

A Zeta Components Bundle for Symfony2
PHP
8
star
40

websocket-proxy-example

Example Go microservice that acts as a Websocket proxy for other server applications
Go
6
star
41

stdlib

Some fun
PHP
6
star
42

compilefile-ext

C
5
star
43

Zend_Db-Adapter-for-ext-mysql

Legacy applications often work with ext/mysql all over the place. This Zend_Db adapter allows to share the resources and benefit from Zend_Db.
PHP
5
star
44

php8-benchmark-doctrine

PHP
5
star
45

ZetaWorkflowCouchDB

Zeta Components CouchDB Backend for Workflow
PHP
4
star
46

php-overload-poc

C
4
star
47

php-couch-content-repository

PHP
3
star
48

funcall

Fork of the pecl extension "funcall"
C
3
star
49

flow3-doctrine2

prototype hack for doctrine2 as persistence manager for flow3
PHP
3
star
50

redmine_gherkinviewer

Redmine Plugin: Display feature files from project repository directly in a "Features" tab in the project.
Ruby
3
star
51

AzureTaskDemoBundle

Demo bundle for Azure Functionality with a Symfony+Doctrine application
JavaScript
2
star
52

beberlei

1
star
53

deprecations

PHP
1
star
54

pecl_http

PHP
1
star
55

cj-push-server

PubSubHubBub Server in Clojure
Clojure
1
star
56

interrupt-sampler-poc

C
1
star
57

hdrhistogram-php-stubs

Adding support for hdrhistogram in IDEs and Scrutinizer
PHP
1
star