Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ foreach (Attributes::findTargetProperties(Column::class) as $target) {
var_dump($target->attribute, $target->class, $target->name);
}

// Find the target method-parameters of the UserInput attribute.
foreach (Attributes::findTargetMethodParameters(UserInput::class) as $target) {
var_dump($target->attribute, $target->class, $target->method, $target->name);
}

// Filter target methods using a predicate.
// You can also filter target classes and properties.
$predicate = fn($attribute) => is_a($attribute, Route::class, true);
Expand Down
51 changes: 51 additions & 0 deletions src/AttributeGroupsReflector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace olvlvl\ComposerAttributeCollector;

use PhpParser\ConstExprEvaluationException;
use PhpParser\ConstExprEvaluator;
use PhpParser\Node;
use PhpParser\Node\Expr;
use ReflectionAttribute;

/**
* @internal
*/
class AttributeGroupsReflector
{
/**
* @param Node\AttributeGroup[] $attrGroups
* @return ReflectionAttribute<object>[]
*/
public function attrGroupsToAttributes(array $attrGroups): array
{
$evaluator = new ConstExprEvaluator(function (Expr $expr) {
if ($expr instanceof Expr\ClassConstFetch && $expr->class instanceof Node\Name && $expr->name instanceof Node\Identifier) {
return constant(sprintf('%s::%s', $expr->class->toString(), $expr->name->toString()));
}

throw new ConstExprEvaluationException("Expression of type {$expr->getType()} cannot be evaluated");
});

$attributes = [];
foreach ($attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
$argValues = [];
foreach ($attr->args as $i => $arg) {
if ($arg->name === null) {
$argValues[$i] = $evaluator->evaluateDirectly($arg->value);
continue;
}

$argValues[$arg->name->toString()] = $evaluator->evaluateDirectly($arg->value);
}
$attributes[] = new FakeAttribute(
$attr->name,
$argValues,
);
}
}

return $attributes; // @phpstan-ignore return.type
}
}
22 changes: 22 additions & 0 deletions src/Attributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ public static function findTargetProperties(string $attribute): array
return self::getCollection()->findTargetProperties($attribute);
}

/**
* @template T of object
*
* @param class-string<T> $attribute
*
* @return TargetMethodParameter<T>[]
*/
public static function findTargetMethodParameters(string $attribute): array
{
return self::getCollection()->findTargetMethodParameters($attribute);
}

/**
* @param callable(class-string $attribute, class-string $class):bool $predicate
*
Expand Down Expand Up @@ -91,6 +103,16 @@ public static function filterTargetProperties(callable $predicate): array
return self::getCollection()->filterTargetProperties($predicate);
}

/**
* @param callable(class-string $attribute, class-string $class, string $property, string $method):bool $predicate
*
* @return array<TargetMethodParameter<object>>
*/
public static function filterTargetMethodParameters(callable $predicate): array
{
return self::getCollection()->filterTargetMethodParameters($predicate);
}

/**
* @param class-string $class
*
Expand Down
45 changes: 45 additions & 0 deletions src/CachedParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace olvlvl\ComposerAttributeCollector;

use Composer\IO\IOInterface;
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\Parser;

/**
* @internal
*/
class CachedParser
{
private Parser $parser;

/** @var array<string, Node[]> */
private array $parserCache = [];

public function __construct(Parser $parser)
{
$this->parser = $parser;
}

/**
* @return Node[]
*/
public function parse(string $file): array
{
if (isset($this->parserCache[$file])) {
return $this->parserCache[$file];
}
$contents = file_get_contents($file);
if ($contents === false) {
return [];
}

$ast = $this->parser->parse($contents);
assert($ast !== null);
$nameTraverser = new NodeTraverser(new NameResolver());

return $this->parserCache[$file] = $nameTraverser->traverse($ast);
}
}
125 changes: 49 additions & 76 deletions src/ClassAttributeCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@

use Attribute;
use Composer\IO\IOInterface;
use PhpParser\ConstExprEvaluationException;
use PhpParser\ConstExprEvaluator;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
Expand All @@ -16,6 +13,7 @@
use ReflectionAttribute;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use ReflectionProperty;

