PHP code example of stryxx / strict-types

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

    

stryxx / strict-types example snippets


use Stryxx\StrictTypes\Cast;
use Stryxx\StrictTypes\Type;

$name = Type::nonEmptyString($data['name'] ?? null);
$userId = Cast::int($data['id'] ?? null);

$name = Type::string($value);
$id = Type::positiveInt($value);
$items = Type::list($value);
$user = Type::instanceOf($value, User::class);

Type::string(123);      // throws InvalidType
Type::float(1);         // throws InvalidType
Type::positiveInt(0);   // throws InvalidType
Type::array(false);     // throws InvalidType

$ids = Type::listOf(
    [1, 2, 3],
    Type::int(...),
);

Type::listOf(['1', '2'], Cast::int(...)); // throws

Cast::string(123);      // '123'
Cast::int('123');       // 123
Cast::float('12.5');    // 12.5
Cast::bool('false');    // false

Cast::string(true);       // throws InvalidCast
Cast::int('12 items');    // throws InvalidCast
Cast::int(12.5);          // throws InvalidCast
Cast::bool('yes');        // throws InvalidCast

Cast::int(' 123 ');   // 123
Cast::int('+123');    // 123
Cast::int('00123');   // 123

Cast::int('12.0');    // throws InvalidCast
Cast::int('1e3');     // throws InvalidCast
Cast::float('1e3');   // 1000.0

Cast::bool(' FALSE '); // false
Cast::bool('1');       // true
Cast::bool('');        // throws InvalidCast

$result = $connection->executeQuery(
    'SELECT id FROM users WHERE email = :email',
    ['email' => $email],
);

$value = $result->fetchOne();

$userId = false === $value
    ? null
    : Cast::int($value);

$result = $connection->executeQuery(
    'SELECT uuid FROM users WHERE email = :email',
    ['email' => $email],
);

$value = $result->fetchOne();

$userUuid = false === $value
    ? null
    : Type::string($value);

$result = $connection->executeQuery('SELECT COUNT(*) FROM users');
$value = $result->fetchOne();

if (false === $value) {
    throw new UnexpectedValueException('Count query returned no row.');
}

$count = Cast::int($value);

$result = $connection->executeQuery(
    'SELECT id, name FROM users WHERE email = :email',
    ['email' => $email],
);

$row = $result->fetchAssociative();

if (false === $row) {
    return null;
}

$user = new User(
    Cast::int($row['id'] ?? null),
    Type::nonEmptyString($row['name'] ?? null),
);

$result = $connection->executeQuery('SELECT id FROM users');

$ids = Cast::listOf(
    $result->fetchFirstColumn(),
    Cast::int(...),
);

function legacyOption(string $name): mixed
{
    return get_option($name);
}

$enabled = Cast::bool(legacyOption('search_enabled'));
$limit = Type::positiveInt(
    Cast::int(legacyOption('result_limit')),
);

$data = Type::array($response->json());

$id = Cast::int($data['id'] ?? null);
$name = Type::nonEmptyString($data['name'] ?? null);

$ids = Type::listOf(
    $value,
    Type::int(...),
);

$usersById = Type::arrayOf(
    $value,
    static fn(mixed $item): User => Type::instanceOf($item, User::class),
);

$ids = Cast::listOf(['1', '2', '3'], Cast::int(...));

$usersById = Cast::arrayOf(
    $data,
    static fn(mixed $item): User => $resolver->resolve($item),
);

$ids = Cast::listOf('1, 2, 3', Cast::int(...));
$roles = Cast::listOf(
    'admin; editor',
    Type::nonEmptyString(...),
    separator: ';',
);

$user = Type::instanceOf($value, User::class);
$users = Type::instancesOf($value, User::class);

$status = Cast::enum('ready', Status::class);

use Stryxx\StrictTypes\Contract\Resolver;

/**
 * @implements Resolver<User>
 */
final class UserResolver implements Resolver
{
    public function resolve(mixed $value): User
    {
        $data = Type::array($value);

        return new User(
            Cast::int($data['id'] ?? null),
            Type::nonEmptyString($data['name'] ?? null),
        );
    }
}

$user = (new UserResolver())->resolve($payload);

$users = Cast::listOf(
    $payloads,
    $resolver->resolve(...),
);

use Stryxx\StrictTypes\Contract\TargetTypeProvider;

/**
 * @implements TargetTypeProvider<UserResponse>
 */
final class UserRequest implements TargetTypeProvider
{
    public static function targetType(): string
    {
        return UserResponse::class;
    }
}

$request = new UserRequest();

$user = Type::targetOf(
    $serializer->deserialize(
        $payload,
        $request::targetType(),
    ),
    $request,
);

$user = Type::instanceOf(
    $factory->create(User::class),
    User::class,
);

$user = Type::nullable(
    $value,
    static fn(mixed $value): User => Type::instanceOf(
        $value,
        User::class,
    ),
);

$status = Cast::nullable(
    $value,
    static fn(mixed $value): Status => Cast::enum(
        $value,
        Status::class,
    ),
);

use Stryxx\StrictTypes\Exception\InvalidCast;
use Stryxx\StrictTypes\Exception\InvalidType;

use Stryxx\StrictTypes\Exception\StrictTypesException;

try {
    $id = Cast::int($value);
} catch (StrictTypesException $exception) {
    // Handle InvalidType and InvalidCast from this package.
}
bash
composer fix