PHPackages                             flashios09/php-union-types - 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. flashios09/php-union-types

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

flashios09/php-union-types
==========================

A php class for union types

v1.0.3(5y ago)316MITPHPPHP ^7.1

Since Dec 12Pushed 5y ago1 watchersCompare

[ Source](https://github.com/flashios09/php-union-types)[ Packagist](https://packagist.org/packages/flashios09/php-union-types)[ RSS](/packages/flashios09-php-union-types/feed)WikiDiscussions master Synced 6d ago

READMEChangelogDependencies (4)Versions (5)Used By (0)

[![PHP UnionTypes](assets/php-union-types.jpg "PHP UnionTypes")](assets/php-union-types.jpg)

 [ ![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265) ](LICENSE) [ ![Build Status](https://camo.githubusercontent.com/70a1707a255860650df96d3e412acd85bc427106e65e6eb7914c30e8a1bccddc/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f666c617368696f7330392f7068702d756e696f6e2d74797065732f6d61737465722e7376673f7374796c653d666c61742d737175617265) ](https://travis-ci.org/flashios09/php-union-types) [ ![Coverage Status](https://camo.githubusercontent.com/513421d156737685d5d8d3f626549d281a53ac7e89bc52869a48ceeb65a0c695/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f666c617368696f7330392f7068702d756e696f6e2d74797065732f62616467652e7376673f6272616e63683d6d6173746572) ](https://coveralls.io/github/flashios09/php-union-types?branch=master) [ ![Latest Stable Version](https://camo.githubusercontent.com/c72b1ef728ea65468a1b3c5ace00862ca0a1768c01d7619988cfa2f922e138bf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f666c617368696f7330392f7068702d756e696f6e2d74797065732e7376673f7374796c653d666c61742d737175617265266c6162656c3d737461626c65) ](https://packagist.org/packages/flashios09/php-union-types)

Requirements
------------

[](#requirements)

- PHP 7.1+
- Composer

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

[](#installation)

```
composer require flashios09/php-union-types
```

Usage
-----

[](#usage)

#### [UnionTypes::assert](#uniontypes-assert)

[](#uniontypesassert)

```
UnionTypes::assert(mixed $value, string[] $types, array $options = []): void
```

Throw a **TypeError** if the given value isn't in the passed union type.

See the full list of the [valid types](#valid-types) `$types` string array, e.g. `['int', 'string', Posts::class, ...]`.

Examples:

- ```
    UnionTypes::assert(1.2, ['int', 'float']);
    ```

    ✓ should pass
- ```
    UnionTypes::assert('1.2', ['int', 'float']);
    ```

    ✖ will throw a **TypeError** *"'1.2' must be of the union type `int|float`, `string` given"*
- ```
    UnionTypes::assert('1.2', ['int', 'float', 'string']);
    ```

    ✓ should pass
- Check for `instance of`, added on `1.0.2`

    ```
    use \DateTime;

    class Time extends DateTime
    {
      public static function today()
      {
        return new Time();
      }
    }

    $today = Time::today();
    ```

    ```
    // `instanceOf` check is enabled by default
    UnionTypes::assert($today, [\DateTime::class, 'string']);
    ```

    ✓ should pass

    ```
    // disabled using the `instanceOf` option
    UnionTypes::assert($today, [\DateTime::class, 'string', ['instanceOf' => false]]);
    ```

    ✖ will throw a **TypeError** *"object(Time)" must be of the union type `\DateTime|string`, `Time` given"*

#### [UnionTypes::is](#uniontypes-is)

[](#uniontypesis)

```
UnionTypes::is(mixed $value, string[] $types, array $options = []): bool
```

Check if the value type is one of the passed types.

Works just like `UnionTypes::assert($value, $types)` but it will return a **bool**(`true`/`false`) instead of throwing a **TypeError**.

See the full list of the [valid types](#valid-types) `$types` string array, e.g. `['int', 'string', Posts::class, ...]`.

Examples:

- ```
    UnionTypes::is(1.2, ['int', 'float']);
    ```

    equivalent to `is_int(1.2) || is_float(1.2)`

    ✓ return `true`
- ```
    UnionTypes::is('1.2', ['int', 'float']);
    ```

    equivalent to `is_int('1.2') || is_float('1.2')`

    ✖ return `false`
- ```
    UnionTypes::is('1.2', ['int', 'float', 'string']);
    ```

    equivalent to `is_int('1.2') || is_float('1.2') || is_string('1.2')`

    ✓ return `true`
- Check for `instance of`, added on `1.0.2`

    ```
    use \DateTime;

    class Time extends DateTime
    {
      public static function today()
      {
        return new Time();
      }
    }

    $today = Time::today();
    ```

    ```
    // `instanceOf` check is enabled by default
    UnionTypes::assert($today, [\DateTime::class, 'string']);
    ```

    ✓ return `true`

    ```
    // disabled using the `instanceOf` option
    UnionTypes::assert($today, [\DateTime::class, 'string', ['instanceOf' => false]]);
    ```

    ✖ return `false`

#### [UnionTypes::assertFuncArg](#uniontypes-asserfuncarg)

[](#uniontypesassertfuncarg)

```
UnionTypes::assertFuncArg(string $argName, string[] $types, array $options = []): void
```

Throw a **TypesError** if the value of the argument isn't in the union type.

See the full list of the [valid types](#valid-types) `$types` string array, e.g. `int`, `string`, `Posts::class` ...

Examples:

- ```
    function add($a, $b)
    {
        UnionTypes::assertFuncArg('a', ['int', 'float']);
        return $a + $b;
    }
    // invocation
    add(1.2, 1);
    ```

    ✓ should pass
- ```
    class Math
    {
      public static function add($a, $b)
      {
        UnionTypes::assertFuncArg('a', ['int', 'float']);
        return $a + $b;
      }
    }
    // invocation
    Math::add('1.2', 1);
    ```

    ✖ will throw **TypeError** *"Argument `a` passed to `Math::add(int|float $a, ...)` must be of the union type `int|float`, `string` given"*
- ```
    $closure = function ($a, $b) {
        UnionTypes::assertFuncArg('a', ['int', 'float', 'string']);
        return $a + $b;
    };
    // invocation
    $closure('1.2', 1);
    ```

    ✓ should pass
- Check for `instance of`, added on `1.0.2`

    ```
    use \DateTime;

    class Time extends DateTime
    {
      public static function today()
      {
        return new Time();
      }
    }

    $today = Time::today();
    ```

    ```
    $closure = function ($today) {
        // `instanceOf` check is enabled by default
        UnionTypes::assertFuncArg($today, [\DateTime::class, 'string']);
        // some logic here

        return $today;
    };
    // invocation
    $closure($today);
    ```

    ✓ should `pass`

    ```
    $closure = function ($today) {
        // disabled using the `instanceOf` option
        UnionTypes::assertFuncArg($today, [\DateTime::class, 'string', ['instanceOf' => false]]);
        // some logic here

        return $today;
    };
    // invocation
    $closure($today);
    ```

    ✖ will throw a **TypeError** *"object(Time)" must be of the union type `\DateTime|string`, `Time` given"*

#### [Valid types:](#valid-types)

[](#valid-types)

- `'string'`
- `'int'`(not `'integer'` or `'double'`)
- `'float'`(not `'double'` or `'decimal'`)
- `'bool'`(not `'boolean'`)
- `'null'`(not `'NULL'`)
- `'array'`
- Any valid **classname string**, e.g `Table::class` or `'Cake\ORM\Table'`
- `resource`

#### [Configuration](#configuration)

[](#configuration)

- [**Friendly editor file path**:](#friendly-editor-file-path)

    By default, every thrown **Error** or **Exception** will have a **called in** at the end of the message `called in #{stackTraceIndex} {file}:{line}`, e.g. `called in #0 /path/to/app/src/Controller/PostsController.php:126`.

    To have a friendly editor(VSCode, Atom, SublimeText, ...) file path **relative to the workspace**, you need to define a constant `UnionTypes.PATH_TO_APP` somewhere, e.g:

    ```
    // config/bootstrap.php
    define('UnionTypes.PATH_TO_APP', '/path/to/app/');

    // using `$_SERVER`(isn't available in **php cli**)
    $PATH_TO_APP = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR : '';
    define('UnionTypes.PATH_TO_APP', $PATH_TO_APP);
    // using `dirname(__FILE__)`, maybe you need to remove/add some parts, depending on the `__FILE__` location.
    define('UnionTypes.PATH_TO_APP', dirname(__FILE__) . DIRECTORY_SEPARATOR;
    // using the `PWD` key of the `getEnv()` array
    define('UnionTypes.PATH_TO_APP', getEnv()['PWD'] . DIRECTORY_SEPARATOR;
    ```

    Now the `/path/to/app/` **prefix** will be removed from the **called in**, e.g. `called in #0 src/Controller/PostsController.php:126`.

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

[](#contributing)

### Installation

[](#installation-1)

- `git clone git@github.com:flashios09/php-union-types.git`
- `cd php-union-types`
- `composer install`(will install dev dependencies like `whoops`, `kahlan`, `var-dumper`, `cakephp-codesniffer`)

### Start a local php server with livereload

[](#start-a-local-php-server-with-livereload)

- `yarn install`(node dependencies)
- `yarn serve`(then add your code to `php-union-types/index.php` and open a browser window at `http://localhost:3080`)

### Start a local kahlan test with livereload

[](#start-a-local-kahlan-test-with-livereload)

- `yarn install`(node dependencies)
- `yarn test`(it will watch any change in the `spec` folder and re-launch the test)

### Linting

[](#linting)

- `composer cs-check`
- `composer cs-fix`

### Running test

[](#running-test)

- `composer test`

License
-------

[](#license)

This project is licensed under the [MIT License](LICENSE.md).

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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.

###  Release Activity

Cadence

Every ~109 days

Total

4

Last Release

2020d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/53088e2b07980377cfbbdd54fde0d379d2e95449999611e7ddd0357bd8a7c01f?d=identicon)[flashios09](/maintainers/flashios09)

---

Top Contributors

[![flashios09](https://avatars.githubusercontent.com/u/1313482?v=4)](https://github.com/flashios09 "flashios09 (13 commits)")

---

Tags

mixed-typesphpunion-typesunion typestype hintingmixed types

### Embed Badge

![Health badge](/badges/flashios09-php-union-types/health.svg)

```
[![Health](https://phpackages.com/badges/flashios09-php-union-types/health.svg)](https://phpackages.com/packages/flashios09-php-union-types)
```

###  Alternatives

[bpocallaghan/generators

Custom Laravel File Generators with config and publishable stubs.

11965.8k3](/packages/bpocallaghan-generators)[solbianca/yii2-fias

Fias base for your site

142.0k](/packages/solbianca-yii2-fias)

PHPackages © 2026

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