Skip to content

Implement ParameterAttributeCollector #33

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

Closed
wants to merge 2 commits into from
Closed
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
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
57 changes: 40 additions & 17 deletions src/ClassAttributeCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public function __construct(
* array<TransientTargetClass>,
* array<TransientTargetMethod>,
* array<TransientTargetProperty>,
* array<array<TransientTargetMethodParameter>>,
* }
*
* @throws ReflectionException
Expand All @@ -34,7 +35,7 @@ public function collectAttributes(string $class): array
$classReflection = new ReflectionClass($class);

if (self::isAttribute($classReflection)) {
return [ [], [], [] ];
return [ [], [], [], [] ];
}

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

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

foreach ($classReflection->getMethods() as $methodReflection) {
foreach ($methodReflection->getAttributes() as $attribute) {
if (self::isAttributeIgnored($attribute)) {
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 @@ -94,7 +87,7 @@ public function collectAttributes(string $class): array
}
}

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

/**
Expand Down Expand Up @@ -124,4 +117,34 @@ private static function isAttributeIgnored(ReflectionAttribute $attribute): bool

return isset($ignored[$attribute->getName()]); // @phpstan-ignore offsetAccess.nonOffsetAccessible
}

/**
* @param array<TransientTargetMethod> $methodAttributes
* @param array<array<TransientTargetMethodParameter>> $methodParameterAttributes
* @return void
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's remove this one, it's already in the signature.

*/
private function collectMethodAndParameterAttributes(string $class, \ReflectionMethod $methodReflection, array &$methodAttributes, array &$methodParameterAttributes): void
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's split this over multiple lines.

Suggested change
private function collectMethodAndParameterAttributes(string $class, \ReflectionMethod $methodReflection, array &$methodAttributes, array &$methodParameterAttributes): void
private function collectMethodAndParameterAttributes(
string $class,
\ReflectionMethod $methodReflection,
array &$methodAttributes,
array &$methodParameterAttributes
): void {

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I'd like it better if we were not using references… but I can live with it.

{
$parameterAttributeCollector = new ParameterAttributeCollector($this->io);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's initialize our dependencies in the construct function.

Suggested change
$parameterAttributeCollector = new ParameterAttributeCollector($this->io);
$parameterAttributeCollector = $this->parameterAttributeCollector;

foreach ($methodReflection->getAttributes() as $attribute) {
if (self::isAttributeIgnored($attribute)) {
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 !== []) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if ($parameterAttributes !== []) {
if ($parameterAttributes) {

Simpler to read.

$methodParameterAttributes[] = $parameterAttributes;
}
}
}
70 changes: 70 additions & 0 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,15 @@ final class Collection
* @param array<class-string, array<array{ mixed[], class-string, non-empty-string }>> $targetProperties
* Where _key_ is an attribute class and _value_ an array of arrays
* where 0 are the attribute arguments, 1 is a target class, and 2 is the target property.
* @param array<class-string, array<array{ mixed[], class-string, non-empty-string, non-empty-string }>> $targetMethodParameters
* Where _key_ is an attribute class and _value_ an array of arrays
* where 0 are the attribute arguments, 1 is a target class, 2 is the target method, and 3 is the target parameter.
*/
public function __construct(
private array $targetClasses,
private array $targetMethods,
private array $targetProperties,
private array $targetMethodParameters,
) {
}

Expand Down Expand Up @@ -109,6 +113,46 @@ private static function createMethodAttribute(
}
}

/**
* @template T of object
*
* @param class-string<T> $attribute
*
* @return array<TargetMethodParameter<T>>
*/
public function findTargetMethodParameters(string $attribute): array
{
return array_map(
fn(array $t) => self::createMethodParameterAttribute($attribute, ...$t),
$this->targetMethodParameters[$attribute] ?? [],
);
}

/**
* @template T of object
*
* @param class-string<T> $attribute
* @param array<mixed> $arguments
* @param class-string $class
* @param non-empty-string $method
* @param non-empty-string $parameter
*
* @return TargetMethodParameter<T>
*/
private static function createMethodParameterAttribute(string $attribute, array $arguments, string $class, string $method, string $parameter): object
{
try {
$a = new $attribute(...$arguments);
return new TargetMethodParameter($a, $class, $method, $parameter);
} catch (Throwable $e) {
throw new RuntimeException(
"An error occurred while instantiating attribute $attribute on method $class::$method($parameter)",
0,
$e,
);
}
}

/**
* @template T of object
*
Expand Down Expand Up @@ -196,6 +240,32 @@ public function filterTargetMethods(callable $predicate): array
return $ar;
}

/**
* @param callable(class-string $attribute, class-string $class, non-empty-string $method, non-empty-string $parameter):bool $predicate
*
* @return array<TargetMethodParameter<object>>
*/
public function filterTargetMethodParameters(callable $predicate): array
{
$ar = [];

foreach ($this->targetMethodParameters as $attribute => $references) {
foreach ($references as [$arguments, $class, $method, $parameter]) {
if ($predicate($attribute, $class, $method, $parameter)) {
$ar[] = self::createMethodParameterAttribute(
$attribute,
$arguments,
$class,
$method,
$parameter
);
}
}
}

return $ar;
}

/**
* @param callable(class-string $attribute, class-string $class, non-empty-string $property):bool $predicate
*
Expand Down
11 changes: 9 additions & 2 deletions src/MemoizeAttributeCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ class MemoizeAttributeCollector
* array<TransientTargetClass>,
* array<TransientTargetMethod>,
* array<TransientTargetProperty>,
* array<array<TransientTargetMethodParameter>>,
* }>
* Where _key_ is a class and _value is an array where:
* - `0` is a timestamp
* - `1` is an array of class attributes
* - `2` is an array of method attributes
* - `3` is an array of property attributes
* - `4` is an array of arrays. _key_ is a method name and _value_ parameter attributes
*/
private array $state;

Expand Down Expand Up @@ -59,7 +61,8 @@ public function collectAttributes(array $classMap): TransientCollection
$classAttributes,
$methodAttributes,
$propertyAttributes,
] = $this->state[$class] ?? [ 0, [], [], [] ];
$methodParameterAttributes,
] = $this->state[$class] ?? [ 0, [], [], [], [] ];

