PHP code example of nejcc / php-datatypes

1. Go to this page and download the library: Download nejcc/php-datatypes library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nejcc / php-datatypes example snippets


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

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

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

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

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(),
        ]);
    }
}

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

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

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

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

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

use Nejcc\PhpDatatypes\Composite\Option;

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

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

echo $processed; // "HELLO"

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();
}

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

// In your form request
public function rules(): array
{
    return [
        'age' => [',
    ];
}

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

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

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

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

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
}

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

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

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

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

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);
bash
composer