PHP code example of j0hnys / trident-typed

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

    

j0hnys / trident-typed example snippets


// This collection will only allow objects of type `Post` in it.
$postCollection = new Collection([new Post()]);

// This tuple will keep its signature of (Point, Point).
$vector = new Tuple(new Point(30, 5), new Point(120, 0));

// This struct's fields are autmoatically type checked.
$struct = [
    'foo' => new Post(),
    'bar' => function () {
        // ...
    },
];

$list = new Collection(T::bool());

$list[] = new Post(); // TypeError

$list = (new Collection(T::string()))->set(['a', 'b', 'c']);

$list = new IntegerList([1, 4]);

$list[] = 'a'; // TypeError

$map = new Map(T::string(),T::integer());

$map['name'] = 1;

$map[] = new Post(); // TypeError
$map[] = 1; // TypeError

$map = (new Map(T::string(),T::integer()))->set(['a'=>2]);

$postList = new Collection(T::generic(Post::class));

$postList[] = 1; // TypeError

$point = new Tuple(T::float(), T::float());

$point[0] = 1.5;
$point[1] = 3;

$point[0] = 'a'; // TypeError
$point['a'] = 1; // TypeError
$point[10] = 1; // TypeError

$tuple = (new Tuple(T::string(), T::array()))->set('abc', []);

$developer = new Struct([
    'name' => T::string(),
    'age' => T::int(),
    'second_name' => T::nullable(T::string()),
]);

$developer['name'] = 'Brent';
$developer['second_name'] = 'John';

$developer->set([
    'name' => 'BrenDt',
    'age' => 23,
    'second_name' => null,
]);

echo $developer->age;

$developer->name = 'Brent';

$developer->age = 'abc' // TypeError
$developer->somethingElse = 'abc' // TypeError

$list1 = new Collection(T::int()->nullable());

$list2 = new Collection(T::nullable(T::int()));

$list = new Collection(T::union(T::int(), T::float()));

$list[] = 1;
$list[] = 1.1;

$list[] = 'abc'; // TypeError

$postList = new Collection(T::generic(Post::class));

$postList[] = new Post();
$postList[] = 1; // TypeError 

use J0hnys\Typed\Type;
use J0hnys\Typed\Types\Nullable;

class PostType implements Type
{
    use Nullable;
    
    public function validate($post): Post
    {
        return $post;
    }
}

$postList = new Collection(new PostType());

class T extends J0hnys\Typed\T
{
    public static function post(): PostType
    {
        return new PostType();
    }
}

// ...

$postList = new Collection(T::post());

public function nullable(): NullType
{
    return new NullType($this);
}

class Coordinates extends Tuple
{
    public function __construct(int $x, int $y)
    {
        parent::__construct(T::int(), T::int());

        $this[0] = $x;
        $this[1] = $y;
    }
}