fubber/util-types

Provides a simple type system preferring native PHP types while allowing object polymorphism methods such as 'asFloat()', 'asInt()' and type checking helpers.

0.1 2020-08-24 14:17 UTC

This package is auto-updated.

Last update: 2024-10-25 03:09:50 UTC


README

A small library allowing for type polymorphism between objects and scalar values via class methods asBool(): bool, asInt(): int, asFloat(): float, __toString(): string and asString() for completion.

This library is not intended to be used in place of directly using PHP native types. The use cases for the library are quite niche, for example if you need to implement a simple byte code virtual machine, a database ORM or similar. In an ORM, it can be nice if objects when cast to integers return their primary key. This would allow something like:

    $father = Person::load(42); // $father is an object that implements the 'asInt(): int' method

    // The 'Fubber\Util\Type::toInt()' would be called inside the 'where()' method
    $table->where('father = :father', [ 'father' => $father ]);

Basic Usage

Instead of function foo(int $bar) you would use the 'Type::assert*' methods:

function foo($bar) {
    Type::assertInt($bar);
    ...

Instead of $foo + $bar you would use Type::toNumeric($foo) + Type::toNumeric($bar).

When boolean testing, you would use the Type::toBool($foo) method.

Injectable type conversion

Sometimes you need to be able to implement this functionality into other class that don't already have the 'asInt()', 'asFloat()', 'asString()' or 'asBool()' methods. In this case, you can declare a function ClassName__asBool(ClassName $instance): bool { ... }.

This works with namespaced classes as well. Example:

/**
 * Declaring a converter for Some\Other\Namespace\SomeClass
 * to integer
 */
namespace Some\Other\Namespace {
    function SomeClass__asInt(SomeClass $value): int {
        return $value->id;
    }
}

/**
 * Usage Examples
 */
namespace {

    $instance = new Some\Other\Namespace\SomeClass();

    if (Fubber\Util\Type::isInt($instance)) {
        echo "- it is an integer\n";
    }

    echo (10 + Fubber\Util\Type::toInt($instance))." is 10x!\n";

}

Rationale

This library was created because it was needed in the Fubber\Table ORM which we are, building. Specifically in the functionality related to the CSV file backend. We could obviously have kept the implementation details internal to the Fubber\Table library, but then we would have to keep the awesome Fubber\Util\Comparator library internal as well - and so on.

Use it if you want. It has no dependencies.