A utility package that helps inspect functions in PHP.
This package provides some utilities for inspecting functions (callables) in PHP. You can use it to find parameters, return types and more.
Support development
If you would like to support the on going maintenance and development of this package, please consider sponsoring me on GitHub.
Installation
You can install the package via Composer:
composer require ryangjchandler/fn-inspector
Usage
You can create a new instance of FnInspector
by calling FnInspector::new()
and passing a string
, array
or callable
.
use RyanChandler\FnInspector\FnInspector;
$inspector = FnInspector::new('strlen');
$inspector = FnInspector::new(function () {});
$inspector = FnInspector::new([MyClass::class, 'staticMethod']);
$inspector = FnInspector::new([MyClass::class, 'instanceMethod']);
Return Type
You can retrieve the return type of a function by calling the returnType
method.
$returnType = FnInspector::new(function (): void {})
->returnType()
->getName();
echo $returnType; // `void`
Number of Parameters
You can retrieve the number of parameters by calling the numberOfParameters
method.
$params = FnInspector::new(function ($name): void {})
->numberOfParameters();
echo $params; // `1`
Number of Required Parameters
If you're only interested in required parameters, you can provide a bool
to the numberOfParameters
method.
$params = FnInspector::new(function ($name = null): void {})
->numberOfParameters(required: true);
echo $params; // `0`
Parameters
You can retrieve an instance of ParameterFinder
by calling the parameters
method. The ParameterFinder
class provides a set of granular utilities to help you find parameters by name and type.
$parameters = FnInspector::new(function ($name = null): void {})
->parameters();
To get the first parameter in a function, use the first
method.
$first = $parameters->first()->getName(); // returns `name`.
If you wish to find a parameter by type, you can use the type
method.
// Returns a new instance of `ParameterFinder` with parameters matching the type provides.
$models = $parameters->type(Model::class);
You can find parameters that match multiple types by providing an array to the type
method.
// Returns a new instance of `ParameterFinder` with parameters matching the types provides.
$usersAndCustomers = $parameters->type([User::class, Customer::class]);
You can retrieve all parameters by calling the all
method.
// Returns an array of `ReflectionParameter` objects.
$usersAndCustomers = $parameters->all();
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.