PHP code example of bermudaphp / types

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

    

bermudaphp / types example snippets


use Bermuda\Stdlib\Types;

// Check basic types
Types::is($value, Types::TYPE_STRING);  // true if string
Types::is($value, Types::TYPE_INT);     // true if integer
Types::is($value, 'array');             // true if array

// Check multiple types
Types::isAny($value, [Types::TYPE_STRING, Types::TYPE_INT]); // true if string OR int

// Check object instances
Types::is($user, User::class);         // true if $user instanceof User
Types::isInstanceOf($user, UserInterface::class); // true if implements interface

use Bermuda\Stdlib\Types;

// Throws InvalidArgumentException if not matching
Types::assert($value, Types::TYPE_STRING);
Types::assert($value, [Types::TYPE_STRING, Types::TYPE_INT]);

// enforce() is an alias for assert() (backward compatibility)
Types::enforce($value, Types::TYPE_STRING);

// Assert not null with type check
$user = Types::assertNotNull($maybeUser, User::class);
// $user is guaranteed to be non-null User instance

// Custom error messages
Types::assert($value, Types::TYPE_INT, 'ID must be an integer');

use Bermuda\Stdlib\Types;

// Get the actual type
$type = Types::getType($value); // returns 'string', 'int', 'array', etc.

// Get class name for objects
$type = Types::getType($object, Types::OBJECT_AS_CLASS); // returns 'App\User'

// Handle callables as objects
$type = Types::getType($callable, Types::CALLABLE_AS_OBJECT);

use Bermuda\Stdlib\Types;

// Check if string is a valid class name
Types::isClass('App\User');           // true if class exists
Types::isClass($value, User::class);   // true if $value === 'App\User' (case-insensitive)

// Check if string is a valid interface name
Types::isInterface('App\UserInterface'); // true if interface exists

// Check subclass relationships
Types::isSubclassOf('App\Admin', 'App\User'); // true if Admin extends User
Types::isSubclassOfAny('App\Admin', ['App\User', 'App\Manager']);

use Bermuda\Stdlib\Types;

class UserService
{
    public function createUser(mixed $data): User
    {
        Types::assert($data, Types::TYPE_ARRAY, 'User data must be an array');
        
        $id = Types::assertNotNull($data['id'] ?? null, Types::TYPE_INT);
        $email = Types::assertNotNull($data['email'] ?? null, Types::TYPE_STRING);
        
        return new User($id, $email);
    }
    
    public function processPayment(mixed $handler): void
    {
        Types::assert($handler, [
            PaymentInterface::class,
            Types::TYPE_CALLABLE
        ], 'Payment handler must implement PaymentInterface or be callable');
        
        // Process payment...
    }
}