Skip to content

Function parameter defaults are incorrect for const-like values #716

@tmdk

Description

@tmdk

When determining the default value of an Argument, the result is wrong when the default value is referencing either a constant or class constant.

An example:

<?php

require __DIR__ . '/vendor/autoload.php';

use Acme\Plugin;

function foo( $output = Plugin::class ) {}

function bar( $output = OBJECT ) {}

$projectFactory = \phpDocumentor\Reflection\Php\ProjectFactory::createInstance();
$projectFiles   = [ new \phpDocumentor\Reflection\File\LocalFile( __FILE__ ) ];
$project        = $projectFactory->create( 'My Project', $projectFiles );
$file           = $project->getFiles()[ __FILE__ ];

// output: \Plugin::class
echo $file->getFunctions()['\\foo()']->getArguments()[0]->getDefault( false )->render() . PHP_EOL;

// output: object
echo $file->getFunctions()['\\bar()']->getArguments()[0]->getDefault( false )->render() . PHP_EOL;

Analysis:

\phpDocumentor\Reflection\Php\Factory\Reducer\Parameter::determineDefault() uses ExpressionPrinter to render the default value, which in turn uses TypeResolver to render Name nodes.

In case of the OBJECT const default value, the type resolver returns the type Object_ without FQSEN (which is a result, I guess, of the phpstan type parser not having enough context to properly deduce the type). In absence of a FQSEN, casting the Object_ to string returns 'object'

In case of the Plugin::class class const default value, the type resolver returns the type Object_ with FQSEN '\Plugin'. I'm guessing in this case, the problem is that the file does not have a namespace? It seems no Context is created that contains the namespace aliases / use statements, so the type resolver runs with an empty Context, leading to the incorrect result. If I add a namespace to the file, the FQSEN does resolve correctly.

When debugging this issue, I also noticed that the default values were not properly resolved by php-parser. This is due to ElementNameResolver stopping traversal of Function and Method nodes, which means the NameResolver visitor never sees the function/method parameters. I can see that you would stop traversal out of performance considerations, but is it really worth all the effort in other places to fix up the missing name resolutions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions