├── LICENSE ├── README.md ├── composer.json └── src ├── ArgumentsResolver.php ├── InDepthArgumentsResolver.php ├── NamedArgumentsResolver.php ├── ReflectionFactory.php └── UnresolvableArgumentException.php /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014-2021 Eugene Leonovich 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ArgumentsResolver 2 | ================= 3 | ![Quality Assurance](https://github.com/rybakit/arguments-resolver/workflows/QA/badge.svg) 4 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/rybakit/arguments-resolver/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/rybakit/arguments-resolver/?branch=master) 5 | [![Code Coverage](https://scrutinizer-ci.com/g/rybakit/arguments-resolver/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/rybakit/arguments-resolver/?branch=master) 6 | 7 | ArgumentsResolver allows you to determine the arguments to pass to a function or method. 8 | 9 | 10 | ## Installation 11 | 12 | The recommended way to install ArgumentsResolver is through [Composer](http://getcomposer.org): 13 | 14 | ```bash 15 | composer require rybakit/arguments-resolver 16 | ``` 17 | 18 | 19 | ## Usage example 20 | 21 | ```php 22 | use ArgumentsResolver\InDepthArgumentsResolver; 23 | 24 | $greet = function ($username, DateTime $date, $greeting = 'Hello %s!') { 25 | // ... 26 | }; 27 | 28 | $parameters = [ 29 | 'Welcome %s!', 30 | ['foo'], 31 | new DateTime(), 32 | 'username' => 'Stranger', 33 | 'bar', 34 | ]; 35 | 36 | $arguments = (new InDepthArgumentsResolver($greet))->resolve($parameters); 37 | print_r($arguments); 38 | ``` 39 | 40 | The above example will output: 41 | 42 | ```php 43 | Array 44 | ( 45 | [0] => Stranger 46 | [1] => DateTime Object (...) 47 | [2] => Welcome %s! 48 | ) 49 | ``` 50 | 51 | 52 | ## Resolvers 53 | 54 | The library ships with two resolvers, the [InDepthArgumentsResolver](#indepthargumentsresolver) and [NamedArgumentsResolver](#namedargumentsresolver). 55 | They both expect a function to be supplied as a single constructor argument. The function can be any [callable](http://php.net/manual/en/language.types.callable.php), [a string representing a class method](http://php.net/manual/en/reflectionmethod.construct.php#refsect1-reflectionmethod.construct-parameters) or an instance of [ReflectionFunctionAbstract](http://php.net/manual/en/class.reflectionfunctionabstract.php): 56 | 57 | ```php 58 | new InDepthArgumentsResolver(['MyClass', 'myMethod']); 59 | new InDepthArgumentsResolver([new MyClass(), 'myMethod']); 60 | new InDepthArgumentsResolver(['MyClass', 'myStaticMethod']); 61 | new InDepthArgumentsResolver('MyClass::myStaticMethod'); 62 | new InDepthArgumentsResolver('MyClass::__construct'); 63 | new InDepthArgumentsResolver(['MyClass', '__construct']); 64 | new InDepthArgumentsResolver(new MyInvokableClass()); 65 | new InDepthArgumentsResolver(function ($foo) {}); 66 | new InDepthArgumentsResolver('MyNamespace\my_function'); 67 | new InDepthArgumentsResolver(new ReflectionMethod('MyClass', 'myMethod')); 68 | new InDepthArgumentsResolver(new ReflectionFunction('MyNamespace\my_function')); 69 | ``` 70 | 71 | There is also an utility class which helps in creating a reflection instance: 72 | 73 | ```php 74 | use ArgumentsResolver\ReflectionFactory; 75 | 76 | $reflection = ReflectionFactory::create('MyClass::__construct'); 77 | $resolver = new InDepthArgumentsResolver($reflection); 78 | ``` 79 | 80 | 81 | #### InDepthArgumentsResolver 82 | 83 | In the `InDepthArgumentsResolver`, the decision about whether an argument matched the parameter value or not 84 | is influenced by multiple factors, namely the argument's type, the class hierarchy (if it's an object), 85 | the argument name and the argument position. 86 | 87 | To clarify, consider each circumstance in turn: 88 | 89 | *Argument type* 90 | 91 | ```php 92 | function foo(array $array, stdClass $object, callable $callable) {} 93 | 94 | (new InDepthArgumentsResolver('foo'))->resolve([ 95 | ... 96 | function () {}, // $callable 97 | ... 98 | new stdClass(), // $object 99 | ... 100 | [42], // $array 101 | ... 102 | ]); 103 | ``` 104 | 105 | *Class hierarchy* 106 | 107 | ```php 108 | function foo(Exception $e, RuntimeException $re) {} 109 | 110 | (new InDepthArgumentsResolver('foo'))->resolve([ 111 | ... 112 | new RuntimeException(), // $re 113 | ... 114 | new Exception(), // $e 115 | ... 116 | ]); 117 | ``` 118 | 119 | *Argument name* 120 | 121 | ```php 122 | function foo($a, $b) {} 123 | 124 | (new InDepthArgumentsResolver('foo'))->resolve([ 125 | ... 126 | 'c' => 3, 127 | 'b' => 2, // $b 128 | 'a' => 1, // $a 129 | ... 130 | ]); 131 | ``` 132 | 133 | *Argument position* 134 | 135 | ```php 136 | function foo($a, $b) {} 137 | 138 | (new InDepthArgumentsResolver('foo'))->resolve([ 139 | 1, // $a 140 | 2, // $b 141 | ... 142 | ]); 143 | ``` 144 | 145 | #### NamedArgumentsResolver 146 | 147 | The `NamedArgumentsResolver` is a very simple resolver which does the matching only by the argument name. 148 | Therefore this requires parameters to be an associative array: 149 | 150 | ```php 151 | function foo($a, array $b, $c = null) {} 152 | 153 | (new NamedArgumentsResolver('foo'))->resolve([ 154 | ... 155 | 'b' => [], // $b 156 | 'a' => 1, // $a 157 | 'c' => 'bar', // $c 158 | ... 159 | ]); 160 | ``` 161 | 162 | 163 | ## Tests 164 | 165 | ArgumentsResolver uses [PHPUnit](http://phpunit.de) for unit testing. 166 | In order to run the tests, you'll first need to setup the test suite using composer: 167 | 168 | ```bash 169 | composer install 170 | ``` 171 | 172 | You can then run the tests: 173 | 174 | ```bash 175 | vendor/bin/phpunit 176 | ``` 177 | 178 | 179 | ## License 180 | 181 | ArgumentsResolver is released under the MIT License. See the bundled [LICENSE](LICENSE) file for details. 182 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rybakit/arguments-resolver", 3 | "description": "ArgumentsResolver allows you to determine the arguments to pass to a function or method.", 4 | "keywords": ["arguments", "parameters", "function", "method", "callable", "reflection", "injection", "invoke", "resolver"], 5 | "homepage": "https://github.com/rybakit/arguments-resolver", 6 | "type": "library", 7 | "license": "MIT", 8 | "authors": [ 9 | { 10 | "name": "Eugene Leonovich", 11 | "email": "gen.work@gmail.com" 12 | } 13 | ], 14 | "require": { 15 | "php": "^7.1|^8" 16 | }, 17 | "require-dev": { 18 | "friendsofphp/php-cs-fixer": "^2.13", 19 | "phpunit/phpunit": "^7.1|^8|^9" 20 | }, 21 | "autoload": { 22 | "psr-4": { 23 | "ArgumentsResolver\\": "src/" 24 | } 25 | }, 26 | "autoload-dev" : { 27 | "psr-4": { 28 | "ArgumentsResolver\\Tests\\": "tests/" 29 | } 30 | }, 31 | "config": { 32 | "preferred-install": { 33 | "*": "dist" 34 | }, 35 | "sort-packages": true 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/ArgumentsResolver.php: -------------------------------------------------------------------------------- 1 | 9 | * 10 | * For the full copyright and license information, please view the LICENSE 11 | * file that was distributed with this source code. 12 | */ 13 | 14 | namespace ArgumentsResolver; 15 | 16 | abstract class ArgumentsResolver 17 | { 18 | /** 19 | * @var \ReflectionFunctionAbstract 20 | */ 21 | protected $reflection; 22 | 23 | public function __construct($function) 24 | { 25 | $this->reflection = $function instanceof \ReflectionFunctionAbstract 26 | ? $function 27 | : ReflectionFactory::create($function); 28 | } 29 | 30 | /** 31 | * Resolves function arguments. 32 | * 33 | * @throws UnresolvableArgumentException 34 | * @throws \ReflectionException 35 | */ 36 | public function resolve(array $parameters) : array 37 | { 38 | if (!$number = $this->reflection->getNumberOfParameters()) { 39 | return []; 40 | } 41 | 42 | $arguments = \array_fill(0, $number, null); 43 | 44 | foreach ($this->getParameters() as $pos => $parameter) { 45 | $result = $this->match($parameter, $parameters); 46 | 47 | if ($result) { 48 | $arguments[$pos] = $result[1]; 49 | unset($parameters[$result[0]]); 50 | continue; 51 | } 52 | 53 | if ($parameter->isDefaultValueAvailable()) { 54 | $arguments[$pos] = $parameter->getDefaultValue(); 55 | continue; 56 | } 57 | 58 | throw UnresolvableArgumentException::fromParameter($parameter); 59 | } 60 | 61 | return $arguments; 62 | } 63 | 64 | /** 65 | * Returns an array of reflection parameters. 66 | * 67 | * @return \ReflectionParameter[] 68 | */ 69 | protected function getParameters() : array 70 | { 71 | return $this->reflection->getParameters(); 72 | } 73 | 74 | /** 75 | * Returns the [key, value] pair if the parameter is matched or null otherwise. 76 | */ 77 | abstract protected function match(\ReflectionParameter $parameter, array $parameters) : ?array; 78 | } 79 | -------------------------------------------------------------------------------- /src/InDepthArgumentsResolver.php: -------------------------------------------------------------------------------- 1 | 9 | * 10 | * For the full copyright and license information, please view the LICENSE 11 | * file that was distributed with this source code. 12 | */ 13 | 14 | namespace ArgumentsResolver; 15 | 16 | class InDepthArgumentsResolver extends ArgumentsResolver 17 | { 18 | /** 19 | * @var \ReflectionParameter[] 20 | */ 21 | private $sortedParameters; 22 | 23 | /** 24 | * {@inheritdoc} 25 | */ 26 | protected function getParameters() : array 27 | { 28 | if (null === $this->sortedParameters) { 29 | $this->sortedParameters = $this->reflection->getParameters(); 30 | \uasort($this->sortedParameters, [__CLASS__, 'compareParameters']); 31 | } 32 | 33 | return $this->sortedParameters; 34 | } 35 | 36 | /** 37 | * {@inheritdoc} 38 | */ 39 | protected function match(\ReflectionParameter $parameter, array $parameters) : ?array 40 | { 41 | $found = null; 42 | 43 | foreach ($parameters as $key => $value) { 44 | if (!self::matchType($parameter, $value)) { 45 | continue; 46 | } 47 | 48 | if ($key === $parameter->name) { 49 | return [$key, $value]; 50 | } 51 | 52 | if (!$found) { 53 | $found = [$key, $value]; 54 | } 55 | } 56 | 57 | return $found; 58 | } 59 | 60 | /** 61 | * Checks if the value matches the parameter type. 62 | * 63 | * @param mixed $value 64 | */ 65 | private static function matchType(\ReflectionParameter $parameter, $value) : bool 66 | { 67 | if (!$type = $parameter->getType()) { 68 | return true; 69 | } 70 | 71 | $typeName = $type->getName(); 72 | 73 | if ('array' === $typeName) { 74 | return \is_array($value); 75 | } 76 | 77 | if ('callable' === $typeName) { 78 | return \is_callable($value); 79 | } 80 | 81 | if (!$type->isBuiltin()) { 82 | if (!\is_object($value)) { 83 | return false; 84 | } 85 | 86 | $class = new \ReflectionClass($typeName); 87 | 88 | return $class && $class->isInstance($value); 89 | } 90 | 91 | switch ($typeName) { 92 | case 'bool': return \is_bool($value); 93 | case 'float': return \is_float($value); 94 | case 'int': return \is_int($value); 95 | case 'string': return \is_string($value); 96 | case 'iterable': return \is_iterable($value); 97 | } 98 | 99 | return true; 100 | } 101 | 102 | /** 103 | * Compares reflection parameters by type and position. 104 | */ 105 | private static function compareParameters(\ReflectionParameter $a, \ReflectionParameter $b) : int 106 | { 107 | $aType = $a->getType(); 108 | $bType = $b->getType(); 109 | 110 | if (0 !== $result = self::compareParameterClasses($aType, $bType)) { 111 | return $result; 112 | } 113 | 114 | $aTypeName = $aType ? $aType->getName() : null; 115 | $bTypeName = $bType ? $bType->getName() : null; 116 | 117 | if (('array' === $aTypeName) ^ ('array' === $bTypeName)) { 118 | return ('array' === $bTypeName) << 1 - 1; 119 | } 120 | 121 | if (('callable' === $aTypeName) ^ ('callable' === $bTypeName)) { 122 | return ('callable' === $bTypeName) << 1 - 1; 123 | } 124 | 125 | return $a->getPosition() - $b->getPosition(); 126 | } 127 | 128 | /** 129 | * Compares reflection parameters by class hierarchy. 130 | */ 131 | private static function compareParameterClasses(?\ReflectionType $a, ?\ReflectionType $b) : int 132 | { 133 | $a = $a && !$a->isBuiltin() 134 | ? new \ReflectionClass($a->getName()) 135 | : null; 136 | 137 | $b = $b && !$b->isBuiltin() 138 | ? new \ReflectionClass($b->getName()) 139 | : null; 140 | 141 | if ($a && $b) { 142 | return $a->isSubclassOf($b->name) ? -1 : (int) $b->isSubclassOf($a->name); 143 | } 144 | 145 | return (int) !$a - (int) !$b; 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/NamedArgumentsResolver.php: -------------------------------------------------------------------------------- 1 | 9 | * 10 | * For the full copyright and license information, please view the LICENSE 11 | * file that was distributed with this source code. 12 | */ 13 | 14 | namespace ArgumentsResolver; 15 | 16 | class NamedArgumentsResolver extends ArgumentsResolver 17 | { 18 | /** 19 | * {@inheritdoc} 20 | */ 21 | protected function match(\ReflectionParameter $parameter, array $parameters) : ?array 22 | { 23 | return \array_key_exists($parameter->name, $parameters) 24 | ? [$parameter->name, $parameters[$parameter->name]] 25 | : null; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/ReflectionFactory.php: -------------------------------------------------------------------------------- 1 | 9 | * 10 | * For the full copyright and license information, please view the LICENSE 11 | * file that was distributed with this source code. 12 | */ 13 | 14 | namespace ArgumentsResolver; 15 | 16 | abstract class ReflectionFactory 17 | { 18 | /** 19 | * Creates a reflection for a given function. 20 | * 21 | * @param callable|string $function A callable or a string representing a class method (non-static, delimited by ::) 22 | * 23 | * @throws \ReflectionException 24 | * 25 | * @return \ReflectionFunction|\ReflectionMethod 26 | */ 27 | public static function create($function) : \ReflectionFunctionAbstract 28 | { 29 | if (\is_string($function)) { 30 | return \strpos($function, '::') ? new \ReflectionMethod($function) : new \ReflectionFunction($function); 31 | } 32 | 33 | if (\is_array($function)) { 34 | return (new \ReflectionClass(\ReflectionMethod::class))->newInstanceArgs($function); 35 | } 36 | 37 | if (\method_exists($function, '__invoke')) { 38 | return new \ReflectionMethod($function, '__invoke'); 39 | } 40 | 41 | return new \ReflectionFunction($function); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/UnresolvableArgumentException.php: -------------------------------------------------------------------------------- 1 | 9 | * 10 | * For the full copyright and license information, please view the LICENSE 11 | * file that was distributed with this source code. 12 | */ 13 | 14 | namespace ArgumentsResolver; 15 | 16 | class UnresolvableArgumentException extends \InvalidArgumentException 17 | { 18 | public static function fromParameter(\ReflectionParameter $parameter) : self 19 | { 20 | return new self(\sprintf( 21 | 'Unable to resolve argument $%s (#%d) of %s.', 22 | $parameter->name, 23 | $parameter->getPosition(), 24 | self::getFunctionName($parameter->getDeclaringFunction()) 25 | )); 26 | } 27 | 28 | private static function getFunctionName(\ReflectionFunctionAbstract $reflection) : string 29 | { 30 | $name = $reflection->name.'()'; 31 | 32 | if ($reflection instanceof \ReflectionMethod) { 33 | $name = $reflection->getDeclaringClass()->name.'::'.$name; 34 | } 35 | 36 | return $name; 37 | } 38 | } 39 | --------------------------------------------------------------------------------