Skip to content
/ Type Public

A library to check a variable's type at runtime

Notifications You must be signed in to change notification settings

Nadybot/Type

Repository files navigation

Nadylib\Type

Introduction

The type component of Nadylib is a ripped version of Psl\Type that was stripped down to be self-dependant and only has minimum requirements as well as working with PHP down to version 8.1. If you want a full framework, check out azjezz's awesome PHP Standard Library.

Nadylib\Type provides a set of functions to ensure that a given value is of a specific type at Runtime. It aims to provide a solution for the Parse, Don't Validate problem.

Usage

use Nadylib\Type;

$untrustedInput = $request->get('input');

// Turns a string-like value into a non-empty-string
$trustedInput = Type\nonEmptyString()->coerce($untrustedInput);

// Or assert that it's already a non-empty-string
$trustedInput = Type\nonEmptyString()->assert($untrustedInput);

// Or check if it's a non-empty-string
$isTrustworthy = Type\nonEmptyString()->matches($untrustedInput);

Every type provided by this component is an instance of Type\TypeInterface<Tv>. This interface provides the following methods:

  • matches(mixed $value): $value is Tv – Checks if the provided value is of the type.
  • assert(mixed $value): Tv – Asserts that the provided value is of the type or throws an AssertException on failure.
  • coerce(mixed $value): Tv – Coerces the provided value into the type or throws a CoercionException on failure.

Static Analysis

Your static analyzer should fully understand the types provided by this component if they support @psalm-assert. The only exception is shape() which would require a special component on the analyzers which is not available for Nadylib\Type. If you need this, use the PHP Standard Library instead.

About

A library to check a variable's type at runtime

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages