Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

1 Commit

Repository files navigation

Types for PHP

PHP types powered by Reflections

[!WARNING] > Experimental project – feedback is appreciated

Features:

Installation

Important

This project is not yet published to Packagist. You need to add the repository manually or clone the repository as a submodule.

Option 1: Add as a Git submodule

$ git submodule add git@github.com:attitude/types-php.git path/to/types-php

Option 2: Add as a dependency using Composer

Update composer.json of your project:

{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/attitude/types-php"
}
],
"require": {
"attitude/types": "dev-main"
}
}
$ composer install

Option 3: Download the repository as a ZIP


Usage

Shape types

Define a class extending AbstractShapeType and define properties with types just like you would with a regular class.

When creating an instance of the class, you can pass an associative array of properties. The constructor will validate the properties and throw an exception if any of the properties are missing or have the wrong type.

Unless you define const REST, the constructor will throw an exception if there are any properties in the array that are not defined in the class.

The value of the REST constant will be used as a key for all properties that are not defined in the class.

<?phprequire_once'path/to/types-php/src/Types.php';
class HeaderProps extends AbstractShapeType {
publicconstREST = '__';
publicarray$__;
publicstring$title;
public ?string$subtitle;
}
$header = newHeaderProps([
'title' => 'Title',
'extra' => 'Extra',
]);
['title' => $title, '__' => $rest] = $header;
$header; // instanceof HeaderProps::class$title; // 'Title'$rest; // ['extra' => 'Extra']

List types

To define a list of items with a specific type, use AbstractListType and provide a parse() method that will be used to parse each item.

<?phprequire_once'path/to/types-php/src/Types.php';
class HeadersList extends AbstractListType {
publicfunctionparse($item): HeaderProps {
if ($iteminstanceof HeaderProps) {
return$item;
} else {
returnnewHeaderProps($item);
}
}
}

The AbstractListType class has few methods to help you work with the list similar to JavaScript's Array class.

<?php$items = newHeadersList([
['title' => 'Title 1'],
['title' => 'Title 2'],
]);
$items->length; // 2$items->push(newHeaderProps(['title' => 'Title 3']));
$items->map(function ($item) {
return$item->title;
}); // ['Title 1', 'Title 2', 'Title 3']

Enjoy!

Created by martin_adamko

About

PHP types powered by Reflections

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages