Git Product home page Git Product logo

assert's Introduction

Assert

Travis Status: Build Status

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:

{
    "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:

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);
}

List of assertions

<?php
use Assert\Assertion;

Assertion::integer($value);
Assertion::digit($value);
Assertion::integerish($value);
Assertion::range($value, $minValue, $maxValue);
Assertion::boolean($value);
Assertion::notEmpty($value);
Assertion::notNull($value);
Assertion::regex($value, $regex);
Assertion::length($value, $length);
Assertion::minLength($value, $length);
Assertion::maxLength($value, $length);
Assertion::betweenLength($value, $minLength, $maxLength);
Assertion::startsWith($value, $needle);
Assertion::isArray($value);
Assertion::contains($value, $needle);
Assertion::choice($value, $choices);
Assertion::inArray($value, $choices);
Assertion::numeric($value);
Assertion::keyExists($value, $key);
Assertion::notBlank($value);
Assertion::isInstanceOf($value, $className);
Assertion::classExists($value);
Assertion::subclassOf($value, $className);
Assertion::directory($value);
Assertion::file($value);
Assertion::readable($value);
Assertion::writeable($value);
Assertion::email($value);
Assertion::alnum($value);
Assertion::true($value);
Assertion::false($value);
Assertion::min($value, $min);
Assertion::max($value, $max);
Assertion::eq($actual, $expected);
Assertion::same($actual, $expected);

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 a last argument to any assertion to control the message. Every exception contains a message code by default.

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

try {
    Assertion::integer($value, "The pressure of gas is measured in integers.");
} catch(AssertionFailedException $e) {
    // error handling
}

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. To shield your library from bugs or misinterpretations inside Assert you should introduce a library/project based assertion subclass, where you can override the exception thrown as well:

namespace MyProject;

use Assert\Assertion as BaseAssertion;

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

assert's People

Contributors

beberlei avatar chh avatar edorian avatar matthiasvdh avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.