PHP code example of phpexperts / datatype-validator

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

    

phpexperts / datatype-validator example snippets


// 1. Pick a Type Checker (IsAFuzzyDataType or IsAStrictDataType).
//    * IsAFuzzyDataType tries its best to emulate PHP's `==`.
//    * IsAStrictDataType observes PHP's `strict_types=1` rules.
    $validator = new DataValidator(new IsAStrictDataType());

// There are two powerful mechanisms out of the box:
// 2. It is easy to validate any data type dynamically, without a ton of if statements.

    $validator->isType('asdf', 'string'); // true or false.
    $validator->assertIsType(1, 'int'); // null or throws InvalidDataTypeException

// 3. You can also validate arrays:

    $data = [
        'name'     => 'Cheyenne',
        'age'      => 22,
        'birthday' => Carbon::parse('1996-12-04 15:15:15'),
        'daysOld'  => 8194.35,
        'today'    => Carbon::now(),
        'sayHi'    => function () { return 'Hi!'; },
    ];
    
    $rules = [
         'name'     => 'string',
         'age'      => 'int',
         'birthday' => 'Carbon',
         'daysOld'  => 'float',
         'today'    => 'Carbon\Carbon',
         'sayHi'    => 'callable',
     ];

    $validator->validate($data, $rules);

// 4. DataValidator::validate() will return `true` on success or throw 
//    an `InvalidDataTypeException` that contains an array of errors:

    $data = [
        'name'     => 'Cheyenne',
        'age'      => '22',
        'birthday' => '1996-12-04 15:15:15',
    ];
    
    try {
        $validator->validate($data, $rules);
    } catch (InvalidDataTypeException $e) {
        print_r($e->getReasons());

        /* Output:
        array:2 [
          0 => "age is not a valid int"
          1 => "birthday is not a valid Carbon"
        ]
        */
    }

// 5. It can validate objects based on their short name or full name.
    $data = [
        'yesterday' => \Carbon\Carbon::parse('2019-05-11'),
        'tomorrow'  => \Carbon\Carbon::parse('2019-05-13'),
    ];
    
    $validator->validate($data, [
        'yesterday' => '\Carbon\Carbon',
        'tomorrow'  => 'Carbon',
    ]);