PHP code example of stougeiro / schema

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

    

stougeiro / schema example snippets


$schema = new Schema([
    'email' => 'string',
    'amount' => 'float',
]);

// Structure first
if ( ! $schema->validate($data, $error)) {
    return response(422, $error);
}

// Business logic second
$email = EmailService::validate($data['email']);

use STDW\Schema\Schema;

$schema = new Schema([
  'name' => 'string',
  'age' => 'int',
]);

$payload = [
  'name' => 'Sidney',
  'age' => 42,
];

$schema->validate($payload); // true

/**
 * Using the global schema() helper (optional)
 * 
 * For convenience, you may use the global schema() helper
 * instead of instantiating Schema manually.
 * It behaves exactly the same, but makes nested definitions easier to read
 * */

$schema = schema([
  'id' => 'int',
  'name' => 'string',
  'email' => 'string',
  'status' => 'enum(active|inactive|pending)',
  'metadata' => schema([
    'ip' => 'string',
    'userAgent' => 'string:o',
  ])->optional(),
]);

$payload = [
  'id'     => 1,
  'name'   => 'Sidney',
  'email'  => '[email protected]',
  'status' => 'active',
  'metadata' => [
    'ip' => '127.0.0.1',
  ],
];

$schema->validate($payload); // true

use STDW\Schema\Schema;

$schema = new Schema([
  'name' => 'string',
  'age'  => 'int',
]);

$payload = [
  'name' => 'Sidney',
  'age'  => '12',
];

if ( ! $schema->validate($payload, $error)) {
  echo $error; // Invalid 

$schema = new Schema([
  'template' => 'enum(user|product|payment)',
  'user' => new Schema([
    'id'    => 'int',
    'name'  => 'string',
    'email' => 'string',
  ]),
]);

$payload = [
  'template' => 'user',
  'user' => [
    'id'    => '12',
    'name'  => 'Sidney',
    'email' => '[email protected]',
  ],
];

if ( ! $schema->validate($payload, $error)) {
  echo $error; // Invalid