use function file_get_contents;
Expand All @@ -29,14 +27,12 @@
class ClassAttributeCollector
{
private IOInterface $io;
private Parser $parser;
private CachedParser $cachedParser;

/** @var array<string, Node[]> */
private array $parserCache = [];
public function __construct(IOInterface $io, Parser $parser)
{
$this->io = $io;
$this->parser = $parser;
$this->cachedParser = new CachedParser($parser);
}
/**
* @param class-string $class
Expand All @@ -45,6 +41,7 @@ public function __construct(IOInterface $io, Parser $parser)
* array<TransientTargetClass>,
* array<TransientTargetMethod>,
* array<TransientTargetProperty>,
* array<array<TransientTargetMethodParameter>>,
* }
*
* @throws ReflectionException
Expand All @@ -54,7 +51,7 @@ public function collectAttributes(string $class): array
$classReflection = new ReflectionClass($class);

if ($this->isAttribute($classReflection)) {
return [ [], [], [] ];
return [ [], [], [], [] ];
}

$classAttributes = [];
Expand All @@ -74,23 +71,15 @@ public function collectAttributes(string $class): array
}

$methodAttributes = [];
$methodParameterAttributes = [];

foreach ($classReflection->getMethods() as $methodReflection) {
foreach ($this->getMethodAttributes($methodReflection) as $attribute) {
if (self::isAttributeIgnored($attribute->getName())) {
continue;
}

$method = $methodReflection->name;

$this->io->debug("Found attribute {$attribute->getName()} on $class::$method");

$methodAttributes[] = new TransientTargetMethod(
$attribute->getName(),
$attribute->getArguments(),
$method,
);
}
$this->collectMethodAndParameterAttributes(
$class,
$methodReflection,
$methodAttributes,
$methodParameterAttributes,
);
}

$propertyAttributes = [];
Expand All @@ -114,7 +103,7 @@ public function collectAttributes(string $class): array
}
}

return [ $classAttributes, $methodAttributes, $propertyAttributes ];
return [ $classAttributes, $methodAttributes, $propertyAttributes, $methodParameterAttributes ];
}

/**
Expand Down Expand Up @@ -189,63 +178,15 @@ public function enterNode(Node $node)
return [];
}

return $this->attrGroupsToAttributes($classVisitor->classNodeToReturn->attrGroups);
return (new AttributeGroupsReflector())->attrGroupsToAttributes($classVisitor->classNodeToReturn->attrGroups);
}

/**
* @return Node[]
*/
private function parse(string $file): array
{
if (isset($this->parserCache[$file])) {
return $this->parserCache[$file];
}
$contents = file_get_contents($file);
if ($contents === false) {
return [];
}

$ast = $this->parser->parse($contents);
assert($ast !== null);
$nameTraverser = new NodeTraverser(new NameResolver());

return $this->parserCache[$file] = $nameTraverser->traverse($ast);
}

/**
* @param Node\AttributeGroup[] $attrGroups
* @return ReflectionAttribute<object>[]
*/
private function attrGroupsToAttributes(array $attrGroups): array
{
$evaluator = new ConstExprEvaluator(function (Expr $expr) {
if ($expr instanceof Expr\ClassConstFetch && $expr->class instanceof Node\Name && $expr->name instanceof Node\Identifier) {
return constant(sprintf('%s::%s', $expr->class->toString(), $expr->name->toString()));
}

throw new ConstExprEvaluationException("Expression of type {$expr->getType()} cannot be evaluated");
});

$attributes = [];
foreach ($attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
$argValues = [];
foreach ($attr->args as $i => $arg) {
if ($arg->name === null) {
$argValues[$i] = $evaluator->evaluateDirectly($arg->value);
continue;
}

$argValues[$arg->name->toString()] = $evaluator->evaluateDirectly($arg->value);
}
$attributes[] = new FakeAttribute(
$attr->name,
$argValues,
);
}
}

return $attributes; // @phpstan-ignore return.type
return $this->cachedParser->parse($file);
}

/**
Expand Down Expand Up @@ -304,7 +245,7 @@ public function enterNode(Node $node): ?int
return [];
}

return $this->attrGroupsToAttributes($propertyVisitor->propertyNodeToReturn->attrGroups);
return (new AttributeGroupsReflector())->attrGroupsToAttributes($propertyVisitor->propertyNodeToReturn->attrGroups);
}

/**
Expand Down Expand Up @@ -361,6 +302,38 @@ public function enterNode(Node $node): ?int
return [];
}

return $this->attrGroupsToAttributes($methodVisitor->methodNodeToReturn->attrGroups);
return (new AttributeGroupsReflector())->attrGroupsToAttributes($methodVisitor->methodNodeToReturn->attrGroups);
}

/**
* @param string $class
* @param ReflectionMethod $methodReflection
* @param array<TransientTargetMethod> $methodAttributes
* @param array<array<TransientTargetMethodParameter>> $methodParameterAttributes
* @return void
*/
private function collectMethodAndParameterAttributes(string $class, \ReflectionMethod $methodReflection, array &$methodAttributes, array &$methodParameterAttributes): void
{
$parameterAttributeCollector = new ParameterAttributeCollector($this->io, $this->cachedParser);
foreach ($this->getMethodAttributes($methodReflection) as $attribute) {
if (self::isAttributeIgnored($attribute->getName())) {
continue;
}

$method = $methodReflection->name;

$this->io->debug("Found attribute {$attribute->getName()} on $class::$method");

$methodAttributes[] = new TransientTargetMethod(
$attribute->getName(),
$attribute->getArguments(),
$method,
);
}

$parameterAttributes = $parameterAttributeCollector->collectAttributes($methodReflection);
if ($parameterAttributes !== []) {
$methodParameterAttributes[] = $parameterAttributes;
}
}
}
Loading