A package for adding more type safety to your PHP projects.

Overview

PHP Type Safe logo

Latest Version on Packagist Build Status Total Downloads PHP from Packagist GitHub license

Table of Contents

Overview

Type Safe is a lightweight package that you can use in your PHP projects to ensure your variables' types.

If you're interested in reading about why I made this package, check out this blog post.

Installation

You can install the package via Composer:

composer require ashallendesign/type-safe

The package has been developed and tested to work with the following minimum requirements:

  • PHP 8.0

Usage

Simple Checks

Validating that a property is an integer:

use AshAllenDesign\TypeSafe\Type;

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

Validating that a property is a string:

use AshAllenDesign\TypeSafe\Type;

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

Validating that a property is a boolean:

use AshAllenDesign\TypeSafe\Type;

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

Validating that a property is a closure:

use AshAllenDesign\TypeSafe\Type;

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

Validating that a property is an object:

use AshAllenDesign\TypeSafe\Type;

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

Validating that a property is an array:

use AshAllenDesign\TypeSafe\Type;

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

Validating that a property is an associative array:

use AshAllenDesign\TypeSafe\Type;

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

Advanced Checks

Validating that a property is an object of a specific class:

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

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

Validating that a property is an array containing specific fields:

use AshAllenDesign\TypeSafe\Type;

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

Validating that a property is an associative array containing specific fields:

use AshAllenDesign\TypeSafe\Type;

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

Custom Checks

You might want to use your own custom checks that aren't provided in the package by default. To do this, you can create your own class that implements the AshAllenDesign\TypeSafe\Check interface.

The interface enforces two methods: passes() and message(). The passes() method is used to define your logic that determines if the field is the correct type. The message() method is used to return the message that will be passed to the thrown exception if the validation fails.

For example, if we wanted to create a custom check to assert that our field was a Laravel Collection that only contained User models, it might look something like this:

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.';
    }
}

We could then use that check like so:

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

safe($collection, new LaravelUserCollection());

Skipping Checks

There may be times when you don't want to run the type checks. For example, you might want to disable them in production environments and only run them in local, testing and staging environments. To skip the checks, you can simply use the skipChecks like shown in the example below:

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

TypeSafe::skipChecks();

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

Helpers Methods

There are three different ways that you can use the package to add type safe checks to your code.

The first method is by using the TypeSafe object itself like so:

use AshAllenDesign\TypeSafe\TypeSafe;

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

Alternatively, you can use the safe() helper function that achieves the same thing as the code above. You can use the helper function like so:

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

The TypeSafe also includes helper methods that you can use for all the simple checks. The example shows how you can validate an integer field:

use AshAllenDesign\TypeSafe\TypeSafe;

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

Testing

To run the tests for the package, you can use the following command:

composer test

Security

If you find any security related issues, please contact me directly at [email protected] to report it.

Contribution

If you wish to make any changes or improvements to the package, feel free to make a pull request.

To contribute to this library, please use the following guidelines before submitting your pull request:

  • Write tests for any new functions that are added. If you are updating existing code, make sure that the existing tests pass and write more if needed.
  • Follow PSR-12 coding standards.
  • Make all pull requests to the master branch.

Credits

Changelog

Check the CHANGELOG to get more information about the latest changes.

License

The MIT License (MIT). Please see License File for more information.

You might also like...
A library for adding economic concepts.

PHP use binary version 8.0.10 use PocketMine-MP version API4-beta11+dev2067 Init use oiran\walletlib\api\WalletLib; use oiran\walletlib\api\WarningLev

A library for adding economic concepts.

Summary This plugin adds the concept of money to the server. Wallet data held by the player is stored in .json format and I/O asynchronously. As for t

Adds support for quickly adding a "snow day" banner at the top of a website.

❄️ Snow Day Plugin 🚨 Requires OctoberCMS 2.0 ✨ What does this plugin do? Provides the ability to quickly add a cross-site banner using a component. ❓

