Skip to content

Commit 8e4bc6d

Browse files
author
nejc
committed
feat: implement core features and refactoring
1 parent f4bd3af commit 8e4bc6d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+4886
-813
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,4 @@ vendor
2121
vendor/
2222
composer.lock
2323
todo.txt
24-
/build/
24+
/build/**

README.md

Lines changed: 176 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,82 @@
1-
# Introducing PHP Datatypes: A Strict and Safe Way to Handle Primitive Data Types
1+
# PHP Datatypes: Strict, Safe, and Flexible Data Handling for PHP
22

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

7-
87
[![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)
98
[![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)
109
[![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)
1110
[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)
1211
[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=Nejcc_php-datatypes&metric=bugs)](https://sonarcloud.io/summary/new_code?id=Nejcc_php-datatypes)
13-
14-
15-
1612
[![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)
17-
18-
1913
[![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)
2014

21-
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.).
22-
23-
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.
15+
---
16+
17+
## Overview
18+
19+
**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:
20+
- Enforce type safety and value ranges
21+
- Prevent overflows, underflows, and type juggling bugs
22+
- Serialize and deserialize data with confidence
23+
- Improve code readability and maintainability
24+
- Build scalable and secure applications with ease
25+
- Integrate seamlessly with modern PHP frameworks and tools
26+
- Leverage advanced features like custom types, validation rules, and serialization
27+
- Ensure data integrity and consistency across your application
28+
29+
Whether you are building business-critical applications, APIs, or data processing pipelines, PHP Datatypes helps you write safer and more predictable PHP code.
30+
31+
### Key Benefits
32+
- **Type Safety:** Eliminate runtime errors caused by unexpected data types
33+
- **Precision:** Ensure accurate calculations with strict floating-point and integer handling
34+
- **Range Safeguards:** Prevent overflows and underflows with explicit type boundaries
35+
- **Readability:** Make your code self-documenting and easier to maintain
36+
- **Performance:** Optimized for minimal runtime overhead
37+
- **Extensibility:** Easily define your own types and validation rules
38+
39+
### Impact on Modern PHP Development
40+
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.
41+
42+
## Features
43+
- **Strict Scalar Types:** Signed/unsigned integers (Int8, UInt8, etc.), floating points (Float32, Float64), booleans, chars, and bytes
44+
- **Composite Types:** Structs, arrays, unions, lists, dictionaries, and more
45+
- **Type-safe Operations:** Arithmetic, validation, and conversion with built-in safeguards
46+
- **Serialization:** Easy conversion to/from array, JSON, and XML
47+
- **Laravel Integration:** Ready for use in modern PHP frameworks
48+
- **Extensible:** Easily define your own types and validation rules
2449

2550
## Installation
2651

27-
You can install the package via composer:
52+
Install via Composer:
2853

2954
```bash
3055
composer require nejcc/php-datatypes
3156
```
3257

33-
## Usage
34-
35-
Below are examples of how to use the basic integer and float classes in your project.
36-
37-
38-
This approach has a few key benefits:
39-
40-
- 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.
41-
42-
43-
- 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.
44-
45-
46-
- Range Safeguards: By specifying exact ranges, you can prevent issues like overflows or underflows that often go unchecked in dynamic typing languages like PHP.
47-
48-
49-
- 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.
58+
## Why Use PHP Datatypes?
59+
- **Type Safety:** Prevent invalid values and unexpected type coercion
60+
- **Precision:** Control floating-point and integer precision for critical calculations
61+
- **Range Safeguards:** Avoid overflows and underflows with explicit type boundaries
62+
- **Readability:** Make your code self-documenting and easier to maintain
5063

51-
### Laravel example
64+
## Why Developers Love PHP Datatypes
65+
- **Zero Runtime Overhead:** Optimized for performance with minimal overhead
66+
- **Battle-Tested:** Used in production environments for critical applications
67+
- **Community-Driven:** Actively maintained and supported by a growing community
68+
- **Future-Proof:** Designed with modern PHP practices and future compatibility in mind
69+
- **Must-Have for Enterprise:** Trusted by developers building scalable, secure, and maintainable applications
5270

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

73+
### Laravel Example
5574
```php
5675
namespace App\Http\Controllers;
5776

58-
use Illuminate\Http\Request;use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;
77+
use Illuminate\Http\Request;
78+
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;
79+
use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;
5980

6081
class TestController
6182
{
@@ -66,28 +87,22 @@ class TestController
6687
{
6788
// Validating and assigning UInt8 (ensures non-negative user ID)
6889
$this->user_id = uint8($request->input('user_id'));
69-
7090
// Validating and assigning Float32 (ensures correct precision)
7191
$this->account_balance = float32($request->input('account_balance'));
72-
7392
// Now you can safely use the $user_id and $account_balance knowing they are in the right range
7493
dd([
7594
'user_id' => $this->user_id->getValue(),
7695
'account_balance' => $this->account_balance->getValue(),
7796
]);
7897
}
7998
}
80-
8199
```
82-
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.
83-
84-
85-
PHP examples
86-
87-
### Integers
88100

101+
### Scalar Types
102+
#### Integers
89103
```php
90-
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int8;use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;
104+
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int8;
105+
use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;
91106

92107
$int8 = new Int8(-128); // Minimum value for Int8
93108
echo $int8->getValue(); // -128
@@ -96,10 +111,10 @@ $uint8 = new UInt8(255); // Maximum value for UInt8
96111
echo $uint8->getValue(); // 255
97112
```
98113

99-
### Floats
100-
114+
#### Floats
101115
```php
102-
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float64;
116+
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float32;
117+
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float64;
103118

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

111-
### Arithmetic Operations
112-
126+
#### Arithmetic Operations
113127
```php
114128
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int8;
115129

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

119133
$result = $int1->add($int2); // Performs addition
120134
echo $result->getValue(); // 80
121-
122135
```
123136

124-
# ROAD MAP
137+
## Roadmap
125138

126139
```md
127140
Data Types
128141
129142
├── Scalar Types
130143
│ ├── Integer Types
131144
│ │ ├── Signed Integers
132-
│ │ │ ├── ✓ Int8
133-
│ │ │ ├── ✓ Int16
134-
│ │ │ ├── ✓ Int32
145+
│ │ │ ├── Int8
146+
│ │ │ ├── Int16
147+
│ │ │ ├── Int32
135148
│ │ │ ├── Int64
136149
│ │ │ └── Int128
137150
│ │ └── Unsigned Integers
138-
│ │ ├── ✓ UInt8
139-
│ │ ├── ✓ UInt16
140-
│ │ ├── ✓ UInt32
151+
│ │ ├── UInt8
152+
│ │ ├── UInt16
153+
│ │ ├── UInt32
141154
│ │ ├── UInt64
142155
│ │ └── UInt128
143156
│ ├── Floating Point Types
144-
│ │ ├── ✓ Float32
145-
│ │ ├── ✓ Float64
157+
│ │ ├── Float32
158+
│ │ ├── Float64
146159
│ │ ├── Double
147160
│ │ └── Double Floating Point
148161
│ ├── Boolean
@@ -180,32 +193,129 @@ Data Types
180193
└── Channel
181194
```
182195

196+
## Testing
183197

184-
### Testing
185-
198+
Run the test suite with:
186199
```bash
187200
composer test
188201
```
189202

190-
### Changelog
203+
## Changelog
191204

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

194207
## Contributing
195208

196-
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
209+
Contributions are welcome! Please see [CONTRIBUTING](CONTRIBUTING.md) for guidelines.
197210

198-
### Security
211+
## Security
199212

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

202215
## Credits
203-
- [Nejc Cotic](https://github.com/nejcc)
216+
- [Nejc Cotic](https://github.com/nejcc)
204217

205218
## License
206219

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

209-
## PHP Package Boilerplate
222+
## Real-Life Examples
223+
224+
### Financial Application
225+
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.
226+
227+
```php
228+
use Nejcc\PhpDatatypes\Scalar\FloatingPoints\Float64;
229+
230+
$balance = new Float64(1000.50);
231+
$interest = new Float64(0.05);
232+
$newBalance = $balance->multiply($interest)->add($balance);
233+
echo $newBalance->getValue(); // 1050.525
234+
```
235+
236+
### API Development
237+
When building APIs, data validation and type safety are essential. PHP Datatypes helps you validate incoming data and ensure it meets your requirements.
238+
239+
```php
240+
use Nejcc\PhpDatatypes\Scalar\Integers\Unsigned\UInt8;
241+
242+
$userId = new UInt8($request->input('user_id'));
243+
if ($userId->getValue() > 0) {
244+
// Process valid user ID
245+
} else {
246+
// Handle invalid input
247+
}
248+
```
249+
250+
### Data Processing Pipeline
251+
In data processing pipelines, ensuring data integrity is crucial. PHP Datatypes helps you maintain data consistency and prevent errors.
210252

211-
This package was generated using the [PHP Package Boilerplate](https://laravelpackageboilerplate.com) by [Beyond Code](http://beyondco.de/).
253+
```php
254+
use Nejcc\PhpDatatypes\Scalar\Integers\Signed\Int32;
255+
256+
$data = [1, 2, 3, 4, 5];
257+
$sum = new Int32(0);
258+
foreach ($data as $value) {
259+
$sum = $sum->add(new Int32($value));
260+
}
261+
echo $sum->getValue(); // 15
262+
```
263+
264+
## Advanced Usage
265+
266+
### Custom Types
267+
PHP Datatypes allows you to define your own custom types, enabling you to encapsulate complex data structures and validation logic.
268+
269+
```php
270+
use Nejcc\PhpDatatypes\Composite\Struct\Struct;
271+
272+
class UserProfile extends Struct
273+
{
274+
public function __construct(array $data = [])
275+
{
276+
parent::__construct([
277+
'name' => ['type' => 'string', 'nullable' => false],
278+
'age' => ['type' => 'int', 'nullable' => false],
279+
'email' => ['type' => 'string', 'nullable' => true],
280+
], $data);
281+
}
282+
}
283+
284+
$profile = new UserProfile(['name' => 'Alice', 'age' => 30]);
285+
echo $profile->get('name'); // Alice
286+
```
287+
288+
### Validation Rules
289+
You can define custom validation rules to ensure your data meets specific requirements.
290+
291+
```php
292+
use Nejcc\PhpDatatypes\Composite\Struct\Struct;
293+
294+
$schema = [
295+
'email' => [
296+
'type' => 'string',
297+
'rules' => [fn($v) => filter_var($v, FILTER_VALIDATE_EMAIL)],
298+
],
299+
];
300+
301+
$struct = new Struct($schema, ['email' => 'invalid-email']);
302+
// Throws ValidationException
303+
```
304+
305+
### Serialization
306+
PHP Datatypes supports easy serialization and deserialization of data structures.
307+
308+
```php
309+
use Nejcc\PhpDatatypes\Composite\Struct\Struct;
310+
311+
$struct = new Struct([
312+
'id' => ['type' => 'int'],
313+
'name' => ['type' => 'string'],
314+
], ['id' => 1, 'name' => 'Alice']);
315+
316+
$json = $struct->toJson();
317+
echo $json; // {"id":1,"name":"Alice"}
318+
319+
$newStruct = Struct::fromJson($struct->getFields(), $json);
320+
echo $newStruct->get('name'); // Alice
321+
```

0 commit comments

Comments
 (0)