Download the PHP package stryxx/strict-types without Composer
On this page you can find all versions of the php package stryxx/strict-types. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download stryxx/strict-types
More information about stryxx/strict-types
Files in stryxx/strict-types
Package strict-types
Short Description A lightweight library that helps enforce and maintain predictable types in PHP 8.1+ applications.
License MIT
Homepage https://github.com/stryxx/strict-types
Informations about the package strict-types
Strict Types
A small PHP library for checking values and making clear conversions at runtime.
This package does not replace or change PHP's declare(strict_types=1).
It is useful when a value comes from a place with a broad return type, for example:
- Doctrine DBAL,
- an external API or SDK,
- old or dynamic code,
- JSON, cache, configuration, or plugin data,
- any method that returns
mixed,object,array<mixed>, or another broad type.
The main API has two classes:
Typechecks values and returns them without changing them,Castconverts values using documented rules.
The optional Resolver<T> and TargetTypeProvider<T> contracts carry object types through generic code. They are tested with PHPStan and can also improve type hints and code completion in PhpStorm.
Installation
Basic use
Both return the expected type. Wrong values cause an exception.
Type
Type checks that a value already has the expected type. It does not convert it.
Wrong values are rejected:
Collection helpers also keep the original values. Their callback must check and return the same value:
This is not a conversion helper:
Use Cast::listOf() when items must be converted.
Cast
Cast converts a value only when it matches a documented rule. It rejects partial values, non-finite floats, and values that do not match a clear conversion rule.
Unsafe or unclear conversions are rejected:
For booleans, the library accepts only the values listed below. It does not use PHP's automatic boolean conversion.
Conversion rules
| Method | Accepted values |
|---|---|
Cast::string() |
strings, integers, finite floats, and Stringable objects |
Cast::int() |
integers, decimal integer strings, and finite whole floats inside the PHP integer range |
Cast::float() |
finite floats, integers that can be converted to float and back without changing the integer, and finite numeric strings |
Cast::bool() |
booleans, integers 0 and 1, and the strings 0, 1, true, and false |
Whitespace, a sign, and leading zeroes are allowed in integer strings:
Decimal and exponent strings are not integers:
Boolean strings are trimmed and are not case-sensitive:
A finite float is any float other than INF, -INF, or NAN. These special values can appear after an overflow or an invalid math operation.
Float conversions use normal PHP float behavior and precision.
Doctrine DBAL examples
Doctrine DBAL uses broad return types because the exact PHP value can depend on the query and database driver.
The Doctrine\DBAL\Result class has methods such as:
fetchOne(): mixed,fetchAssociative(): array<string, mixed>|false,fetchFirstColumn(): list<mixed>.
fetchOne() returns the first value from the next row. It returns false when there are no more rows.
For a string column, verify the value instead of casting it:
When a row must exist, handle false before converting the value:
fetchAssociative() already tells you that a row can be missing:
fetchFirstColumn() returns a list, but every item is still mixed:
The application decides what a missing row means. The library only checks or converts the value after that decision.
Legacy and vendor code
The whole project does not need to be strict. You can add a checked boundary only around new code.
After this point, the new code receives a real bool and a positive int.
The same idea works with API responses:
Arrays and lists
Type::arrayOf() and Type::listOf() check every item and keep the original values.
arrayOf() keeps the original keys. listOf() requires a list with sequential keys.
Use the Cast versions when the callback should change the values:
The second example uses a resolver as the collection callback. See Resolvers.
Cast::listOf() can also read a comma-separated string. The separator can be changed:
An empty source string becomes an empty list. Empty items such as 1,,2 are rejected.
Objects and enums
You can verify one object or a list of objects:
You can also convert backed enum values:
Resolvers
Resolver<T> is useful when one class maps unknown data into a known result type.
Use the resolver directly:
Because resolve() has a native User return type, PHPStan and PhpStorm know that $user is a User. The Resolver<User> annotation keeps this type when the resolver is passed through generic code.
Resolvers can also be used with collection casts:
Target type providers
TargetTypeProvider<T> connects an object with its expected result type.
A serializer or factory can use the provided class. Type::targetOf() then verifies the returned object:
For a direct class name, use Type::instanceOf():
Nullable values
Use nullable() when null is allowed and there is no dedicated nullable helper for the target type.
For example, Type::nullable() can verify a nullable object:
Cast::nullable() can convert a nullable value into a custom type:
For common scalar types, use helpers such as nullableString(), nullableInt(), nullableFloat(), or nullableBool().
Exceptions
The package uses two main exceptions:
Both implement StrictTypesException:
The package does not wrap exceptions thrown by your callbacks or resolvers.
Passing a callback that changes a value to a Type collection or nullable helper is an invalid argument.
Static analysis
Static analysis is optional. The package works at runtime without PHPStan.
PHP enforces native return types. Refined and generic PHPDoc types are tested with PHPStan. PhpStorm can also use many of them for type hints and code completion, but its support is not identical to PHPStan.
PHPStan can understand types such as:
When a package method promises a refined PHPDoc type, its runtime check matches that promise.
Requirements
- PHP 8.1 or newer
PHP 8.1 support is kept mainly for older projects. For new projects, use a currently supported PHP version.
Examples
The examples/ directory contains runnable examples.
Run all of them with:
Development
Install development dependencies:
Run all checks:
Apply automatic fixes:
License
MIT. See LICENSE.