This package is abandoned and no longer maintained. The author suggests using the hamet-framework/type package instead.

Hamlet Framework / Cast

0.0.1 2019-04-18 11:21 UTC

This package is auto-updated.

Last update: 2019-05-01 09:19:58 UTC


README

There are five aspects of specifying type of an expression in PHP:

  1. The most exact specification of the type (we assume it's in psalm syntax), for example array<int,DateTime|null>
  2. The sequence of assertions that are required to check that the actual object at run time has this type, in pseudo code something like assert($records instanceof array<int,DateTime|null>)
  3. The type cast that will tell static analysers (this is meant to be psalm at the moment) what's the exact type specification after the cast, or in pseudo code(array<int,DateTime|null>) $records
  4. The ability of deriving the types from other types without doing string manipulation, expressed in pseudo code as something like array<int,DateTime|null> || null

This library provides the basic building blocks for type specifications. For example the following expression

$type = _map(
  _int(), 
  _union(
    _class(DateTime::class), 
    _null()
  )
)

creates an object of type Type<array<int,DateTime|null>>.

This object can be used in following ways

Assert at run time that the type of $records is array<int,DateTime|null>>:

assert($type($records));

Cast $records to array<int,DateTime|null>> and throw an exception when $records are not of type array<int,DateTime|null>> when assertions are enabled:

return $type->cast($records);

Cast $records to array<int,DateTime|null>> or throw a runtime exception if cast fails:

return $type->castOrFail($records);

Combine type with other types, for example, making it nullable array<int,DateTime|null>>|null:

_union($type, _null())

Object like arrays

Object like arrays are specified as intersections of simpler property types. For example for type array{id:int,name:string,valid?:bool} corresponds to this construct:

$type = _intersection(
    _property('id', true, _int()),
    _property('name', true, _string()),
    _property('valid', false, _bool())
);

Quite a mouthful. But it allows us to do things like this