PHP code example of le0daniel / typescript-schema

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

    

le0daniel / typescript-schema example snippets


use TypescriptSchema\Definition\Schema;

$userType = Schema::object([
    'name' => Schema::string()->nonEmpty()->minLength(1)->maxLength(255),
    'email' => Schema::string()->email()->endsWith('.com')
]);

$userType->toDefinition()->input() // JsonSchema => ['type' => 'object', 'properties' => ['name' => ['type' => 'string'], 'email' => ['type' => 'string']], (...)]
$userType->toDefinition()->output() // JsonSchema => ['type' => 'object', 'properties' => ['name' => ['type' => 'string'], 'email' => ['type' => 'string']], (...)]

$schema = Schema::make($userType);
$schema->parse(['name' => 'The name', 'email' => '[email protected]', 'other']);
// => Result<['name' => 'The name', 'email' => '[email protected]']>

$schema->parse(['name' => 'The name', 'email' => 'INVALID', 'other']);
// => Result<Value::INVALID>

$schema->parseOrFail(['name' => 'The name', 'email' => 'INVALID', 'other']);
// => throws ParsingException

$schema->parseOrFail(['name' => 'The name', 'email' => '[email protected]', 'other']);
// => ['name' => 'The name', 'email' => '[email protected]']


use TypescriptSchema\Utils\Typescript;
use TypescriptSchema\Definition\Schema;
use TypescriptSchema\Data\Options;

$schema = Schema::object(['name' => Schema::string()])->toSchema();
$result = $schema->parse(['name' => 'Test name'])->castInto(Person::class);

use TypescriptSchema\Utils\Typescript;
use TypescriptSchema\Definition\Schema;

$schema = Schema::make(
    Schema::object([
        'id' => Schema::int()->min(1),
        'name' => Schema::string(),
    ])
);

Typescript::fromJsonSchema($schema->toDefinition()->output());
// => {id:number;name:string}

use TypescriptSchema\Definition\Schema;

enum MyEnum {
    case SUCCESS;
    case FAILURE;
}

$type = Schema::enum(MyEnum::class);

$type->toDefinition()->input()                // => 'SUCCESS'|'FAILURE'
$type->toDefinition()->output()               // => 'SUCCESS'|'FAILURE'

// Parsing always returns the Enum case itself.
Schema::make($type)->parse(MyEnum::SUCCESS) // => MyEnum::SUCCESS
Schema::make($type)->parse('SUCCESS') // => MyEnum::SUCCESS

// Parsing as strings always returns the string with the enum name.
Schema::make($type)->serialize('SUCCESS') // => 'SUCCESS'
Schema::make($type)->serialize(MyEnum::SUCCESS) // => 'SUCCESS'

use TypescriptSchema\Definition\Schema;

$type = Schema::make(Schema::any());
$type->parse(null) // => Result<null>
$type->parse('string') // => Result<'string'>
$type->parse((object) []) // => Result<object{}>
$type->parse([]) // => Result<array{}>

use TypescriptSchema\Definition\Schema;
use \TypescriptSchema\Utils\Typescript;

$user = Schema::object([
    'name' => Schema::string(),
]);

Typescript::fromJsonSchema($user->toDefinition()->input())  // => {name: string;}
Typescript::fromJsonSchema($user->toDefinition()->output()) // => {name: string;}

use TypescriptSchema\Definition\Complex\Field;use TypescriptSchema\Definition\Schema;
use TypescriptSchema\Definition\Schema;

$user = Schema::object([
    'fullName' => Field::ofType(Schema::string())
        ->resolvedBy(fn(User $user): string => $user->fullName()),
]);

use TypescriptSchema\Definition\Complex\Field;
use TypescriptSchema\Definition\Schema;

$user = Schema::object([
    'fullName' => Field::ofType(Schema::string())
        ->resolvedBy(fn(User $user): string => $user->fullName())
        ->describe('The combination of title, first and last name')
        ->deprecated('Use lastName, firstName and title to compute manually', DateTime::createFromFormat('Y-m-d', '2024-05-25')),
]);

use TypescriptSchema\Contracts\Type;
use TypescriptSchema\Definition\Shared\Nullable;
use TypescriptSchema\Definition\Shared\Refinable;
use TypescriptSchema\Definition\Shared\Transformable;
use TypescriptSchema\Definition\Shared\Validators;
use TypescriptSchema\Helpers\Context;
use TypescriptSchema\Data\Enum\Value;
use TypescriptSchema\Exceptions\Issue;

final class MyCustomType implements Type {
    use Nullable, Refinable, Transformable, Validators;

    public function toDefinition(): SchemaDefinition {
        return new \TypescriptSchema\Data\Schema\Definition(
            ['type' => 'string'],
            ['type' => 'string'],
        );
    }

    public function serializeValue(mixed $value, Context $context): Value|string {
        if (!is_string($value)) {
            $context->addIssue(Issue::custom('Value must be a string.'));
            return Value::INVALID;
        }
        
        if (!$this->runValidators($value, $context)) {
            return Value::INVALID;
        }
        
        return $value;
    }
    
    public function minLength(): MyCustomType {
        return $this->addValidator(function (string $value) {
            return strlen($value) > 5;
        });
    }
}