plook / type-guard
Library to ensure correctness of types with a readable interface.
Installs: 1 295
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.2
Requires (Dev)
- brainbits/phpcs-standard: ^7.0
- ergebnis/phpstan-rules: ^2.2.0
- phpstan/phpstan: ^1.10.58
- phpstan/phpstan-phpunit: ^1.3.15
- phpunit/phpunit: ^11.0.3
- rector/rector: ^1.0.1
- squizlabs/php_codesniffer: ^3.9.0
- thecodingmachine/phpstan-safe-rule: ^1.2.0
- thecodingmachine/phpstan-strict-rules: ^1.0.0
README
A PHP library to ensure correctness of types providing a readable interface.
Installation
$ composer require plook/type-guard
Example
use function Plook\TypeGuard\asBool; use function Plook\TypeGuard\asDateTimeImmutable; use function Plook\TypeGuard\asFloat; use function Plook\TypeGuard\asInt; use function Plook\TypeGuard\asString; use function Plook\TypeGuard\notNull; $row = $this->fetchProjectRow(123); $project = new Project( notNull(asInt($row['id'])), notNull(asString($row['name'])), notNull(asDateTimeImmutable($row['createdAt'])), notNull(asBool($row['is_assigned'])), asDateTimeImmutable($row['closedAt']), asFloat($row['rating']), );
Provided helper functions
Ensure Types
asBool($value)
Converts input value to a boolean, but passesnull
.asFloat($value)
Converts input value to a float, but passesnull
.asInt($value)
Converts input value to a int, but passesnull
.asDateTimeImmutable($value)
Converts input value to aDateTimeImmutable
object, but passesnull
.asDateTimeString($value)
Converts input value to a date string including the timezone, but passesnull
.asString($value)
Converts input value to a string, but passesnull
.
Assertions
notNull($value)
Throws an exception if the value isnull
otherwise it passes the original value.
Configuration
Setting the default target time zone of DateTimeImmutable
objects
use Plook\TypeGuard\TypeGuard; TypeGuard::instance()->timeZone('Australia/Adelaide'); TypeGuard::instance()->timeZone(new DateTimeZone('Australia/Adelaide'));
Setting the default format of date time strings
use Plook\TypeGuard\TypeGuard; TypeGuard::instance()->dateTimeFormat(DateTimeInterface::ATOM);