PHP code example of nexusphp / assert

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

    

nexusphp / assert example snippets




use Nexus\Assert\Assert;

function test(mixed $a, mixed $b, mixed $c): void
{
    Assert::that($a)->isString();
    // $a is now understood as string

    Assert::that($b)->isString()->isNumeric();
    // $b is now understood as numeric string

    Assert::that($c)->isInt()->not()->isNegativeInt();
    // $c is understood as int<0, max>
}




use Nexus\Assert\Assert;

function test(mixed $a): void
{
    Assert::that($a)->isNumeric()->not()->isString();
    // $a is narrowed as either int or float
}




use Nexus\Assert\Assert;

function test(mixed $a): void
{
    Assert::that($a)->nullOr()->isString();
    // $a is now understood as either string or null
}




use Nexus\Assert\Assert;

function test(mixed $a, mixed $b): void
{
    Assert::that($a)->values()->isInt();
    // $a is now understood as iterable<mixed, int>

    Assert::that($b)->keys()->isString();
    // $b is now understood as iterable<string, mixed>
}




use App\Exporter\MyExporter;
use Nexus\Assert\Assert;

Assert::setExporter(new MyExporter());

function foo(mixed $value): void
{
    Assert::that($value)->isBool();
}




use Nexus\Assert\Assert;

function test(mixed $a): void
{
    $message = 'Value "{value}" is not of type string'.
    Assert::that($a)->isString($message);
    // if this fails, the message would be something like:
    // Value "42" is not of type string.
}