PHP code example of fasano / lib-primitives

1. Go to this page and download the library: Download fasano/lib-primitives 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/ */

    

fasano / lib-primitives example snippets


function sendEmail(string $email) // Requires checks

function sendEmail(Email $email)  // Trusted input

readonly class Email
{
    public function __construct(public string $value)
    {
        if (false === filter_var($value, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException(sprintf('%s is not a valid email', $value));
        }
    }
}

use Fasano\PrimitivesLib\Metadata\Attribute\Name;
use Fasano\PrimitivesLib\Metadata\Attribute\Example;
use Fasano\PrimitivesLib\Metadata\Attribute\Description;

#[Name('Email Address')]
#[Example('[email protected]')]
#[Description('A valid email address for user communication')]
readonly class Email
{
    public function __construct(public string $value)
    {
        if (false === filter_var($value, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException(sprintf('%s is not a valid email', $value));
        }
    }
}

use Fasano\PrimitivesLib\StringPrimitive;

readonly class ProductCode extends StringPrimitive
{
    public static function check(string $value): bool
    {
        return preg_match('/^[A-Z]{2}-\d{4}$/', $value) === 1;
    }
}

// Usage
$code = new ProductCode('AB-1234'); // Valid
$code = new ProductCode('invalid'); // Throws InvalidArgumentException

use Fasano\PrimitivesLib\Primitives;

$isPrimitive = Primitives::isPrimitive(Email::class);    // true
$isPrimitive = Primitives::isPrimitive(stdClass::class); // false

$metadata = Primitives::getMetadata(Email::class);

echo $metadata->name;        // "Email Address"
echo $metadata->example;     // "[email protected]"
echo $metadata->description; // "A valid email address for user communication"
echo $metadata->type;        // "string"
echo $metadata->fqcn;        // "MyApp\Domain\User\Property\Email"

$email = new Email('[email protected]');
$value = Primitives::valueOf($email); // "[email protected]"

$email = Primitives::create(Email::class, '[email protected]');
// Equivalent to: new Email('[email protected]')

$email1 = new Email('[email protected]');
$email2 = new Email('[email protected]');
$email3 = new Email('[email protected]');

Primitives::equals($email1, $email2); // true
Primitives::equals($email1, $email3); // false