PHP code example of lezhnev74 / pasvl

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

    

lezhnev74 / pasvl example snippets


// Define the pattern of the data, define keys and values separately
$pattern = [
    '*' => [
        'type' => 'book',
        'title' => ':string :contains("book")',
        'chapters' => [
            ':string :len(2) {1,3}' => [
                'title' => ':string',
                ':exact("interesting") ?' => ':bool',
            ],
        ],
    ],
];

// Provide the data to match against the above pattern.
$data = [
    [
        'type' => 'book',
        'title' => 'Geography book',
        'chapters' => [
            'eu' => ['title' => 'Europe', 'interesting' => true],
            'as' => ['title' => 'America', 'interesting' => false],
        ],
    ],
    [
        'type' => 'book',
        'title' => 'Foreign languages book',
        'chapters' => [
            'de' => ['title' => 'Deutsch'],
        ],
    ],
];

$builder = \PASVL\Validation\ValidatorBuilder::forArray($pattern);
$validator = $builder->build();
try {
    $validator->validate($data);
} catch (ArrayFailedValidation $e) {
    // If data cannot be matched against the pattern, then exception is thrown.
    // It is not always easy to detect why the data failed matching, the exception MAY sometimes give you extra hints.
    echo "failed: " . $e->getMessage() . "\n";
}

$pattern = ":string :regexp('#^[ab]+$#')";
$builder = \PASVL\Validation\ValidatorBuilder::forString($pattern);
$validator = $builder->build();
$validator->validate("abab"); // the string is valid
$validator->validate("abc"); // throws RuleFailed exception with the message: "string does not match regular expression ^[ab]+$"

    $pattern = [":string *" => ":number"];
    // the above pattern matches data:
    $data = ["june"=>10, "aug" => "11"];
  

  $pattern = ["name" => ":any"]; // here the key is the exact value
  $pattern = ["name?" => ":any"]; // here the key is the exact value, can be absent as well
  $pattern = [":exact('name')" => ":any"]; // this is the same
  

  $pattern = ["name" => ":string?"]; // the value must be a string or null
  

  $pattern = ["name" => ":string :regexp('#\d*#')"]; // the value must be a string which contains only digits
  

  $pattern = [":string {2}" => ":any"]; // data must have exactly two string keys
  

  $builder = ValidatorBuilder::forArray($pattern)->withLocator(new MyLocator()); // set your new locator
  $validator = $builder->build();
  

  $data = ["12" => ""];
  $pattern_invalid = [":string" => ""];
  $pattern_valid = [":number :int" => ""];