PHP code example of slevomat / consistence

1. Go to this page and download the library: Download slevomat/consistence 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/ */

    

slevomat / consistence example snippets




class CardColor extends \Consistence\Enum\Enum
{

	public const BLACK = 'black';
	public const RED = 'red';

}

$red = CardColor::get(CardColor::RED);

$availableValues = CardColor::getAvailableValues(); // ['black', 'red']

function doMagicTrick(CardColor $guessedCardColor)
{
	// ...
}



class Foo extends \Consistence\ObjectPrototype
{

}

$foo = new Foo();

// \Consistence\UndefinedPropertyException: Property Foo::$bar is not defined or is not accessible
$foo->bar = 'bar';



use Consistence\Type\Type;

Type::checkType('foo', 'string');
Type::checkType('foo', 'string|int');
Type::checkType(1, 'string|int');
Type::checkType(
	[
		[
			'foo',
		],
		[
			'bar',
		],
	],
	'string[][]'
);



use Consistence\Time\TimeFormat;

// example of strict validation of format:

// H H:i"
TimeFormat::createDateTimeFromFormat('H:i', '2:30');

// example of strict validation of values:

// there is no 25th hour in the day
// \Consistence\Time\TimeDoesNotExistException: Time given in "25:00" does not exist
TimeFormat::createDateTimeFromFormat('H:i', '25:00');



$haystack = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];
foreach ($haystack as $value) {
	if (strlen($value) < 5) {
		// do something with value
	}
}



use Consistence\Type\ArrayType\ArrayType;

$haystack = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];
$value = ArrayType::findValueByCallback($haystack, function($value) {
	return strlen($value) < 5;
});
if ($value !== null) {
	// do something with value
}