sdk-generator / typed-array
Runtime-validated typed collections for PHP 8+: one type, or a union such as int|string.
Requires
- php: >=8.0
- ext-json: *
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^9.6 || ^10.5 || ^11.5 || ^12.5 || ^13.0
Suggests
None
Provides
None
Conflicts
None
Replaces
- typedarray/typedarray: 1.4.0
README
ArrayObject-based typed collections for PHP 8+, validating construction and explicit writes. Native SPL iterator writes and foreach by reference can change the stored type without validation; see the runtime validation contract.
Declaring a type
Extend TypedArray\TypedArray and set $expected_type, or create one without a subclass:
use TypedArray\{TypedArray, IntegerArray, GenericArray}; class UserArray extends TypedArray { protected string $expected_type = User::class; } $ids = new IntegerArray([1, 2]); // ready-made classes for each basic type $mixed = new GenericArray('int|string', [1, 'a']); $users = TypedArray::of(User::class, [$ada]); // the same, as a factory
int|string, User|null and ?int are accepted, as are int, float, bool, callable, iterable and mixed besides the names gettype() uses. Details and the full table: docs/types.md.
Reading and filtering
$ids = new IntegerArray(['a' => 1, 'b' => 2, 'c' => 3]); $ids->isEmpty(); // false $ids->first(); // 1 (null when empty) $ids->last(); // 3 $ids->filter(fn (int $id) => $id > 1); // an IntegerArray: ['b' => 2, 'c' => 3] $ids->map(fn (int $id) => "#$id"); // a plain array: ['a' => '#1', ...] $ids->toArray(); // the items as a plain array $ids->accepts('x'); // false, never throws
filter() returns a collection of the same class and type, keys preserved; map() returns a plain array because its results need not be of the declared type.
Installation
Composer
To install the library, execute the following code:
composer require sdk-generator/typed-array
Manual
Download the library from https://github.com/sdk-generator/typed-array
Include all the files from the "installation path/src"
function autoload($path) {
$items = glob($path . DIRECTORY_SEPARATOR . "*");
foreach($items as $item) {
$isPhp = pathinfo($item) ["extension"] === "php";
if (is_file($item) && $isPhp) {
require_once $item;
} elseif (is_dir($item)) {
autoload($item);
}
}
}
autoload($installation_path . DIRECTORY_SEPARATOR . 'src');
Examples of Usage
Are you sick of typing your arrays with comments that are working in your IDEs, but your code still allows mixed values?
Here are some examples demonstrating how to use the library:
Define a Custom Typed Array
Here is a simple solution to this problem.
Instead of typing your arrays like:
/* @var int[] */ $my_int_array = [];
You can select a default typed array. For example:
<?php use TypedArray\IntegerArray; $intArray = new IntegerArray(); $intArray[] = 10; // Valid $intArray[] = 20; // Valid // $intArray[] = "Hello"; // This will throw a TypeError
Default valid types are:
- TypedArray\ArrayArray
- TypedArray\BooleanArray
- TypedArray\DoubleArray
- TypedArray\FloatArray (the same as DoubleArray, named as PHP names the type)
- TypedArray\IntegerArray
- TypedArray\ObjectArray
- TypedArray\ResourceArray
- TypedArray\StringArray
Working With Class Typed Arrays
You can also create a typed array that accepts only objects of a specific class type.
Extend from TypedArray\TypedArray and pass the class::name to the protected property expected type. For example:
<?php use TypedArray\TypedArray; use Examples\MyCustomClass; // Assuming this class is defined elsewhere in your project class MyCustomClassArray extends TypedArray { protected string $expected_type = MyCustomClass::class; } /* @var MyCustomClass[] */ $objectArray = new MyCustomClassArray(); $object1 = new MyCustomClass(); $object2 = new MyCustomClass(); $objectArray[] = $object1; // Valid $objectArray[] = $object2; // Valid // $objectArray[] = new SomeOtherClass(); // This will throw a TypeError
Also works with extended classes
<?php class User { public string $name; public string $email; public function __construct(string $name, string $email) { $this->name = $name; $this->email = $email; } } class InvalidClass { } class AdminUser extends User { } class UserArray extends TypedArray { protected string $expected_type = User::class; } // Example of usage without keys $userArray = new UserArray([ new User('John Doe', 'john@example.com'), new User('Jane Smith', 'jane@example.com'), new AdminUser('Admin User', 'admin@example.com'), ]); $userArray[] = new User('Alice Johnson', 'alice@example.com'); // Example of usage with keys $keyedUserArray = new UserArray([ 'admin' => new AdminUser('Admin User', 'admin@example.com'), 'editor' => new User('Editor User', 'editor@example.com'), ]); $keyedUserArray['viewer'] = new User('Viewer User', 'viewer@example.com'); // Example of invalid value $invalidUserArray = new UserArray([ 'invalid-value', // This will throw a TypeError new InvalidClass(), // This will throw a TypeError ]);
Handle Exceptions
When a value doesn't meet the validation rules, an exception is thrown. You can handle it as follows:
<?php try { $intArray[] = "Invalid Value"; } catch (TypeError $TypeError) { echo "Caught exception: " . $TypeError->getMessage(); // Validation error message }
License
Released under the MIT License. Copyright (c) 2024-2026 David Moreno Falero.
Contributing and maintenance
Contributions and bug reports are welcome. Please read CONTRIBUTING.md for the branching workflow, compatibility expectations, and local checks.
The stable Composer package is currently sdk-generator/typed-array. The master branch and Git version tags are used for stable releases; develop is used for ongoing development. Automated PHPUnit tests and continuous integration are configured on develop. A manual release workflow is staged on develop; production publication requires branch protections, a protected release environment and explicit approval.
Tests and continuous integration
Install development dependencies and run the PHPUnit suite:
composer install
composer test
The CI workflow validates Composer metadata, checks PHP syntax, and runs PHPUnit on PHP 8.0 through 8.5 for pushes and pull requests targeting develop or master.
The KnownLimitationsTest.php suite documents the intentionally writable SPL paths with executable tests: getIterator(), external ArrayIterator wrappers, and foreach by reference. The runtime validation contract defines exactly which writes are checked.
More documentation
- Typed SDK object collections
- Compatibility and type-safety limits
- Maintainer release process
- Security policy
- Changelog
Run composer analyse for static analysis. CI enforces at least 95% line coverage of the currently included source and generates a downloadable coverage report. The CI workflow reports the authoritative status for each PHP version.