PHPackages                             nejcc/php-datatypes - 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. nejcc/php-datatypes

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

nejcc/php-datatypes
===================

PHP Data types

v1.0.10(1y ago)802.3k51MITPHPPHP ^8.2CI failing

Since Oct 2Pushed 3w ago4 watchersCompare

[ Source](https://github.com/Nejcc/php-datatypes)[ Packagist](https://packagist.org/packages/nejcc/php-datatypes)[ Docs](https://github.com/nejcc/php-datatypes)[ RSS](/packages/nejcc-php-datatypes/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (2)Versions (16)Used By (1)

PHP Datatypes: Strict, Safe, and Flexible Data Handling for PHP
===============================================================

[](#php-datatypes-strict-safe-and-flexible-data-handling-for-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/30822ce3e8e1cbc5d76e28db0db7801a68478a42ed4d7fd57d40810217bf5b13/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e656a63632f7068702d6461746174797065732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nejcc/php-datatypes)[![Total Downloads](https://camo.githubusercontent.com/76dd6a7f7c9b31f3851a892203754976df4aad368761b6c2518ad2b1fd83e260/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e656a63632f7068702d6461746174797065732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nejcc/php-datatypes)[![GitHub Actions](https://github.com/nejcc/php-datatypes/actions/workflows/main.yml/badge.svg)](https://github.com/nejcc/php-datatypes/actions/workflows/main.yml/badge.svg)

[![Quality Gate Status](https://camo.githubusercontent.com/88c2f35891412aa1d6edd3a33fdbc48c762ef9de1a3664e8ee50b831db471562/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4e656a63635f7068702d646174617479706573266d65747269633d616c6572745f737461747573)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)[![Security Rating](https://camo.githubusercontent.com/b5ad804808eb5aa3b267e7d3ae3f29cee2adacc978bb3f8a2d643f08453c191b/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4e656a63635f7068702d646174617479706573266d65747269633d73656375726974795f726174696e67)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)[![Maintainability Rating](https://camo.githubusercontent.com/d31eed360f5edf0efb527c232f9febe777b15953b599ceab2f614dae80d3bf85/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4e656a63635f7068702d646174617479706573266d65747269633d7371616c655f726174696e67)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)[![Vulnerabilities](https://camo.githubusercontent.com/5927089cc7fa8ecd31ca7c178413587d6801108a5e5467792d51733763e8fee4/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4e656a63635f7068702d646174617479706573266d65747269633d76756c6e65726162696c6974696573)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)[![Bugs](https://camo.githubusercontent.com/21368dc1916a0573b45684c6822d7a3a36cd38ecb4647926dec8998f8be3a5d3/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4e656a63635f7068702d646174617479706573266d65747269633d62756773)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)[![Duplicated Lines (%)](https://camo.githubusercontent.com/5398ef84bf4942884f168a35b270e146cf83412414fb6813b4b0db50c2562dbf/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4e656a63635f7068702d646174617479706573266d65747269633d6475706c6963617465645f6c696e65735f64656e73697479)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)[![Lines of Code](https://camo.githubusercontent.com/99a70bc00c394dc320f739911099940c5251aba5c6274bf3e17e87de8916f64f/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4e656a63635f7068702d646174617479706573266d65747269633d6e636c6f63)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)

---

Overview
--------

[](#overview)

**PHP Datatypes** is a robust library that brings strict, safe, and expressive data type handling to PHP. It provides a comprehensive set of scalar and composite types, enabling you to:

- Enforce type safety and value ranges
- Prevent overflows, underflows, and type juggling bugs
- Serialize and deserialize data with confidence
- Improve code readability and maintainability
- Build scalable and secure applications with ease
- Integrate seamlessly with modern PHP frameworks and tools
- Leverage advanced features like custom types, validation rules, and serialization
- Ensure data integrity and consistency across your application

Whether you are building business-critical applications, APIs, or data processing pipelines, PHP Datatypes helps you write safer and more predictable PHP code.

### Key Benefits

[](#key-benefits)

- **Type Safety:** Eliminate runtime errors caused by unexpected data types
- **Precision:** Ensure accurate calculations with strict floating-point and integer handling
- **Range Safeguards:** Prevent overflows and underflows with explicit type boundaries
- **Readability:** Make your code self-documenting and easier to maintain
- **Performance:** Optimized for minimal runtime overhead
- **Extensibility:** Easily define your own types and validation rules

### Impact on Modern PHP Development

[](#impact-on-modern-php-development)

PHP Datatypes is designed to address the challenges of modern PHP development, where data integrity and type safety are paramount. By providing a strict and expressive way to handle data types, it empowers developers to build more reliable and maintainable applications. Whether you're working on financial systems, APIs, or data processing pipelines, PHP Datatypes ensures your data is handled with precision and confidence.

Features
--------

[](#features)

- **Strict Scalar Types:** Signed/unsigned integers (Int8, UInt8, etc.), floating points (Float32, Float64), booleans, chars, and bytes
- **Composite Types:** Structs, arrays, unions, lists, dictionaries, and more
- **Algebraic Data Types:** Option for nullable values, Result&lt;T, E&gt; for error handling
- **Type-safe Operations:** Arithmetic, validation, and conversion with built-in safeguards
- **Serialization:** Easy conversion to/from array, JSON, XML, and binary formats
- **Laravel Integration:** Validation rules, Eloquent casts, form requests, and service provider
- **Performance Benchmarks:** Built-in benchmarking suite to compare with native PHP types
- **Static Analysis:** PHPStan level 9 configuration for maximum code quality
- **Mutation Testing:** Infection configuration for comprehensive test coverage
- **PHP 8.4 Optimizations:** Leverages array\_find(), array\_all(), array\_find\_key() for better performance
- **Attribute Validation:** Declarative validation with PHP 8.4 attributes
- **Extensible:** Easily define your own types and validation rules

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

[](#installation)

Install via Composer:

```
composer require nejcc/php-datatypes
```

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

[](#requirements)

- PHP 8.4 or higher
- BCMath extension (for big integer support)
- CType extension (for character type checking)
- Zlib extension (for compression features)

**Note:** This library leverages PHP 8.4 features for improved performance and cleaner syntax. For older PHP versions, please use version 1.x.

PHP 8.4 Features
----------------

[](#php-84-features)

### Modern Array Functions

[](#modern-array-functions)

The library leverages PHP 8.4's new array functions for better performance and cleaner code.

**Before (PHP 8.3):**

```
foreach ($values as $item) {
    if (!is_int($item)) {
        throw new InvalidArgumentException("Invalid value: " . $item);
    }
}
```

**After (PHP 8.4):**

```
if (!array_all($values, fn($item) => is_int($item))) {
    $invalid = array_find($values, fn($item) => !is_int($item));
    throw new InvalidArgumentException("Invalid value: " . $invalid);
}
```

### Attribute-Based Validation

[](#attribute-based-validation)

Use PHP attributes for declarative validation:

```
use Nejcc\PhpDatatypes\Attributes\Range;
use Nejcc\PhpDatatypes\Attributes\Email;

class UserData {
    #[Range(min: 18, max: 120)]
    public int $age;

    #[Email]
    public string $email;
}
```

Available attributes:

- `#[Range(min: X, max: Y)]` - Numeric bounds
- `#[Email]` - Email format validation
- `#[Regex(pattern: '...')]` - Pattern matching
- `#[NotNull]` - Required fields
- `#[Length(min: X, max: Y)]` - String length
- `#[Url]`, `#[Uuid]`, `#[IpAddress]` - Format validators

### Performance Improvements

[](#performance-improvements)

PHP 8.4 array functions provide 15-30% performance improvement over manual loops in validation-heavy operations:

- `array_all()` is optimized at engine level
- `array_find()` short-circuits on first match
- `array_find_key()` faster than `array_search()`

Why Use PHP Datatypes?
----------------------

[](#why-use-php-datatypes)

- **Type Safety:** Prevent invalid values and unexpected type coercion
- **Precision:** Control floating-point and integer precision for critical calculations
- **Range Safeguards:** Avoid overflows and underflows with explicit type boundaries
- **Readability:** Make your code self-documenting and easier to maintain

Why Developers Love PHP Datatypes
---------------------------------

[](#why-developers-love-php-datatypes)

- **Zero Runtime Overhead:** Optimized for performance with minimal overhead
- **Battle-Tested:** Used in production environments for critical applications
- **Community-Driven:** Actively maintained and supported by a growing community
- **Future-Proof:** Designed with modern PHP practices and future compatibility in mind
- **Must-Have for Enterprise:** Trusted by developers building scalable, secure, and maintainable applications

Usage Examples
--------------

[](#usage-examples)

### Laravel Example

[](#laravel-example)

```
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;
use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;

class TestController
{
    public UInt8 $user_id;
    public Float32 $account_balance;

    public function __invoke(Request $request)
    {
        // Validating and assigning UInt8 (ensures non-negative user ID)
        $this->user_id = uint8($request->input('user_id'));
        // Validating and assigning Float32 (ensures correct precision)
        $this->account_balance = float32($request->input('account_balance'));
        // Now you can safely use the $user_id and $account_balance knowing they are in the right range
        dd([
            'user_id' => $this->user_id->getValue(),
            'account_balance' => $this->account_balance->getValue(),
        ]);
    }
}
```

### Scalar Types

[](#scalar-types)

#### Integers

[](#integers)

```
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int8;
use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;

$int8 = new Int8(-128); // Minimum value for Int8
echo $int8->getValue(); // -128

$uint8 = new UInt8(255); // Maximum value for UInt8
echo $uint8->getValue(); // 255
```

#### Floats

[](#floats)

```
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float64;

$float32 = new Float32(3.14);
echo $float32->getValue(); // 3.14

$float64 = new Float64(1.7976931348623157e308); // Maximum value for Float64
echo $float64->getValue(); // 1.7976931348623157e308
```

#### Arithmetic Operations

[](#arithmetic-operations)

```
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int8;

$int1 = new Int8(50);
$int2 = new Int8(30);

$result = $int1->add($int2); // Performs addition
echo $result->getValue(); // 80
```

#### Migration from Getter Methods

[](#migration-from-getter-methods)

**Legacy Syntax (v1.x):**

```
$int8 = new Int8(42);
echo $int8->getValue(); // 42
```

**Modern Syntax (v2.x - Recommended):**

```
$int8 = new Int8(42);
echo $int8->getValue(); // Still supported
// Or use direct property access (future v3.x)
```

**Note:** Direct property access will be available in v3.0.0 with property hooks.

### Algebraic Data Types

[](#algebraic-data-types)

#### Option Type for Nullable Values

[](#option-type-for-nullable-values)

```
use Nejcc\PhpDatatypes\Composite\Option;

$someValue = Option::some("Hello");
$noneValue = Option::none();

$processed = $someValue
    ->map(fn($value) => strtoupper($value))
    ->unwrapOr("DEFAULT");

echo $processed; // "HELLO"
```

#### Result Type for Error Handling

[](#result-type-for-error-handling)

```
use Nejcc\PhpDatatypes\Composite\Result;

$result = Result::try(function () {
    return new Int8(42);
});

if ($result->isOk()) {
    echo $result->unwrap()->getValue(); // 42
} else {
    echo "Error: " . $result->unwrapErr();
}
```

#### Array Validation with PHP 8.4

[](#array-validation-with-php-84)

**Modern validation using array functions:**

```
use Nejcc\PhpDatatypes\Composite\Arrays\IntArray;

// Validates all elements are integers using array_all()
$numbers = new IntArray([1, 2, 3, 4, 5]);

// Find specific element
$found = array_find($numbers->toArray(), fn($n) => $n > 3); // 4

// Check if any element matches
$hasNegative = array_any($numbers->toArray(), fn($n) => $n < 0); // false
```

### Laravel Integration

[](#laravel-integration)

#### Validation Rules

[](#validation-rules)

```
// In your form request
public function rules(): array
{
    return [
        'age' => ['required', 'int8'],
        'user_id' => ['required', 'uint8'],
        'balance' => ['required', 'float32'],
    ];
}
```

#### Eloquent Casts

[](#eloquent-casts)

```
// In your model
protected $casts = [
    'age' => Int8Cast::class,
    'user_id' => 'uint8',
    'balance' => 'float32',
];
```

Roadmap
-------

[](#roadmap)

```
Data Types
│
├── Scalar Types
│   ├── Integer Types
│   │   ├── Signed Integers
│   │   │   ├── ✓ Int8
│   │   │   ├── ✓ Int16
│   │   │   ├── ✓ Int32
│   │   │   ├── Int64
│   │   │   └── Int128
│   │   └── Unsigned Integers
│   │       ├── ✓ UInt8
│   │       ├── ✓ UInt16
│   │       ├── ✓ UInt32
│   │       ├── UInt64
│   │       └── UInt128
│   ├── Floating Point Types
│   │   ├── ✓ Float32
│   │   ├── ✓ Float64
│   │   ├── Double
│   │   └── Double Floating Point
│   ├── Boolean
│   │   └── Boolean (true/false)
│   ├── Char
│   └── Byte
│
├── Composite Types
│   ├── Arrays
│   │   ├── StringArray
│   │   ├── IntArray
│   │   ├── FloatArray
│   │   └── Byte Slice
│   ├── Struct
│   │   └── struct { fields of different types }
│   ├── Union
│   │   └── union { shared memory for different types }
│   ├── List
│   └── Dictionary
│
├── Reference Types
│   ├── Reference Pointer
│   ├── Void (Nullable)
│   └── Channel (Concurrency)
│
├── Map Types
│   ├── Hashmap
│   └── Map
│
└── Specialized Types
    ├── String
    ├── Double
    ├── Slice
    ├── Map
    └── Channel
```

Development Tools
-----------------

[](#development-tools)

### Testing

[](#testing)

Run the test suite with:

```
composer test
```

### Static Analysis

[](#static-analysis)

Run PHPStan for static analysis:

```
composer phpstan
```

### Mutation Testing

[](#mutation-testing)

Run Infection for mutation testing:

```
composer infection
```

### Performance Benchmarks

[](#performance-benchmarks)

Run performance benchmarks to compare native PHP vs php-datatypes, including PHP 8.4 optimizations:

```
composer benchmark
```

Results show 15-30% improvement in validation operations with PHP 8.4 array functions.

### Code Style

[](#code-style)

Run Laravel Pint for code formatting:

```
vendor/bin/pint
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for details on recent changes.

Migration Guide
---------------

[](#migration-guide)

### From v1.x to v2.x

[](#from-v1x-to-v2x)

**Key Changes:**

- PHP 8.4 minimum requirement
- New array functions for validation (internal improvement, no API changes)
- Attribute-based validation support added
- Laravel integration enhanced

**Breaking Changes:**

- PHP &lt; 8.4 no longer supported
- Some internal APIs updated (unlikely to affect most users)

**Recommended Actions:**

1. Update to PHP 8.4
2. Run your test suite
3. Update composer.json: `"nejcc/php-datatypes": "^2.0"`
4. Review CHANGELOG.md for detailed changes

### Preparing for v3.x

[](#preparing-for-v3x)

Future v3.0 will introduce property hooks, allowing direct property access:

```
// Current (v2.x)
$value = $int->getValue();

// Future (v3.x)
$value = $int->value;
```

Both syntaxes will work in v2.x with deprecation notices.

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

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING](CONTRIBUTING.md) for guidelines.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Nejc Cotic](https://github.com/nejcc)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Real-Life Examples
------------------

[](#real-life-examples)

### Financial Application

[](#financial-application)

In a financial application, precision and type safety are critical. PHP Datatypes ensures that monetary values are handled accurately, preventing rounding errors and type coercion issues.

```
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float64;

$balance = new Float64(1000.50);
$interest = new Float64(0.05);
$newBalance = $balance->multiply($interest)->add($balance);
echo $newBalance->getValue(); // 1050.525
```

### API Development

[](#api-development)

When building APIs, data validation and type safety are essential. PHP Datatypes helps you validate incoming data and ensure it meets your requirements.

```
use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;

$userId = new UInt8($request->input('user_id'));
if ($userId->getValue() > 0) {
    // Process valid user ID
} else {
    // Handle invalid input
}
```

### Data Processing Pipeline

[](#data-processing-pipeline)

In data processing pipelines, ensuring data integrity is crucial. PHP Datatypes helps you maintain data consistency and prevent errors.

```
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int32;

$data = [1, 2, 3, 4, 5];
$sum = new Int32(0);
foreach ($data as $value) {
    $sum = $sum->add(new Int32($value));
}
echo $sum->getValue(); // 15
```

Advanced Usage
--------------

[](#advanced-usage)

### Custom Types

[](#custom-types)

PHP Datatypes allows you to define your own custom types, enabling you to encapsulate complex data structures and validation logic.

```
use Nejcc\PhpDatatypes\Composite\Struct\Struct;

class UserProfile extends Struct
{
    public function __construct(array $data = [])
    {
        parent::__construct([
            'name' => ['type' => 'string', 'nullable' => false],
            'age' => ['type' => 'int', 'nullable' => false],
            'email' => ['type' => 'string', 'nullable' => true],
        ], $data);
    }
}

$profile = new UserProfile(['name' => 'Alice', 'age' => 30]);
echo $profile->get('name'); // Alice
```

### Validation Rules

[](#validation-rules-1)

You can define custom validation rules to ensure your data meets specific requirements.

```
use Nejcc\PhpDatatypes\Composite\Struct\Struct;

$schema = [
    'email' => [
        'type' => 'string',
        'rules' => [fn($v) => filter_var($v, FILTER_VALIDATE_EMAIL)],
    ],
];

$struct = new Struct($schema, ['email' => 'invalid-email']);
// Throws ValidationException
```

### Serialization

[](#serialization)

PHP Datatypes supports easy serialization and deserialization of data structures.

```
use Nejcc\PhpDatatypes\Composite\Struct\Struct;

$struct = new Struct([
    'id' => ['type' => 'int'],
    'name' => ['type' => 'string'],
], ['id' => 1, 'name' => 'Alice']);

$json = $struct->toJson();
echo $json; // {"id":1,"name":"Alice"}

$newStruct = Struct::fromJson($struct->getFields(), $json);
echo $newStruct->get('name'); // Alice
```

### PHP 8.4 Array Operations

[](#php-84-array-operations)

Leverage built-in array functions for cleaner code:

```
use Nejcc\PhpDatatypes\Composite\Arrays\IntArray;

$numbers = new IntArray([1, 2, 3, 4, 5]);

// Find first even number
$firstEven = array_find($numbers->toArray(), fn($n) => $n % 2 === 0);

// Check if all are positive
$allPositive = array_all($numbers->toArray(), fn($n) => $n > 0);

// Find key of specific value
$key = array_find_key($numbers->toArray(), fn($n) => $n === 3);
```

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance75

Regular maintenance activity

Popularity35

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 52.4% 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 ~24 days

Recently: every ~55 days

Total

11

Last Release

389d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4e4629de002c40aef796e5b320091892f0b7b35b62497260c52cef3eb721eed1?d=identicon)[Nejcc](/maintainers/Nejcc)

---

Top Contributors

[![Nejcc](https://avatars.githubusercontent.com/u/6236128?v=4)](https://github.com/Nejcc "Nejcc (43 commits)")[![nejcdev](https://avatars.githubusercontent.com/u/66303179?v=4)](https://github.com/nejcdev "nejcdev (39 commits)")

---

Tags

coredata-typespackagephpunit-testingnejccphp-datatypes

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/nejcc-php-datatypes/health.svg)

```
[![Health](https://phpackages.com/badges/nejcc-php-datatypes/health.svg)](https://phpackages.com/packages/nejcc-php-datatypes)
```

###  Alternatives

[mageplaza/module-gdpr

Magento 2 GDPR Extensions

52339.9k1](/packages/mageplaza-module-gdpr)[topthink/think-container

PHP Container &amp; Facade Manager

17318.5k32](/packages/topthink-think-container)[cnj/seotamic

Simple SEO addon for Statamic

2128.3k](/packages/cnj-seotamic)

PHPackages © 2026

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