Skip to content

Commit

Permalink
Fixes #1686 - support union types
Browse files Browse the repository at this point in the history
  • Loading branch information
mrook committed Jan 4, 2023
1 parent 9ee595a commit 5572e30
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/Phing/IntrospectionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,7 @@ public function __construct($class)
);
}

/** @var ReflectionType $hint */
$classname = (($hint = $params[0]->getType()) && !$hint->isBuiltin()) ? $hint->getName() : null;
$classname = $this->getClassnameFromParameter($params[0]);

if (null === $classname) {
throw new BuildException(
Expand Down Expand Up @@ -235,8 +234,7 @@ public function __construct($class)
);
}

/** @var ReflectionType $hint */
$classname = (($hint = $params[0]->getType()) && !$hint->isBuiltin()) ? $hint->getName() : null;
$classname = $this->getClassnameFromParameter($params[0]);

// we don't use the classname here, but we need to make sure it exists before
// we later try to instantiate a non-existent class
Expand Down Expand Up @@ -451,8 +449,7 @@ public function createElement(Project $project, $element, $elementName)
// exist and that method is using class hints
$params = $method->getParameters();

/** @var ReflectionType $hint */
$classname = (($hint = $params[0]->getType()) && !$hint->isBuiltin()) ? $hint->getName() : null;
$classname = $this->getClassnameFromParameter($params[0]);

// create a new instance of the object and add it via $addMethod
$clazz = new ReflectionClass($classname);
Expand Down Expand Up @@ -654,4 +651,18 @@ public function warn($msg)
echo '[IntrospectionHelper] ' . $msg . "\n";
}
}

/**
* @param \ReflectionParameter $parameter
* @return mixed|null
*/
private function getClassnameFromParameter(\ReflectionParameter $parameter)
{
/** @var ReflectionType $reflectionType */
$reflectionType = $parameter->getType();
if ($reflectionType instanceof \ReflectionNamedType) {
return !$reflectionType->isBuiltin() ? $reflectionType->getName() : null;
}
return null;
}
}
16 changes: 16 additions & 0 deletions tests/Phing/IntrospectionHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,22 @@ public function testElementCreators(): void
$this->assertEquals($fs, $ih->createElement($this->p, new IHProjectComponent(), 'FileSet'));
}

/**
* @requires PHP >= 8
* @return void
*/
public function testUnionTypeOnSetterDoesNotCrashIH(): void
{
$clz = eval('return new class {
public function setSomeAttribute(bool | string $attribute) {
}
};');

$ih = IntrospectionHelper::getHelper(get_class($clz));
$this->assertContains('someattribute', $ih->getAttributes());
}

/*
public function testGetNestedElements()
{
Expand Down

0 comments on commit 5572e30

Please sign in to comment.