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

Related tags

Miscellaneous type
Overview

sebastian/type

CI Status Type Coverage

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

Installation

You can add this library as a local, per-project dependency to your project using Composer:

composer require sebastian/type

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

composer require --dev sebastian/type
Comments
  • "false" pseudo type is not handled properly

    | Q | A | --------------------| --------------- | PHPUnit version | 9.5.5 | PHP version | 8.0.6 | Installation Method | Composer

    Summary

    When mocking a method which returns false|int, I get the error below.

    There was 1 error:
    
    1) AckintoshTest::test
    PHPUnit\Framework\MockObject\IncompatibleReturnValueException: Method foo may not return value of type boolean, its return declaration is "false|int"
    

    How to reproduce

    <?php
    use PHPUnit\Framework\TestCase;
    
    class AckintoshTest extends TestCase
    {
        /**
         * @test
         */
        public function test()
        {
            $m = $this->getMockBuilder(Ackintosh::class)
                      ->setMethods(['foo'])
                      ->getMock();
            $m->expects($this->once())
              ->method('foo')
              ->willReturn(false);
    
            $this->assertFalse($m->foo());
        }
    }
    
    class Ackintosh
    {
        function foo(): false|int
        {
            return false;
        }
    }
    
    $ vendor/bin/phpunit .
    
    PHPUnit 9.5.5 by Sebastian Bergmann and contributors.
    
    Warning:       No code coverage driver available
    
    E                                                                   1 / 1 (100%)
    
    Time: 00:00.023, Memory: 6.00 MB
    
    There was 1 error:
    
    1) AckintoshTest::test
    PHPUnit\Framework\MockObject\IncompatibleReturnValueException: Method foo may not return value of type boolean, its return declaration is "false|int"
    
    /Users/abi01357/test/phpunit/tests/AckintoshTest.php:16
    

    Expected behavior

    The mock returns false.

    bug 
    opened by ackintosh 3
  • Fixed ObjectType to be assignable from the PHP

    Fixed ObjectType to be assignable from the PHP "object" type

    This should fix the issue raised here. Basically, this allows object types to be assignable from object. Before, we were only checking if the object was the same class or a subclass of the type you're trying to assign to.

    bug 
    opened by davidbyoung 3
  • Upgrade/php 8.1 constructor properties

    Upgrade/php 8.1 constructor properties

    Noticed some more improvements to be made, thought I'd waste some time doing just that.

    Needless to say, this is a BC-break because of all the method-to-public-property changes.

    I see that CI/Coding Guidelines fails because of braces php-cs-fixer rule; that is because php-cs-fixer does not yet support constructor property promotion, it wants the empty braces to be split into two lines.

    opened by jurchiks 2
  • Minor optimisation in `IntersectionType`

    Minor optimisation in `IntersectionType`

    Hi,

    I was evaluating this library today for a custom typed generator that I'm developing and I noticed something and I wanted to share what I have in mind.

    Current code:

    private function ensureNoDuplicateTypes(Type ...$types): void
    {
      $names = [];
      
      foreach ($types as $type) {
          assert($type instanceof ObjectType);
      
          $names[] = $type->className()->qualifiedName();
      }
      
      if (count(array_unique($names)) < count($names)) {
          throw new RuntimeException(
              'An intersection type must not contain duplicate types'
          );
      }
    }
    

    The time complexity for this would be:

    • foreach loop: $\mathcal{O}(n)$
    • first count: $\mathcal{O}(1)$
    • array_unique:
      • Worst case: $\mathcal{O}(n)$
      • Best case: $\Omega(n)$
    • second count: $\mathcal{O}(1)$

    What matter here in this snippet is that, no matter how many groups of duplicates $types contains, it will always traverse the full array, this is why $\mathcal{O}(n) == \Omega(n)$ in the first case. However, what we are looking for here, is to throw an exception as soon as there is a duplicate.

    And here we have two scenarios:

    • worst case scenario( $\mathcal{O}$ ): the last item is a duplicate
    • best case scenario( $\Omega$ ): the second item is a duplicate

    Here's what I propose:

    private function ensureNoDuplicateTypes(Type ...$types): void
    {
      $names = [];
      
      foreach ($types as $type) {
          assert($type instanceof ObjectType);
      
          $classQualifiedName = $type->className()->qualifiedName();
      
          $names[] = in_array($classQualifiedName, $names, true)
              ? throw new RuntimeException('An intersection type must not contain duplicate types')
              : $classQualifiedName;
      }
    }
    

    What I propose is to break the loop as soon as a duplicate is found.

    The time complexity for this would be:

    • foreach loop: $\mathcal{O}(n)$
    • in_array:
      • Worst case: $\mathcal{O}(n)$
      • Best case: $\mathcal{O}(2)$
      • Between best and worst cases: $\mathcal{O}(m)$ with $(m < n)$

    What do you think? Actually I often see such things in PHP here and there and I'm wondering if introducing pull-requests for changing these kind of subtle things make sense. Do you think it worth submitting a PR ?

    Thanks in advance.

    opened by drupol 2
  • Check Type::isAssignable() implementations with regard to nullability

    Check Type::isAssignable() implementations with regard to nullability

    @stof wrote:

    2 types allowing null are not automatically assignable to each other. Null is assignable to a type allowing null. And a type allowing null is not assignable to a type not allowing null. But ?string is not assignable to ?int

    opened by sebastianbergmann 2
  • parse nullables and union types

    parse nullables and union types

    I'm not sure if you want this, but I would find it useful if this package was able to parse union type names and nullables. I implemented it in one of my projects using your package and thought "maybe it could be interesting for the main package too" :)

    opened by Dgame 2
  • No support for special

    No support for special "iterable" type

    Newest PHPUnit version 8.2.0 gives us a lot of warnings ("Method ... may not return value of type array") when mocking methods which have "iterable" as return type hint and giving arrays as return value.

    Perhaps this should be its own Type-Class here?

    bug 
    opened by bug-tape 2
  • Backport 8.0 and 8.1 types into branch

    Backport 8.0 and 8.1 types into branch

    As part of https://github.com/sebastianbergmann/phpunit/issues/4879 you mentioned you were happy to accept pull requests for backporting union types into PHPUnit 8. As that ships with v1 of types this does a equivalent backport of both Union and Intersection types (as I was doing the union ones in the first place).

    opened by wilsonge 1
  • Enhancement: Switch to using GitHub actions

    Enhancement: Switch to using GitHub actions

    This PR

    • [x] switches to using GitHub Actions instead of Travis CI

    Fixes #7.

    💁‍♂ Note that GitHub Actions aren't triggered here because I'm pushing from a fork and the workflow does not exist yet.

    opened by localheinz 1
  • Support Disjunctive Normal Form types

    Support Disjunctive Normal Form types

    PHP 8.2 adds support for Disjunctive Normal Form Types:

    This RFC does not introduce any new reflection classes. However, it does make one change to the Reflection API, in that ReflectionUnionType::getTypes() previously was guaranteed to always return an array of ReflectionNamedType instances. Now it will return some combination of ReflectionNamedType and ReflectionIntersectionType instances. The method is already typed to return ReflectionType so this is not an API change, but the previous de facto assumption is no longer valid.

    type/change-in-php-requires-adaptation 
    opened by sebastianbergmann 0
  • Restore skipped tests after merge in php-src

    Restore skipped tests after merge in php-src

    Reverts 6a84c28d0af3f09ffd407b0391796a87d2c07b07

    https://github.com/php/php-src/pull/7546 has been merged so these tests can be "unskipped".

    opened by alexislefebvre 0
  • Class is unassignable to its ClassAlias

    Class is unassignable to its ClassAlias

    This issue comes to me when I try to mock method in PHPUnit witch returns Some_Class_Name but this is a class alias and real class name is like \Some\Class\Name.

    Code is better than 1000 words, so I prepare PR: https://github.com/sebastianbergmann/type/pull/17

    bug 
    opened by vojtabiberle 0
Owner
Sebastian Bergmann
Sebastian Bergmann is the creator of PHPUnit. He co-founded thePHP.cc and helps PHP teams build better software.
Sebastian Bergmann
📦 "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

♚ PH⑦ de Soria™♛ 4 Dec 15, 2022
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
A PHP 7 value objects helper library.

valueobjects Requirements Requires PHP >= 7.1 Installation Through Composer, obviously: composer require funeralzone/valueobjects Extensions This lib

Funeral Zone 56 Dec 16, 2022
Parse DSN strings into value objects to make them easier to use, pass around and manipulate

DSN parser Parse DSN strings into value objects to make them easier to use, pass around and manipulate. Install Via Composer composer require nyholm/d

Tobias Nyholm 77 Dec 13, 2022
A bunch of general-purpose value objects you can use in your Laravel application.

Laravel Value Objects A bunch of general-purpose value objects you can use in your Laravel application. The package requires PHP ^8.0 and Laravel ^9.7

Michael Rubél 136 Jan 4, 2023
A collection of type-safe functional data structures

lamphpda A collection of type-safe functional data structures Aim The aim of this library is to provide a collection of functional data structures in

Marco Perone 99 Nov 11, 2022
Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Super Simple DTO Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Mohammed Manssour 8 Jun 8, 2023
PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects.

?? Yell PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects. Requirement

Zeeshan Ahmad 20 Dec 8, 2018
Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.DeepEqual().

Deeper Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.De

Joubert RedRat 4 Feb 12, 2022
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

EndermanbugZJFC 9 Aug 22, 2022
A collection of command line scripts for Magento 2 code generation, and a PHP module system for organizing command line scripts.

What is Pestle? Pestle is A PHP Framework for creating and organizing command line programs An experiment in implementing python style module imports

Alan Storm 526 Dec 5, 2022
Smd tags - A Textpattern CMS plugin for unlimited, structured taxonomy across content types.

smd_tags Tag articles, images, files and links with stuff, then use the public-side tags to display the lists, filter or find related content. Feature

Stef Dawson 4 Dec 26, 2022
A composer plugin, to install differenty types of composer packages in custom directories outside the default composer default installation path which is in the vendor folder.

composer-custom-directory-installer A composer plugin, to install differenty types of composer packages in custom directories outside the default comp

Mina Nabil Sami 136 Dec 30, 2022
Sync Wordpress Pages and Posts (even custom post types + fields) from static Markdown + YAML files

Sync Markdown Files to WordPress Posts and Pages Static site generators let you use a revision-controlled tree of markdown files to make a site, but d

null 26 Sep 26, 2022
PHP library that helps to map any input into a strongly-typed value object structure.

Valinor • PHP object mapper with strong type support Valinor is a PHP library that helps to map any input into a strongly-typed value object structure

Team CuyZ 873 Jan 7, 2023
Enable method chaining or fluent expressions for any value and method.

PHP Pipe Operator A (hopefully) temporary solution to implement the pipe operator in PHP. Table of contents Requirements How to install How to use The

Sebastiaan Luca 268 Dec 26, 2022
Immutable value object for IPv4 and IPv6 addresses, including helper methods and Doctrine support.

IP is an immutable value object for (both version 4 and 6) IP addresses. Several helper methods are provided for ranges, broadcast and network address

Darsyn 224 Dec 28, 2022
Decimal handling as value object instead of plain strings.

Decimal Object Decimal value object for PHP. Background When working with monetary values, normal data types like int or float are not suitable for ex

Spryker 16 Oct 24, 2022