Add scalar type hints and return types to existing PHP projects using PHPDoc annotations

Overview

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_return_type rules) or Rector instead.

phpdoc-to-typehint adds automatically scalar type hints and return types to all functions and methods of a PHP project using existing PHPDoc annotations.

Build Status

Warning: this project is an early stage of development. It can damage your code. Be sure to make a backup before running this command and to run your test suite after.

Please report any bug you find using this tool.

Install and usage

  1. Download the latest PHAR file
  2. Run php phpdoc-to-typehint.phar <your-project-directory>

Your project should have scalar type hints and return type declarations.

Before:

<?php

/**
 * @param int|null $a
 * @param string   $b
 *
 * @return float
 */
function bar($a, $b, bool $c, callable $d = null)
{
    return 0.0;
}

After:

<?php

/**
 * @param int|null $a
 * @param string   $b
 *
 * @return float
 */
function bar(int $a = null, string $b, bool $c, callable $d = null) : float
{
    return 0.0;
}

Features

Supports:

  • functions
  • methods of classes and traits
  • method definitions in interfaces
  • PHPDoc inheritance
  • PHP 7.1 nullable types (can be disabled with --no-nullable-types option)

Credits

Created by Kévin Dunglas. Sponsored by Les-Tilleuls.coop.

Comments
  • @see is mistaken for a type

    @see is mistaken for a type

    The following class instance variable:

        /**
         * If you’ve enabled user specific timezones, you may set or update the
         * user timezone.
         * @see https://docs.looker.com/reference/embedding/timezones
         * @var string|null
         */
        public $userTimeZone = null;
    

    Produces the error:

      [InvalidArgumentException]
      "\Kounta\Insights\Looker\https://docs.looker.com/reference/embedding/timezones" is not a valid Fqsen.
    
    opened by elliotchance 10
  • Cannot ue 'Void' as class name

    Cannot ue 'Void' as class name

    using the latest release v.0.1.0 I am running into the following error

    $ php phpdoc-to-typehint.phar .
    PHP Fatal error:  Cannot use 'Void' as class name as it is reserved in phar://C:
    /Users/mstaab/Documents/GitHub/deployer/phpdoc-to-typehint.phar/vendor/phpdocume
    ntor/type-resolver/src/Types/Void.php on line 23
    
    Fatal error: Cannot use 'Void' as class name as it is reserved in phar://C:/User
    s/mstaab/Documents/GitHub/deployer/phpdoc-to-typehint.phar/vendor/phpdocumentor/
    type-resolver/src/Types/Void.php on line 23
    

    seems like the downloaded phar is unusable to run on php7.1+

    $ php -v
    PHP 7.1.2 (cli) (built: Feb 14 2017 21:24:45) ( NTS MSVC14 (Visual C++ 2015) x64 )
    Copyright (c) 1997-2017 The PHP Group
    Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
    
    opened by staabm 7
  • First paramert is ofthen not hinted

    First paramert is ofthen not hinted

    Before

        /**
         * The copy the specified message(s) to a specified mailbox.
         *
         * @param string $msgSet  Message(s) to fetch
         * @param string $mailbox Name of mailbox to copy messages to
         * @param bool   $uid     Weather to use UID
         *
         * @return array Raw from responce()
         */
        public function copy($msgSet, $mailbox, $uid = false)
        {
        }
    

    after

        /**
         * The copy the specified message(s) to a specified mailbox.
         *
         * @param string $msgSet  Message(s) to fetch
         * @param string $mailbox Name of mailbox to copy messages to
         * @param bool   $uid     Weather to use UID
         *
         * @return array Raw from responce()
         */
        public function copy($msgSet, string $mailbox, bool $uid = false): array
        {
        }
    
    opened by AJenbo 6
  • Convert tests to PHPUnit

    Convert tests to PHPUnit

    • Add development dependency on phpunit/phpunit ^6.0
    • Update composer.lock for PHPUnit only
    • Change .travis.yml to use PHPUnit in vendor directory
    • Put expected test results into a new directory
    opened by ricordisamoa 4
  • Support PHP7.1

    Support PHP7.1

    Hello,

    Are there any plans to support PHP7.1 new type declarations and nullable types? Example:

    function returnsNothing(iterable $iterable, ?string $nullableString): void {
    ...
    }
    
    opened by zalsader 4
  • converter: apply whitelist filtering on supported types

    converter: apply whitelist filtering on supported types

    Only in effect on all-lowercase types. This is to filter out stuff like mixed, void, $this, etc.

    Currently return type hints like mixed, void or $this, which are quite common, get converted literally into PHP.

    mixed and void are expected to be classes, $this isn't an allowed syntax.

    The idea of this PR is that, in case the whole type hint is in lowercase, it must be one of the supported type declarations as listed at http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration ; otherwise the type hint gets just ignroed.

    This automatically filters out a lot of unsupported stuff.

    An edge case is when referring to all-lowercase classes. This PR wouldn't support them.

    If this is acceptable, I can provide tests too.

    opened by mfn 3
  • Bump dependencies to support up to PHP 7.3

    Bump dependencies to support up to PHP 7.3

    This works, but I cannot get phpunit anymore as a dependency. This because of phpspec/prophecy does not support phpdocumentor/reflection-docblock:^5 yet.

    Should I go for including the phpunit.phar archive ? Should we wait the support of phpdocumentor/reflection-docblock:^5 by prophecy? Maybe another solution...

    WDYT ?

    opened by GregoireHebert 2
  • By reference is applied in correctly

    By reference is applied in correctly

    /**
     * @param array $array
     */
    function test(&$array) {}
    

    Becomes

    /**
     * @param array $array
     */
    function test(&array $array) {}
    

    Should have been

    /**
     * @param array $array
     */
    function test(array &$array) {}
    
    opened by AJenbo 2
  • Example in readme is invalid

    Example in readme is invalid

    I don't think it is correct to generate code which will put an argument with a default value before an argument without a default value.

    In the example the generated code produces a function like that:

    function bar(int $a = null, string $b, bool $c, callable $d = null) : float
    

    This means the first argument is optional, but the second and third aren't.

    I realise = null is the only way in PHP before 7.1 to specify a type-hinted argument could also be null, but generating such code I think is incorrect.

    My suggestion is to never make a parameter without a default value to have one.

    When PHP 7.1 is available - #16, the example could be using ?int which would be correct.

    opened by hkdobrev 2
  • RFC: Do not change method signature when this would break inheritance

    RFC: Do not change method signature when this would break inheritance

    If the function is overriding a parent method there are limitations to changing the method signature. Future PHP versions could improve that with more support for Covariance and Contravariance, but there are still cases where signatures could not blindly be changed.

    If the PHPDoc to typehints conversion take this into account and don't change things which would produce a direct PHP error it would be less risky and could be deployed more widely. It could even work in a CI environment.

    opened by hkdobrev 1
  • Constant visibility is not supported

    Constant visibility is not supported

    Code like this:

    
    class Foo
    {
    	public const BAR = 1;
    }
    

    produces the following error:

    [PhpParser\Error]
      Syntax error, unexpected T_CONST, expecting T_FUNCTION on line 16
    

    This is valid code in PHP 7.1.

    opened by hkdobrev 1
