it-bens / reflection-constructor
A class to find a constructor argument by an object class via Reflection API.
Requires
- php: >=8.0
Requires (Dev)
- captainhook/plugin-composer: ^5.3
- roave/security-advisories: dev-latest
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-11-15 16:49:56 UTC
README
The reflection constructor (or should it be names ConstructorReflection?) can be used to find the name of parameter that matches a given type.
Why is that useful? Well, e.g. it can be used to inject data into a payload, if you only know the data (or its type), but not the name of the payload property.
How can the ReflectionConstructor be used?
The ReflectionConstructor is constructed with the class name of the object it should reflect.
use ITB\ReflectionConstructor\ReflectionConstructor; $constructor = new ReflectionConstructor(SomeClass::class);
The class provides two methods to extract the parameter name.
$parameterName = $constructor->extractParameterNameForClassName(SomeOtherClass::class); // or $someObject = new SomeOtherClass(); $parameterName = $constructor->extractParameterNameForObject($someObject)
What if two parameters share the same type?
Let's imagine there is a class like this:
class SomeClass { public function __construct(Type1 $propertyOne, Type2 $propertyTwo, Type2 $propertyThree) { // ... } }
This would work:
$constructor = new ReflectionConstructor(SomeClass::class); $parameterName = $constructor->extractParameterNameForClassName(Type1::class); // $parameterName = 'propertyOne'
But this would lead to an exception:
$constructor = new ReflectionConstructor(SomeClass::class); $parameterName = $constructor->extractParameterNameForClassName(Type2::class);
The parameters 'parameterTwo' and 'parameterThree' share the same type. The resulting parameter name would be ambiguous.
That's why a list of excluded/ignored parameters can be passed to the methods. This is working again:
$constructor = new ReflectionConstructor(SomeClass::class); $parameterName = $constructor->extractParameterNameForClassName(Type2::class, ['propertyTwo']); // $parameterName = 'propertyThree'
Contributing
I am really happy that the software developer community loves Open Source, like I do! ♥
That's why I appreciate every issue that is opened (preferably constructive) and every pull request that provides other or even better code to this package.
You are all breathtaking!