PHP code example of ashallendesign / type-safe

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

    

ashallendesign / type-safe example snippets


use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::INT);

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::STRING);

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::BOOLEAN);

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::CLOSURE);

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::OBJECT);

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::ARRAY);

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::ASSOC_ARRAY);

use App\Models\User;
use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::object(User::class));

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::arrayOf(Type::INT));

use AshAllenDesign\TypeSafe\Type;

$validatedField = safe($field, Type::assocArrayOf(Type::STRING, Type::STRING));

use App\Models\User;
use AshAllenDesign\TypeSafe\Check;
use Illuminate\Support\Collection;

class LaravelUserCollection implements Check
{
    public function passes(mixed $prop): bool
    {
        if (!$prop instanceof Collection) {
            return false;
        }

        return $prop->whereInstanceOf(User::class)->count() === $prop->count();
    }

    public function message(mixed $prop): string
    {
        return 'One of the items is not a User model.';
    }
}

$collection = collect([new User(), new TestCase()]);

safe($collection, new LaravelUserCollection());

use AshAllenDesign\TypeSafe\Type;
use AshAllenDesign\TypeSafe\TypeSafe;

TypeSafe::skipChecks();

$validatedField = safe($field, Type::ASSOC_ARRAY);

use AshAllenDesign\TypeSafe\TypeSafe;

$validatedField = (new TypeSafe())->safe($field, Type::INT);

$validatedField = safe($field, Type::INT);

use AshAllenDesign\TypeSafe\TypeSafe;

$validatedField = TypeSafe::int($field);