Releases(v0.1.0)
Owner
Kévin Dunglas
Founder of @coopTilleuls / Creator of @api-platform, Mercure.rocks and Vulcain.rocks / @symfony Core Team
Kévin Dunglas
Collection of value objects that represent the types of the PHP type system

sebastian/type Collection of value objects that represent the types of the PHP type system. Installation You can add this library as a local, per-proj

Sebastian Bergmann 1.1k Dec 29, 2022
TYPO3 Extension for on-the-fly evaluation hints in FormEngine

OTF - A TYPO3 extension to display on-the-fly evaluation hints in FormEngine This TYPO3 extension allows to add a FormEngine FieldWizard to specific T

b13 GmbH 3 Sep 22, 2022
H&O Magento 2 Advanced Template Hints module

H&O Magento 2 Advanced Template Hints module Ho_Templatehints extends the default Magento template hints. Easily accessible with muscle memory ?ath=1.

Reach Digital 245 Dec 22, 2022
It allows frontend developer to send ajax requests and return a custom information from the server without a php developer help

[Magento 1 Extension] It allows frontend developer to send ajax requests and return a custom information from the server without a php developer help (without any php code).

Vladimir Fishchenko 62 Apr 1, 2022
Miniset allows you to create compact sets of fields that either combine into a string of classes, or return a simple array of values

Miniset allows you to create compact sets of fields that either combine into a string of classes, or return a simple array of values. Miniset

Jack Sleight 5 Jun 13, 2022
Simple user settings facade for Hyperf. Settings are stored as JSON in a single database column, so you can easily add it to an existing table.

hyperf-user-settings Simple user settings util for hyperf Settings are stored as JSON in a single database column, so you can easily add it to an exis

lysice 1 Oct 15, 2021
This package makes it easy to add early access mode to your existing application.

This package makes it easy to add early access mode to your existing application. This is useful for when you want to launch a product and need to gat

Neo 174 Nov 26, 2022
A package for adding more type safety to your PHP projects.

Table of Contents Overview Installation Usage Simple Checks Advanced Checks Custom Checks Skipping Checks Testing Security Contribution Credits Change

Ash Allen 14 Aug 31, 2022
Magento 2 Module that adds Donation Product Type. Enables the customer to add a donation (product) of a preferred amount to the cart.

Magento 2 Module Experius DonationProduct (RC1.0) Demo website: https://donationproduct.experius.nl Magento Marketplace: https://marketplace.magento.c

Experius 23 Apr 1, 2022
A Bayesian average is a method of estimating the mean of a population using outside information, especially a pre-existing belief, which is factored into the calculation

A Bayesian average is a method of estimating the mean of a population using outside information, especially a pre-existing belief, which is factored into the calculation.

Assisted Mindfulness 3 Oct 19, 2022
Annotations Docblock Parser

Doctrine Annotations Docblock Annotations Parser library (extracted from Doctrine Common). Documentation See the doctrine-project website. Contributin

Doctrine 6.6k Dec 29, 2022
SilverStripe Model Annotations Task

A SilverStripe Task to generate data object model annotations for defined db fields. Also for configs from data extensions.

CSoellinger 2 Apr 21, 2022
Guest to Customer for Magento2 - Quickly and easily convert existing guest checkout customers to registered customers.

Guest to Customer for Magento 2.0 For Magento 2.0.x, 2.1.x, 2.2.x, 2.3.x and 2.4.x In general E-commerce, shoppers do not like to create an account du

MagePal :: Magento Extensions 66 Oct 7, 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
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
Mobile detect change theme and redirect based on device type. Magento 2 module.

Magento 2 Mobile Detect Theme Change Magento 2 Mobile detect system can be used to load different themes base on the client device (desktop, tablet, m

EAdesign 27 Jul 5, 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