$mtime = filemtime($filepath);

Expand All @@ -76,14 +79,15 @@ public function collectAttributes(array $classMap): TransientCollection
$classAttributes,
$methodAttributes,
$propertyAttributes,
$methodParameterAttributes,
] = $classAttributeCollector->collectAttributes($class);
} catch (Throwable $e) {
$this->io->error(
"Attribute collection failed for $class: {$e->getMessage()}",
);
}

$this->state[$class] = [ time(), $classAttributes, $methodAttributes, $propertyAttributes ];
$this->state[$class] = [ time(), $classAttributes, $methodAttributes, $propertyAttributes, $methodParameterAttributes ];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's split this one.

Suggested change
$this->state[$class] = [ time(), $classAttributes, $methodAttributes, $propertyAttributes, $methodParameterAttributes ];
$this->state[$class] = [
time(),
$classAttributes,
$methodAttributes,
$propertyAttributes,
$methodParameterAttributes,
];

}

if (count($classAttributes)) {
Expand All @@ -92,6 +96,9 @@ public function collectAttributes(array $classMap): TransientCollection
if (count($methodAttributes)) {
$collector->addMethodAttributes($class, $methodAttributes);
}
if (count($methodParameterAttributes)) {
$collector->addMethodParameterAttributes($class, $methodParameterAttributes);
}
if (count($propertyAttributes)) {
$collector->addTargetProperties($class, $propertyAttributes);
}
Expand Down
56 changes: 56 additions & 0 deletions src/ParameterAttributeCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace olvlvl\ComposerAttributeCollector;

use Composer\IO\IOInterface;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\Parser;
Comment on lines +6 to +10
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused imports.

Suggested change
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\Parser;


/**
* @internal
*/
class ParameterAttributeCollector
{
public function __construct(
private IOInterface $io
) {
}

/**
* @return array<TransientTargetMethodParameter>
*/
public function collectAttributes(\ReflectionFunctionAbstract $reflectionFunctionAbstract): array
{
$funcParameterAttributes = [];
foreach ($reflectionFunctionAbstract->getParameters() as $parameter) {
$attributes = $parameter->getAttributes();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We initialize the variable here, but it's used much later. Besides, the variable is only used once, we could do without.

Suggested change
$attributes = $parameter->getAttributes();

$functionName = $reflectionFunctionAbstract->name;
$parameterName = $parameter->name;
assert($functionName !== '');
assert($parameterName !== '');

$paramLabel = '';
if ($reflectionFunctionAbstract instanceof \ReflectionMethod) {
$paramLabel = $reflectionFunctionAbstract->class . '::' . $functionName . '(' . $parameterName . ')';
} elseif ($reflectionFunctionAbstract instanceof \ReflectionFunction) {
$paramLabel = $functionName . '(' . $parameterName . ')';
}

foreach ($attributes as $attribute) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
foreach ($attributes as $attribute) {
foreach ($parameter->getAttributes() as $attribute) {

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

$funcParameterAttributes[] = new TransientTargetMethodParameter(
$attribute->getName(),
$attribute->getArguments(),
$functionName,
$parameterName
);
}
}

return $funcParameterAttributes;
}
}
2 changes: 1 addition & 1 deletion src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ final class Plugin implements PluginInterface, EventSubscriberInterface
{
public const CACHE_DIR = '.composer-attribute-collector';
public const VERSION_MAJOR = 2;
public const VERSION_MINOR = 0;
public const VERSION_MINOR = 1;

/**
* @uses onPostAutoloadDump
Expand Down
28 changes: 28 additions & 0 deletions src/TargetMethodParameter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace olvlvl\ComposerAttributeCollector;

/**
* @readonly
*
* @template T of object
*/
final class TargetMethodParameter
{
/**
* @param T $attribute
* @param class-string $class
* The name of the target class.
* @param non-empty-string $name
* The name of the target parameter.
* @param non-empty-string $method
* The name of the target method.
*/
public function __construct(
public object $attribute,
public string $class,
public string $name,
public string $method
) {
}
}
Loading