PHPackages                             rayblair/type-safety - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rayblair/type-safety

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

rayblair/type-safety
====================

Type Safety is a PHP package that enforces strict type safety when working with mixed arrays and variables.

15[3 PRs](https://github.com/rayblair06/type-safety/pulls)PHPCI passing

Since Nov 24Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/rayblair06/type-safety)[ Packagist](https://packagist.org/packages/rayblair/type-safety)[ RSS](/packages/rayblair-type-safety/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (5)Used By (0)

Type Safety
===========

[](#type-safety)

**Type Safety** is a PHP package that enforces strict type safety when working with mixed arrays and variables. It provides an `ArrayType` class for defining strongly-typed arrays, along with a helper method to validate primitive types, object instances, and basic arrays at runtime. By ensuring that only instances of the specified type can be added to variables or arrays, this package helps maintain strong typing throughout your application, improving data integrity and supporting static analysis to reduce type ambiguity.

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require rayblair/type-safety
```

Usage
-----

[](#usage)

Below are some examples demonstrating how to use the `Type Safety` package for type-checking variables and creating type-safe arrays.

### Type Checking for Variables

[](#type-checking-for-variables)

The `type()` function ensures that a variable matches a specific type. If the type doesn't match, a `TypeError` is thrown.

#### Example Usage:

[](#example-usage)

```
// Class Type Checking
$classInstance = new FooType(1, 'Ray');
$classInstance = type($classInstance, FooType::class);

// String Type Checking
$string = 'Foo';
$string = type($string, Type::STRING);

// Integer Type Checking
$integer = 1;
$integer = type($integer, Type::INTEGER);

// Float Type Checking
$float = 1.23;
$float = type($float, Type::FLOAT);

// Boolean Type Checking
$boolean = true;
$boolean = type($boolean, Type::BOOLEAN);

// Array Type Checking
$array = [1, 2, 3, 4];
$array = type($array, Type::ARRAY);
```

### Creating Type-Safe Arrays

[](#creating-type-safe-arrays)

You can also create arrays that enforce type safety for their elements. In this example, we'll demonstrate how to create a custom object and ensure the array only holds instances of that object.

#### Step 1: Define a Class

[](#step-1-define-a-class)

First, define a class to represent the objects you want to store in the array. For example, we'll define a `FooType` class with `id` and `name` properties.

```
class FooType
{
    public function __construct(public int $id, public string $name)
    {}
}
```

#### Step 2: Define a Type-Safe Array

[](#step-2-define-a-type-safe-array)

Next, extend the `ArrayType` class and specify the object type that the array will contain. In this case, we define a `FooArrayType` class that will hold `FooType` objects.

```
class FooArrayType extends ArrayType
{
    public $type = FooType::class;
}
```

#### Step 3: Constructing Type Safe Arrays

[](#step-3-constructing-type-safe-arrays)

Once your type-safe array is set up, you can pass safely pass values in a number of ways that will validate that each value matches the defined type.

##### 3.1: Constructor

[](#31-constructor)

```
$array = new FooArrayType([
    ['id' => 1, 'name' => 'Ray'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Alice']
]);

print_r($array->toArray());
```

### Output:

[](#output)

```
[
    ['id' => 1, 'name' => 'Ray'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Alice'],
]
```

##### 3.2: Appends

[](#32-appends)

```
$array = new FooArrayType();

$array[] = ['id' => 1, 'name' => 'Ray'];
$array[] = ['id' => 2, 'name' => 'Bob'];
$array[] = ['id' => 3, 'name' => 'Alice'];

print_r($array->toArray());
```

### Output:

[](#output-1)

```
[
    ['id' => 1, 'name' => 'Ray'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Alice'],
]
```

##### 3.3: Offset

[](#33-offset)

```
$array = new FooArrayType();

$array[0] = ['id' => 1, 'name' => 'Ray'];
$array[1] = ['id' => 2, 'name' => 'Bob'];
$array[2] = ['id' => 3, 'name' => 'Alice'];

print_r($array->toArray());
```

### Output:

[](#output-2)

```
[
    ['id' => 1, 'name' => 'Ray'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Alice'],
]
```

Handling Invalid Data
---------------------

[](#handling-invalid-data)

The `ArrayType` class enforces strict type safety, which means that any invalid data will trigger exceptions.

### Example 1: Invalid Type

[](#example-1-invalid-type)

If you attempt to add an item where the `id` is not an integer, a `TypeError` will be thrown.

```
$array = new FooArrayType();

// This will throw a TypeError because 'id' should be an integer.
$array[] = ['id' => '4', 'name' => 'Dave'];
```

### Example 2: Missing Parameters

[](#example-2-missing-parameters)

If you omit a required parameter, such as `id`, an `ArgumentCountError` will be thrown.

```
$array = new FooArrayType();

// This will throw an ArgumentCountError because 'id' is missing.
$array[] = ['name' => 'Gary'];
```

Testing
-------

[](#testing)

To run the test suite and ensure everything is working as expected, use the following command:

```
composer test
```

Changelog
---------

[](#changelog)

For details on recent changes and updates, please refer to the [CHANGELOG](CHANGELOG.md).

Contributing
------------

[](#contributing)

We welcome contributions! Please refer to our [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) guidelines for more information.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover any security-related issues, please review our [security policy](../../security/policy) for instructions on how to report vulnerabilities.

Credits
-------

[](#credits)

- [Ray Blair](https://github.com/rayblair)
- [All Contributors](../../contributors)

License
-------

[](#license)

This package is open-source and licensed under the MIT License. For more information, please see the [LICENSE file](LICENSE.md).

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance60

Regular maintenance activity

Popularity5

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity18

Early-stage or recently created project

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/ab35ad2244c1203e3b7f0fdbe2d765fcdcf92c4b51cddee2b82e522c841f4650?d=identicon)[rayblair06](/maintainers/rayblair06)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")[![rayblair06](https://avatars.githubusercontent.com/u/16214725?v=4)](https://github.com/rayblair06 "rayblair06 (1 commits)")

### Embed Badge

![Health badge](/badges/rayblair-type-safety/health.svg)

```
[![Health](https://phpackages.com/badges/rayblair-type-safety/health.svg)](https://phpackages.com/packages/rayblair-type-safety)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
