Skip to content

Update #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ yarn-error.log
vendor
vendor/
composer.lock
todo.txt
todo.txt
/build/**
242 changes: 176 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,61 +1,82 @@
# Introducing PHP Datatypes: A Strict and Safe Way to Handle Primitive Data Types
# PHP Datatypes: Strict, Safe, and Flexible Data Handling for PHP

[![Latest Version on Packagist](https://img.shields.io/packagist/v/nejcc/php-datatypes.svg?style=flat-square)](https://packagist.org/packages/nejcc/php-datatypes)
[![Total Downloads](https://img.shields.io/packagist/dt/nejcc/php-datatypes.svg?style=flat-square)](https://packagist.org/packages/nejcc/php-datatypes)
![GitHub Actions](https://github.com/nejcc/php-datatypes/actions/workflows/main.yml/badge.svg)


[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)
[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)
[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=bugs)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)



[![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)


[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=ncloc)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)

I'm excited to share my latest PHP package, PHP Datatypes. This library introduces a flexible yet strict way of handling primitive data types like integers, floats, and strings in PHP. It emphasizes type safety and precision, supporting operations for signed and unsigned integers (Int8, UInt8, etc.) and various floating-point formats (Float32, Float64, etc.).

With PHP Datatypes, you get fine-grained control over the data you handle, ensuring your operations stay within valid ranges. It's perfect for anyone looking to avoid common pitfalls like overflows, division by zero, and unexpected type juggling in PHP.
---

## 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
- **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
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
- **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
- **Type-safe Operations:** Arithmetic, validation, and conversion with built-in safeguards
- **Serialization:** Easy conversion to/from array, JSON, and XML
- **Laravel Integration:** Ready for use in modern PHP frameworks
- **Extensible:** Easily define your own types and validation rules

## Installation

You can install the package via composer:
Install via Composer:

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

## Usage

Below are examples of how to use the basic integer and float classes in your project.


This approach has a few key benefits:

- Type Safety: By explicitly defining the data types like UInt8, you're eliminating the risk of invalid values sneaking into your application. For example, enforcing unsigned integers ensures that the value remains within valid ranges, offering a safeguard against unexpected data inputs.


- Precision: Especially with floating-point numbers, handling precision can be tricky in PHP due to how it manages floats natively. By offering precise types such as Float32 or Float64, we're giving developers the control they need to maintain consistency in calculations.


- Range Safeguards: By specifying exact ranges, you can prevent issues like overflows or underflows that often go unchecked in dynamic typing languages like PHP.


- Readability and Maintenance: Explicit data types improve code readability. When a developer reads your code, they instantly know what type of value is expected and the constraints around that value. This enhances long-term maintainability.
## 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

### Laravel example
## 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

here's how it can be used in practice across different types, focusing on strict handling for both integers and floats:
## Usage Examples

### Laravel Example
```php
namespace App\Http\Controllers;

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

class TestController
{
Expand All @@ -66,28 +87,22 @@ class TestController
{
// 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(),
]);
}
}

```
Here, we're not only safeguarding user IDs but also handling potentially complex floating-point operations, where precision is critical. This could be especially beneficial for applications in fields like finance or analytics where data integrity is paramount.


PHP examples

### Integers

### Scalar Types
#### Integers
```php
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int8;use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;
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
Expand All @@ -96,10 +111,10 @@ $uint8 = new UInt8(255); // Maximum value for UInt8
echo $uint8->getValue(); // 255
```

### Floats

#### Floats
```php
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float64;
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float64;

$float32 = new Float32(3.14);
echo $float32->getValue(); // 3.14
Expand All @@ -108,8 +123,7 @@ $float64 = new Float64(1.7976931348623157e308); // Maximum value for Float64
echo $float64->getValue(); // 1.7976931348623157e308
```

### Arithmetic Operations

#### Arithmetic Operations
```php
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int8;

Expand All @@ -118,31 +132,30 @@ $int2 = new Int8(30);

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

```

# ROAD MAP
## Roadmap

```md
Data Types
├── Scalar Types
│ ├── Integer Types
│ │ ├── Signed Integers
│ │ │ ├── ✓ Int8
│ │ │ ├── ✓ Int16
│ │ │ ├── ✓ Int32
│ │ │ ├── Int8
│ │ │ ├── Int16
│ │ │ ├── Int32
│ │ │ ├── Int64
│ │ │ └── Int128
│ │ └── Unsigned Integers
│ │ ├── ✓ UInt8
│ │ ├── ✓ UInt16
│ │ ├── ✓ UInt32
│ │ ├── UInt8
│ │ ├── UInt16
│ │ ├── UInt32
│ │ ├── UInt64
│ │ └── UInt128
│ ├── Floating Point Types
│ │ ├── ✓ Float32
│ │ ├── ✓ Float64
│ │ ├── Float32
│ │ ├── Float64
│ │ ├── Double
│ │ └── Double Floating Point
│ ├── Boolean
Expand Down Expand Up @@ -180,32 +193,129 @@ Data Types
└── Channel
```

## Testing

### Testing

Run the test suite with:
```bash
composer test
```

### Changelog
## Changelog

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.
Please see [CHANGELOG](CHANGELOG.md) for details on recent changes.

## Contributing

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

### Security
## Security

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

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

## License

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

## PHP Package Boilerplate
## Real-Life Examples

### 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.

```php
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
When building APIs, data validation and type safety are essential. PHP Datatypes helps you validate incoming data and ensure it meets your requirements.

```php
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
In data processing pipelines, ensuring data integrity is crucial. PHP Datatypes helps you maintain data consistency and prevent errors.

This package was generated using the [PHP Package Boilerplate](https://laravelpackageboilerplate.com) by [Beyond Code](http://beyondco.de/).
```php
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

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

```php
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
You can define custom validation rules to ensure your data meets specific requirements.

```php
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
PHP Datatypes supports easy serialization and deserialization of data structures.

```php
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
```
Loading