PHP code example of extended-type-system / type

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

    

extended-type-system / type example snippets


use Typhoon\Type\types;

$data = (new MyAwesomeJsonDecoder())->decode(
    json: '[1, 0.5, "213"]',
    type: types::list(types::numeric),
);

var_dump($data);

use Typhoon\Type\types;

final readonly class GetUserResponse
{
    /**
     * @param non-empty-string $name
     * @param 'user'|'admin' $group
     */
    public function __construct(
        public Uuid $id,
        public string $name,
        public string $group,
    ) {}
}

echo (new MyAwesomeOpenApiGenerator())->generateSchema(types::object(GetUserResponse::class));

use Typhoon\Type\types;

$type = types::unsealedArrayShape([
    'a' => types::nonEmptyString,
    'b' => types::optional(types::union(types::int, types::float)),
    'c' => types::object(Traversable::class, [types::numericString, types::false]),
    'd' => types::callable(
        parameters: [
            types::classConstantMask(PDO::class),
            types::param(types::classTemplate(Generator::class, 'TSend'), hasDefault: true),
            types::param(types::scalar, variadic: true),
        ],
        return: types::void,
    ),
]);

use Typhoon\Type\types;
use function Typhoon\Type\stringify;

var_dump(
   stringify(
       types::Generator(
           key: types::nonNegativeInt,
           value: types::classTemplate(Foo::class, 'T'),
           send: types::scalar,
       ),
   ),
); // Generator<int<0, max>, T#Foo, scalar, mixed>

use Typhoon\Type\Type;
use Typhoon\Type\types;
use Typhoon\Type\Visitor\DefaultTypeVisitor;

/**
 * @extends DefaultTypeVisitor<bool>
 */
final class BasicIntChecker extends DefaultTypeVisitor
{
    public function int(Type $type, Type $minType, Type $maxType): mixed
    {
        return true;
    }

    public function intValue(Type $type, int $value): mixed
    {
        return true;
    }

    public function intMask(Type $type, Type $ofType): bool
    {
        return true;
    }

    protected function default(Type $type): bool
    {
        return false;
    }
}

var_dump(types::positiveInt->accept(new BasicIntChecker())); // true
var_dump(types::callableString()->accept(new BasicIntChecker())); // false

array(3) {
  [0] => int(1)
  [1] => float(0.5)
  [2] => string(3) "213"
}