jmf/type-validation

Allows to check if a variable is of the expected type, using a type specification string like the ones in PHPDoc blocks (int, \Foo\Bar[], null|string, etc).

4.0.0 2023-07-01 16:53 UTC

This package is auto-updated.

Last update: 2024-10-30 02:26:52 UTC


README

This package allows to check if a variable is of the expected type, using a type specification string like the ones in PHPDoc blocks.

Type specifications strings can be like the following:

- integer
- scalar
- mixed
- string
- float[]
- int[][]
- {string:float}
- {int:\My\Stuff}
- {int:string}[]
- resource
- int|string
- {string:{int:\My\Stuff|int[]}}[]

etc.

Usage

Static validation with exceptions

<?php

use Jmf\TypeValidation\Type;

// Valid, will not throw an exception.
Type::mustBe('string', 'foo');

// Invalid, will throw an exception.
Type::mustBe('string', 123);

Static validation with booleans

<?php

use Jmf\TypeValidation\Type;

$variable = 'foo';

if (Type::is('string', $variable)) {
	// Valid
} else {
	// Invalid
}

Concrete validation

You can also use a concrete instance of a type validator.

<?php

use Jmf\TypeValidation\TypeValidator;

$validator = new TypeValidator();

$variable = 'foo';

if ($validator->isValid('string', $variable)) {
	// Valid
} else {
	// Invalid
}

Typical use

<?php

namespace App;

use Jmf\TypeValidation\Type;

class PotatoPeeler
{
    /**
     * @param Potato[] $potatoes
     */
    public function peel(array $potatoes): void
    {
        Type::mustBe('\App\Potato[]', $potatoes);

        // ...
    }
}