PHP code example of wildphp / type-definitions

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

    

wildphp / type-definitions example snippets


$definition = new \WildPHP\TypeDefinitions\PrimitiveTypeDefinition('string');

echo $definition->validate('this is a valid string'); // true

echo $definition->validate(1); // false
echo $definition->validate(false); // false

$definition = new \WildPHP\TypeDefinitions\PrimitiveTypeDefinition(\WildPHP\TypeDefinitions\PrimitiveTypeDefinition::STRING);

$definition = new \WildPHP\TypeDefinitions\ClassTypeDefinition(stdClass::class);

$object = new stdClass();

echo $definition->validate($object); // true
echo $definition->validate(null); // true

echo $definition->validate('this is a string'); // false
echo $definition->validate(1); // false
echo $definition->validate(false); // false


$childDefinition = new \WildPHP\TypeDefinitions\PrimitiveTypeDefinition('string');
$definition = new \WildPHP\TypeDefinitions\ArrayTypeDefinition($childDefinition);

echo $definition->validate(['this is a valid string', 'another valid string']); // true

echo $definition->validate(1); // false
echo $definition->validate([1]); // false
echo $definition->validate(false); // false
echo $definition->validate([false]); // false
echo $definition->validate(['this is a string', 1]); // false, because 1 does not conform

$map = [
    'array' => ['string'],
    'string' => 'string',
    'stdClass' => stdClass::class
];

$interpreted = \WildPHP\TypeDefinitions\TypeDefinitionInterpreter::createDefinitionMap($map);

// $interpreted['array'] is now an instance of ArrayTypeDefinition with a content definition of PrimitiveTypeDefinition with type 'string'
// $interpreted['string'] is now an instance of PrimitiveTypeDefinition with type 'string'
// $interpreted['stdClass'] is now an instance of ClassTypeDefinition with class identifier stdClass::class

$definition = 'string';

$interpreted = \WildPHP\TypeDefinitions\TypeDefinitionInterpreter::interpret($definition);

// $interpreted is now an instance of PrimitiveTypeDefinition with type 'string'