Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix class namespaces from uses #953

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
106 changes: 103 additions & 3 deletions src/Method.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@

use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag;
use Barryvdh\Reflection\DocBlock\Tag\ReturnTag;
use Barryvdh\Reflection\DocBlock\Tag\ParamTag;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag\ReturnTag;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

Expand All @@ -37,6 +37,7 @@ class Method
protected $real_name;
protected $return = null;
protected $root;
protected $uses = array();

/**
* @param \ReflectionMethod|\ReflectionFunctionAbstract $method
Expand All @@ -53,12 +54,16 @@ public function __construct($method, $alias, $class, $methodName = null, $interf
$this->real_name = $method->isClosure() ? $this->name : $method->name;
$this->initClassDefinedProperties($method, $class);

// TODO: Runtime-cache this.
$this->uses = $this->getUses($class);

//Reference the 'real' function in the declaring class
$this->root = '\\' . ltrim($class->getName(), '\\');

//Create a DocBlock and serializer instance
$this->initPhpDoc($method);


//Normalize the description and inherit the docs from parents/interfaces
try {
$this->normalizeParams($this->phpdoc);
Expand Down Expand Up @@ -237,7 +242,8 @@ protected function normalizeParams(DocBlock $phpdoc)
$tag->setContent($content);

// Get the expanded type and re-set the content
$content = $tag->getType() . ' ' . $tag->getVariableName() . ' ' . $tag->getDescription();
$type = $this->substituteMissingClasses($tag->getType());
$content = $type . ' ' . $tag->getVariableName() . ' ' . $tag->getDescription();
$tag->setContent(trim($content));
}
}
Expand All @@ -263,6 +269,8 @@ protected function normalizeReturn(DocBlock $phpdoc)
$returnValue = str_replace($interface, $real, $returnValue);
}

$returnValue = $this->substituteMissingClasses($returnValue);

// Set the changed content
$tag->setContent($returnValue . ' ' . $tag->getDescription());
$this->return = $returnValue;
Expand Down Expand Up @@ -370,4 +378,96 @@ protected function getInheritDoc($reflectionMethod)
}
}
}

/**
* @param \ReflectionClass $class
*
* @return array
*/
protected function getUses(\ReflectionClass $class)
{
$start = false;
$currentString = '';
$currentUse = '';
$uses = [];
foreach (token_get_all(file_get_contents($class->getFileName())) as $token) {
if ($start === false) {
if (is_numeric($token[0])) {
switch (token_name($token[0])) {
case 'T_CLASS':
// Stop on reaching class definition for performance reasons.
// This leads to not catching any use statements behind the class definition.
break 2;
case 'T_USE':
$start = true;
$currentString = '';
$currentUse = '';
break;
}
}
} else {
if ($token[0] != ';') {
if (is_numeric($token[0])) {
switch (token_name($token[0])) {
case 'T_WHITESPACE':
// Skip Whitespaces.
break;
case 'T_AS':
$currentUse = $currentString;
$currentString = '';
break;
default:
$currentString .= $token[1] ?? '';
}
} else {
$currentString .= $token[1] ?? '';
}
} else {
if ($currentUse != '') {
$uses[$currentString] = $currentUse;
} else {
$uses[$this->classBasename($currentString)] = $currentString;
}

$start = false;
}
}
}
return $uses;
}

/**
* @param string $types
*
* @return string
*/
protected function substituteMissingClasses(string $types)
{
$newTypes = [];
foreach (explode('|', $types) as $type) {
if (!class_exists($type)) {
$baseClassName = $this->classBasename($type);

if ($this->uses[$baseClassName] ?? false) {
$type = $this->uses[$baseClassName];
if (substr($type, 0, 1) != '\\') {
$type = '\\' . $type;
}
}
}
$newTypes[] = $type;
}

return implode('|', $newTypes);
}

/**
* @param string $className
*
* @return string
*/
protected function classBasename(string $className)
{
return basename(str_replace('\\', '/', $className));
}
}
73 changes: 57 additions & 16 deletions tests/MethodTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

use Barryvdh\LaravelIdeHelper\Method;
use Illuminate\Database\Eloquent\Builder;
use \Illuminate\Support\Collection;
use PHPUnit\Framework\TestCase;
use Illuminate\Support\Carbon as AliasedCarbon;

class ExampleTest extends TestCase
class MethodTest extends TestCase
{
/**
* Test that we can actually instantiate the class
Expand All @@ -31,14 +33,15 @@ public function testOutput()

$method = new Method($reflectionMethod, 'Example', $reflectionClass);

$output = '/**
*
*
* @param string $last
* @param string $first
* @param string $middle
* @static
*/';
$output = "/**\n";
$output .= " * \n";
$output .= " *\n";
$output .= " * @param string \$last\n";
$output .= " * @param string \$first\n";
$output .= " * @param string \$middle\n";
$output .= " * @static \n";
$output .= " */";

$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('setName', $method->getName());
$this->assertSame('\\'.ExampleClass::class, $method->getDeclaringClass());
Expand All @@ -59,13 +62,14 @@ public function testEloquentBuilderOutput()

$method = new Method($reflectionMethod, 'Builder', $reflectionClass);

$output = '/**
* Set the relationships that should be eager loaded.
*
* @param mixed $relations
* @return \Illuminate\Database\Eloquent\Builder|static
* @static
*/';
$output = "/**\n";
$output .= " * Set the relationships that should be eager loaded.\n";
$output .= " *\n";
$output .= " * @param mixed \$relations\n";
$output .= " * @return \Illuminate\Database\Eloquent\Builder|static \n";
$output .= " * @static \n";
$output .= " */";

$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('with', $method->getName());
$this->assertSame('\\'.Builder::class, $method->getDeclaringClass());
Expand All @@ -90,6 +94,29 @@ public function testDefaultSpecialChars()
$this->assertSame('$chars = \'$\\\'\\\\\'', $method->getParamsWithDefault(true));
$this->assertSame(['$chars = \'$\\\'\\\\\''], $method->getParamsWithDefault(false));
}

public function testRespectsImportedNamespaces()
{
$reflectionClass = new \ReflectionClass(SampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('someMethod');

$method = new Method($reflectionMethod, 'SampleClass', $reflectionClass);

$output = "/**\n";
$output .= " * \n";
$output .= " *\n";
$output .= " * @param \Illuminate\Support\Collection \$collection\n";
$output .= " * @param \Illuminate\Database\Eloquent\Builder \$builder\n";
$output .= " * @param \Illuminate\Support\Carbon \$carbon\n";
$output .= " * @param \Barryvdh\LaravelIdeHelper\Tests\UnknownClass \$unknownClass\n";
$output .= " * @return \Illuminate\Support\Collection \n";
$output .= " * @static \n";
$output .= " */";

$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('someMethod', $method->getName());
$this->assertSame('\\'. SampleClass::class, $method->getDeclaringClass());
}
}

class ExampleClass
Expand All @@ -109,3 +136,17 @@ public function setSpecialChars($chars = "\$'\\")
return;
}
}

class SampleClass {
/**
* @param Collection $collection
* @param Builder $builder
* @param AliasedCarbon $carbon
* @param UnknownClass $unknownClass
*
* @return Collection
*/
function someMethod(Collection $collection, Builder $builder, AliasedCarbon $carbon, UnknownClass $unknownClass) {
return collect();
}
}