PHP code example of wookieb / type-check

1. Go to this page and download the library: Download wookieb/type-check library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wookieb / type-check example snippets


use Wookieb\TypeCheck\SimpleTypeCheck;
use Wookieb\TypeCheck\ObjectTypeCheck;
use Wookieb\TypeCheck\MultipleTypesCheck;

$string = new SimpleTypeCheck('string'); // accepts only string
$exceptions = new ObjectTypeCheck('\Exception'); // accepts every object that is instance of \Exception
$onlyPureExceptions = new ObjectTypeCheck('\Exception', true); // accepts only \Exception objects (not children)
$multi = new MultipleTypesCheck($string, $exceptions);

$string->isValidType('foo'); // true
$string->isValidType(true); // false
echo $string->getTypeDescription(); // strings

$exceptions->isValidType(new \InvalidArgumentException('foo')); // true
$exceptions->isValidType(null); // false
echo $exceptions->getTypeDescription(); // instances of Exception

$onlyPureExceptions->isValidType(new \Exception('foo')); // true
$onlyPureExceptions->isValidType(new \InvalidArgumentException('foo')); // false
echo $onlyPureExceptions->getTypeDescription(); // objects of class Exception

$multi->isValidType(new \InvalidArgumentException('foo')); // true
$multi->isValidType('foo'); // true
$multi->isValidType(array()); // false
echo $multi->getTypeDescription(); // strings, instances of Exception

TypeCheck::strings();
TypeCheck::integers();
TypeCheck::floats();
TypeCheck::objects();
TypeCheck::booleans();
TypeCheck::arrays();
TypeCheck::resources();

use Wookieb\TypeCheck\TraversableOf;
use Wookieb\TypeCheck\TypeCheck;

$check = new TraversableOf(TypeCheck::strings());
$check->isValidType(array(1, 'foo', 3)); // false
$check->isValidType(array('foo', 'bar', 'zee')); // true
echo $check->getTypeDescription(); // traversable structures that contains strings

use Wookieb\TypeCheck\CallbackTypeCheck;

$check = new CallbackTypeCheck(function ($value) {
    return is_array($value) && reset($value) === 'foo';
}, 'arrays with foo string');

$check->isValidType(array('bar')); // false
$check->isValidType(array('foo')); // true
echo $check->getTypeDescription(); // arrays with foo string

use Wookieb\TypeCheck\TraversableOf;
use Wookieb\TypeCheck\TypeCheck;
use Wookieb\TypeCheck\AllChecks;

// narrow the field of "traversable" data types to arrays
$check = new AllChecks(TypeCheck::arrays(), new TraversableOf(TypeCheck::strings()));
$check->isValidType(new ArrayIterator(array('foo', 'bar'))); // false
$check->isValidType(array('foo', 'bar')); // true
echo $check->getTypeDescription(); // arrays traversable structures that contains strings