Next generation phpDoc parser with support for intersection types and generics.

Overview

PHPDoc-Parser for PHPStan

Build Status Latest Stable Version License PHPStan Enabled


Next generation phpDoc parser with support for intersection types and generics.

Code of Conduct

This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.

Building

Initially you need to run composer install, or composer update in case you aren't working in a folder which was built before.

Afterwards you can either run the whole build including linting and coding standards using

vendor/bin/phing

or run only tests using

vendor/bin/phing tests
Comments
  • Support @template tag

    Support @template tag

    This adds support for the @template tag, with the following syntax:

    @template name [of boundType] [description]
    

    Examples:

    @template T
    @template T of DateTime the value type
    @template T of DateTime
    @template T the value type
    

    Related: https://github.com/phpstan/phpstan/pull/1692

    Semantically, @template declares that the given name referer to a templated type in the scope of the related code object. The actual type is decided by the user of the code; boundType defines a constraint on this type.

    opened by arnaud-lb 24
  • Type projections

    Type projections

    This PR adds support for parsing type projections (phpstan/phpstan#3290) which I'd like to implement in PHPStan. Type projections are a way of declaring the variance of a type parameter at the site of use rather than at the site of its declaration (via @template-covariant). This allows you to have the type parameter in an incompatible position in the generic class, and only prevents you from using it where the projection is used.

    Type projection can be created in the type argument position of a generic type by using either:

    /**
     * @param Box<covariant Animal> $covariant
     * @param Box<contravariant Cat> $contravariant
     * @param Box<*> $star
     */
    

    The choice of the variance keywords favours consistency: while Kotlin uses in and out which might arguably be more intent-revealing, PHPStan already uses @template-covariant in a similar position, so I say let's stick with it.

    One thing I'm not sure about is whether Foo<covariant> should throw a parse error (as currently implemented), or whether it should create an IdentifierTypeNode('covariant'). The former is potentially a BC break if somebody has a class named covariant in their code, and however unlikely it seems, you can always break somebody's build 🤔

    opened by jiripudil 23
  • Enhance support for multiple line descriptions

    Enhance support for multiple line descriptions

    I didn't want to touch \PHPStan\PhpDocParser\Parser\TokenIterator, which I think could be refactored to properly implement the \Iterator interface. That seemed like a task of its own.

    This loops over the tokens passed to \PHPStan\PhpDocParser\Parser\PhpDocParser::parseDeprecatedTagValue and builds the entire message.

    opened by mglaman 18
  • @param type can be omitted

    @param type can be omitted

    According to https://docs.phpdoc.org/3.0/guide/references/phpdoc/tags/param.html, the type may be omitted. This is especially useful in PHP 8 applications, which can almost fully typehint all arguments. The type in the PHPdoc in this case is redundant and may only lead to out-of-sync types.

    PHPstorm and Psalm already appear to support this. However, this is not yet the case with PHPstan: https://phpstan.org/r/691a2424-e087-45a0-a9ce-774a57f887ec

    (fyi, we're about to remove the types in Symfony, which is why I checked support in the popular static analysis libraries)

    opened by wouterj 16
  • Version 1.6 removes endlines

    Version 1.6 removes endlines

    Our CI started to crash with removed endlines: https://github.com/symplify/symplify/pull/4148/commits/36230195b068dffdc0c269e12fc094f45d176963

    Any ideas what is causing it and how to fix it?

    opened by TomasVotruba 15
  • Array shapes support

    Array shapes support

    Adds support for parsing array shapes (object-like arrays).

    Examples:

    array{'foo': int, "bar": string}
    array{0: int, 1?: int}
    array{int, int}
    array{foo: int, bar: string}
    

    Keys can be single quoted strings, double quoted strings, integers, or identifiers (represented as ConstExprStringNode, ConstExprIntegerNode, IdentifierTypeNode).

    They can be marked optional with a ? before the key and the :.

    They can be omitted entirely.

    Values can be any type, including nullable types or nested array shapes.

    opened by arnaud-lb 13
  • request re: shapes

    request re: shapes

    Are there any plans to support the kinds of shapes that psalm supports in docblocks?

    i.e. array<class-string<Foo>, array<int, class-string<Bar>>> ?

    opened by SignpostMarv 12
  • request for clarification re: return types for generators

    request for clarification re: return types for generators

    What's the appropriate docblock here?

    function Foo() : Generator {
        yield from [
            ['foo', 123, ['foo' => ['bar', 'baz', null]]],
            ['bar', 456, ['foo' => ['bar', 'baz', null]]],
            ['baz', 789, ['foo' => ['bar', 'baz', null]]],
        ];
    }
    
    opened by SignpostMarv 12
  • Native types shouldn't try to use the current namespace

    Native types shouldn't try to use the current namespace

    Hi,

    It seems phpdoc-parser tries to use the files' namespace even for native types. Not sure how to best explain this, let me do my best.

    There this really odd issue on the Safe library where phpstan + larastan would throw an error on any library using the Safe package. At first I thought the error was on larastan but after they fixed what I thought was the root cause, the error was still there, so after some more debugging (thank $DEITY for xdebug) I found out that the problem was on the library (or on phpdoc-parser, it could be fixed on both places).

    Long story short, the library is basically a bunch of files redeclaring native php functions, the issue is that whenever there's a phpdoc on one of their files using @param array or @return array, since all function files are namespaced under Safe, the parser tries to use the type Safe\array, which unfortunately has a PSR4 match on their array.php file. The bug appeared when the library was used together with larastan because larastan checks if any of the parameters is a subclass of one of Laravel's Eloquent classes on one of their extensions, triggering the second loading of the same file (doing (new ObjectType(Model::class))->isSuperTypeOf(new ObjectType($nameScope->resolveStringName('Safe\array')))->yes()). I (erroneously) thought that adding \ to the array will force it to be on the global namespace but it turns out that \array is not a valid type for phpstan.

    Anyway, I believe the native types from PHP should take precedence when being parsed (same than the actual PHP behaviour), maybe with some sort of list to be compared with when parsing the types from @param and @return, although I'm not fully familiar with the implementation to make a proper suggestion.

    Please, let me know if there are any doubts so I can explain further, not my best day today :stuck_out_tongue:

    opened by j3j5 11
  • Support multiple lines for array shape

    Support multiple lines for array shape

    Possible fix for https://github.com/phpstan/phpstan/issues/2497

    Hey there, great library, fantastic work to all involved. So, like a lot of folks I'm excited about using array shapes, but without multiline syntax it doesn't really seem practical.

    I haven't done much with parsers since my school days of long ago, and I was told that you have previously dismissed this idea as not feasible, so please tell me what I'm doing wrong.

    opened by shmax 10
  • Multiline return fails to parse

    Multiline return fails to parse

    Having this phpDoc:

        /**
         * Parses and builds AST for the given Query.
         *
         * @return \Doctrine\ORM\Query\AST\SelectStatement |
         *         \Doctrine\ORM\Query\AST\UpdateStatement |
         *         \Doctrine\ORM\Query\AST\DeleteStatement
         */
    

    PHPStan 0.9.2 errors with:

      234    PHPDoc tag @return has invalid value (\Doctrine\ORM\Query\AST\SelectStatement |): Unexpected token "\n     *", expected TOKEN_IDENTIFIER at offset 117
    

    This is currently used in Doctrine: https://github.com/doctrine/doctrine2/blob/2de6c807c8617b888bbb9da8b0908648432b3673/lib/Doctrine/ORM/Query/Parser.php#L227

    Is this by design, bug or simply overseen case?

    opened by Majkl578 10
  • "New in initializers" breaks in docblock

    Bug report

    Since PHP 8.1, it is possible to use new as default parameters ("new in initializers" RFC).

    PHPStan gets it perfectly, but things stop working once we move them to docblocks, explicitly the @method docblock (see example).

    Code snippet that reproduces the problem

    https://phpstan.org/r/5d0cdcbb-5c11-4483-90b0-b95986f92bc2

    Expected output

    Since PHPStan understands the "new in initializers" in the code, I guess that this is a missed use-case instead of an actual bug, but I didn't know where to report it.

    Did PHPStan help you today? Did it make you happy in any way?

    Every. single. day.

    Thanks for this amazing tool!

    opened by juampi92 1
  • Allow method tag return type to be by reference

    Allow method tag return type to be by reference

    Like normal methods the method tag might return by reference. This fix introduces the support of reference return types. However in a real world implementation it not very likely one would ever mix reference return types with none reference return types. If even possible using php __call.

    fixes #158

    opened by jaapio 0
  • [PSR-5] param tag with optional values

    [PSR-5] param tag with optional values

    The param requires a paramname, however, this could be omitted when the param tag is describing just a single argument method or all other params are adequately documented. For example:

    /**
     * @param int
     * /
     public function foo($arg): void 
    {}
    
    /**
     * @param int $arg
     * @param int Optional description
     * /
     public function foo($arg, $second): void 
    {}
    

    I do see this as edge cased, but it makes makes more sense when you align this with other tags for example the @var tag. Which has the same behavior.

    class Foo {
        /** @var int */
       public $bar
    }
    
    class Foo {
        /** 
         * @var int
         * @var string $foo
         */
       public $bar $foo
    }
    

    I'm working on a pr to support this.

    opened by jaapio 0
  • Random ClassNotFoundError PhpStanExtractor.php line 67

    Random ClassNotFoundError PhpStanExtractor.php line 67

    A few times a day, I am getting following exception in symfony project. Clearing symfony cache fixes it - any ideas what could be the issue since it's random?

    Uncaught Error: Class "PHPStan\PhpDocParser\Parser\PhpDocParser" not found
    
    Uncaught PHP Exception Symfony\Component\ErrorHandler\Error\ClassNotFoundError: "Attempted to load class "PhpDocParser" from namespace "PHPStan\PhpDocParser\Parser". Did you forget a "use" statement for another namespace?" at /home/flies/workspace/sf5/homologacja/vendor/symfony/property-info/Extractor/PhpStanExtractor.php line 67
    
    opened by fliespl 4
  • Method tag is missing return by reference

    Method tag is missing return by reference

    The MethodTagValue doesn't contain an property returnsReference. This is not a very common option to use but we found a few of them in the wild.

    Full blown example will look like this:

    /** @method static Type &myMethod() description here */
    

    I will provide a PR later when ready with other things.

    opened by jaapio 2
Releases(1.15.3)
Owner
PHPStan
PHP Static Analysis Tool - discover bugs in your code without running it!
PHPStan
allourideas allows groups to collect and priorize information in an open, democratic, and efficient process.

All Our Ideas All Our Ideas 2.0. This codebase runs two sites photocracy.org and allourideas.org. The allourideas.org project provides the user-facing

All Our Ideas 154 Dec 3, 2022
Simple and effective multi-format Web API Server to host your PHP API as Pragmatic REST and / or RESTful API

Luracast Restler ![Gitter](https://badges.gitter.im/Join Chat.svg) Version 3.0 Release Candidate 5 Restler is a simple and effective multi-format Web

Luracast 1.4k Jan 2, 2023
PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.

PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.

PhpMetrics 2.3k Jan 5, 2023
Daux.io is an documentation generator that uses a simple folder structure and Markdown files to create custom documentation on the fly. It helps you create great looking documentation in a developer friendly way.

Daux.io - Deprecation Notice This repository is deprecated! Daux.io has been moved to an organization, to guarantee future development and support. So

Justin Walsh 4.6k Dec 16, 2022
PHP 7.1 ready Smart and Simple Documentation for your PHP project

Smart and Readable Documentation for your PHP project ApiGen is the simplest, the easiest to use and the most modern api doc generator. It is all PHP

ApiGen 2.1k Dec 22, 2022
Documentation generator for PHP Code using standard technology (SRC, DOCBLOCK, XML and XSLT)

phpDox phpDox is a documentation generator for PHP projects. This includes, but is not limited to, API documentation. The main focus is on enriching t

Arne Blankerts 588 Dec 22, 2022
PHP 7.1 ready Smart and Simple Documentation for your PHP project

Smart and Readable Documentation for your PHP project ApiGen is the simplest, the easiest to use and the most modern api doc generator. It is all PHP

ApiGen 2.1k Apr 20, 2021
Daux.io is an documentation generator that uses a simple folder structure and Markdown files to create custom documentation on the fly. It helps you create great looking documentation in a developer friendly way.

Daux.io Daux.io is a documentation generator that uses a simple folder structure and Markdown files to create custom documentation on the fly. It help

Daux.io 719 Jan 1, 2023
phpDocumentor is an application that is capable of analyzing your PHP source code and DocBlock comments to generate a complete set of API Documentation

phpDocumentor What is phpDocumentor? phpDocumentor is an application that is capable of analyzing your PHP source code and DocBlock comments to genera

phpDocumentor 3.7k Jan 3, 2023
Provides tools for working with DOM documents and structures

laminas-dom This package is considered feature-complete, and is now in security-only maintenance mode, following a decision by the Technical Steering

Laminas Project 16 Jul 10, 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
PHP generics written in PHP

PHP generics written in PHP Require PHP >= 7.4 Composer (PSR-4 Autoload) Table of contents How it works Quick start Example Features Tests How it work

Anton Sukhachev 173 Dec 30, 2022
Generate Sphinx/ReStructured documentation from PHPDoc

PHP-phpdoc-to-rst Forked from Francesco "Abbadon1334" Danti by AeonDigital. In this fork the changes has only visual and superficial effects [ just be

Rianna Cantarelli 0 Nov 16, 2021
Allows the use of the Vite.js next generation frontend tooling with Craft CMS

Vite plugin for Craft CMS 3.x Allows the use of the Vite.js next generation frontend tooling with Craft CMS Related Article: Vite.js Next Generation F

nystudio107 38 Dec 30, 2022
A next-generation package manager for the front-end

Duo is a next-generation package manager that blends the best ideas from Component, Browserify and Go to make organizing and writing front-end code qu

Duo 3.4k Dec 28, 2022
:rocket: Next Generation Template / Theme Framework

Gantry Framework Ready to get started with Gantry 5? That's great! We are here to help. On this page, you will get some quick tips to help you hit the

Gantry Framework 979 Dec 31, 2022
A next generation symfony website landing page with dark mode.

Symfony Web App template themes A next generation symfony website landing page with dark mode.

Mesin Kasir 2 Aug 9, 2022
Next-generation front-end for Magento 2

The next-generation front-end for Magento 2. Fast. Reliable. Extensible. Getting started – create a new application and deploy it as Magento 2 theme o

ScandiPWA 509 Jan 2, 2023
Next generation airdrop tooling. try me!

Supporting Airdrop Task Solver Singkatnya, project ini terinspirasi oleh Viloid, tapi ini jauh lebih kompleks. Airdrop Task Solver adalah Aplikasi ber

Yuza 25 Jul 31, 2022