PHP code example of matthiasmullie / types

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

    

matthiasmullie / types example snippets


use MatthiasMullie\Types;

$type = new Types\Json(
    new Types\Map([
        'user_id' => new Types\Sha1(
            description: 'Unique user id',
        ),
        'email' => new Types\Email(
            description: 'Email address of the user',
        ),
        'gender' => new Types\Enum(
            ['m', 'f'],
            description: 'Biological sex',
        ),
        'birthdate' => new Types\Optional(
            new Types\Integer(),
            description: 'Birth date, UNIX timestamp',
        ),
    ]),
);

// this will succeed because the input is valid;
// `birthdate`, given as a string, will be cast to an integer
$safeInput = $type([
    'user_id' => 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd4',
    'email' => 'jane.doe@example',
    'gender' => 'f',
    'birthdate' => '1715950172',
]);

// this will throw an exception because a an also be used to simply
// check validity instead
$safeInput = $type([
    'user_id' => 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd4',
    'email' => 'jane.doe@example',
    'birthdate' => '1715950172',
]);

// this will throw an exception because the input for `email` is not
// a valid email address
$safeInput = $type([
    'user_id' => 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd4',
    'email' => 'not an email address',
    'gender' => 'f',
    'birthdate' => '1715950172',
]);