This AddOn allows you to search for module names when adding a block
This AddOn allows you to search for module names when adding a block

Modulsuche und Modulvorschau für REDAXO 5 Dieses AddOn ermöglicht die Suche nach Modulnamen, wenn man einen Block hinzufügt. Dies kann sehr hilfreich

Type and shape system for arrays. Help write clearer code when implementing configs for your PocketMine-MP plugin or composer project.
Type and shape system for arrays. Help write clearer code when implementing configs for your PocketMine-MP plugin or composer project.

ConfigStruct Type and shape system for arrays. Help write clearer code when implementing configs for your PocketMine-MP plugin or composer project. It

📦 "PHP type names" contains the list of constants for the available PHP data types.

PHP type names PHP type names 📄 Description Simple library containing the list of constants for the available PHP data types. Use those constant type

A simple and easy-to-use enumeration extension package to help you manage enumerations in your project more conveniently

A simple and easy-to-use enumeration extension package to help you manage enumerations in your project more conveniently

A simple, type-safe, zero dependency port of the javascript fetch WebApi for PHP.
A simple, type-safe, zero dependency port of the javascript fetch WebApi for PHP.

A simple, type-safe, zero dependency port of the javascript fetch WebApi for PHP.

Collection of value objects that represent the types of the PHP type system

sebastian/type Collection of value objects that represent the types of the PHP type system. Installation You can add this library as a local, per-proj

Releases(v1.0.0)
Owner
Ash Allen
Laravel Web Developer Preston, United Kingdom
Ash Allen
Add scalar type hints and return types to existing PHP projects using PHPDoc annotations

PHPDoc to Type Hint Archived! This repository is now archived. Consider using PHP CS Fixer (and especially the phpdoc_to_param_type and phpdoc_to_retu

Kévin Dunglas 228 May 22, 2022
Adding Firebase PHP to your project using Composer

Firebase PHP Client ❤️ Sponsor Based on the Firebase REST API. Available on Packagist. Adding Firebase PHP to your project using Composer For PHP 7 or

Tamas Kalman 786 Dec 31, 2022
The Cache component provides an extended PSR-6 implementation for adding cache to your applications.

Symfony PSR-6 implementation for caching The Cache component provides an extended PSR-6 implementation for adding cache to your applications. It is de

Symfony 3.8k Jan 3, 2023
DiscordLookup | Get more out of Discord with Discord Lookup! Snowflake Decoder, Guild List with Stats, Invite Info and more...

DiscordLookup Get more out of Discord with Discord Lookup! Snowflake Decoder, Guild List with Stats, Invite Info and more... Website Getting Help Tool

Felix 69 Dec 23, 2022
Ratio plugin is a luck plugin. The more lucky you are, the more you win!

Ratio Ratio plugin is a luck plugin. The more lucky you are, the more you win Features When you break a block (Cobblestone), it gives/puts you somethi

Ali Tura Çetin 2 Apr 25, 2022
Orangescrum is a simple yet powerful free and open source project management software that helps team to organize their tasks, projects and deliver more.

Free, open source Project Management software Introduction Orangescrum is the simple yet powerful free and open source project management software tha

Orangescrum 110 Dec 30, 2022
JsonQ is a simple, elegant PHP package to Query over any type of JSON Data

php-jsonq JsonQ is a simple, elegant PHP package to Query over any type of JSON Data. It'll make your life easier by giving the flavour of an ORM-like

Nahid Bin Azhar 834 Dec 25, 2022
An extension for PHPStan for adding analysis for PHP Language Extensions.

PHPStan PHP Language Extensions (currently in BETA) This is an extension for PHPStan for adding analysis for PHP Language Extensions. Language feature

Dave Liddament 9 Nov 30, 2022
Envbar allows you to differentiate between environments by adding a custom colored bar above the top navigation.

Envbar Envbar allows you to differentiate between environments by adding a custom colored bar above the top navigation. This should help backend users

Magenizr 6 Oct 7, 2022