PDF rausgenommen

This commit is contained in:
aschwarz
2023-01-23 11:03:31 +01:00
parent 82d562a322
commit a6523903eb
28078 changed files with 4247552 additions and 2 deletions

View File

@ -0,0 +1,127 @@
<?php
namespace Invoker;
use Interop\Container\ContainerInterface;
use Interop\Container\Exception\NotFoundException;
use Invoker\Exception\NotCallableException;
/**
* Resolves a callable from a container.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class CallableResolver
{
/**
* @var ContainerInterface
*/
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Resolve the given callable into a real PHP callable.
*
* @param callable|string|array $callable
*
* @return callable Real PHP callable.
*
* @throws NotCallableException
*/
public function resolve($callable)
{
if (is_string($callable) && strpos($callable, '::') !== false) {
$callable = explode('::', $callable, 2);
}
$callable = $this->resolveFromContainer($callable);
if (! is_callable($callable)) {
throw NotCallableException::fromInvalidCallable($callable, true);
}
return $callable;
}
/**
* @param callable|string|array $callable
* @return callable
* @throws NotCallableException
*/
private function resolveFromContainer($callable)
{
// Shortcut for a very common use case
if ($callable instanceof \Closure) {
return $callable;
}
$isStaticCallToNonStaticMethod = false;
// If it's already a callable there is nothing to do
if (is_callable($callable)) {
$isStaticCallToNonStaticMethod = $this->isStaticCallToNonStaticMethod($callable);
if (! $isStaticCallToNonStaticMethod) {
return $callable;
}
}
// The callable is a container entry name
if (is_string($callable)) {
try {
return $this->container->get($callable);
} catch (NotFoundException $e) {
throw NotCallableException::fromInvalidCallable($callable, true);
}
}
// The callable is an array whose first item is a container entry name
// e.g. ['some-container-entry', 'methodToCall']
if (is_array($callable) && is_string($callable[0])) {
try {
// Replace the container entry name by the actual object
$callable[0] = $this->container->get($callable[0]);
return $callable;
} catch (NotFoundException $e) {
if ($isStaticCallToNonStaticMethod) {
throw new NotCallableException(sprintf(
'Cannot call %s::%s() because %s() is not a static method and "%s" is not a container entry',
$callable[0],
$callable[1],
$callable[1],
$callable[0]
));
}
throw new NotCallableException(sprintf(
'Cannot call %s on %s because it is not a class nor a valid container entry',
$callable[1],
$callable[0]
));
}
}
// Unrecognized stuff, we let it fail later
return $callable;
}
/**
* Check if the callable represents a static call to a non-static method.
*
* @param mixed $callable
* @return bool
*/
private function isStaticCallToNonStaticMethod($callable)
{
if (is_array($callable) && is_string($callable[0])) {
list($class, $method) = $callable;
$reflection = new \ReflectionMethod($class, $method);
return ! $reflection->isStatic();
}
return false;
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace Invoker\Exception;
/**
* Impossible to invoke the callable.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class InvocationException extends \Exception
{
}

View File

@ -0,0 +1,35 @@
<?php
namespace Invoker\Exception;
/**
* The given callable is not actually callable.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class NotCallableException extends InvocationException
{
/**
* @param string $value
* @param bool $containerEntry
* @return self
*/
public static function fromInvalidCallable($value, $containerEntry = false)
{
if (is_object($value)) {
$message = sprintf('Instance of %s is not a callable', get_class($value));
} elseif (is_array($value) && isset($value[0]) && isset($value[1])) {
$class = is_object($value[0]) ? get_class($value[0]) : $value[0];
$extra = method_exists($class, '__call') ? ' A __call() method exists but magic methods are not supported.' : '';
$message = sprintf('%s::%s() is not a callable.%s', $class, $value[1], $extra);
} else {
if ($containerEntry) {
$message = var_export($value, true) . ' is neither a callable nor a valid container entry';
} else {
$message = var_export($value, true) . ' is not a callable';
}
}
return new self($message);
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace Invoker\Exception;
/**
* Not enough parameters could be resolved to invoke the callable.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class NotEnoughParametersException extends InvocationException
{
}

View File

@ -0,0 +1,122 @@
<?php
namespace Invoker;
use Interop\Container\ContainerInterface;
use Invoker\Exception\NotCallableException;
use Invoker\Exception\NotEnoughParametersException;
use Invoker\ParameterResolver\AssociativeArrayResolver;
use Invoker\ParameterResolver\DefaultValueResolver;
use Invoker\ParameterResolver\NumericArrayResolver;
use Invoker\ParameterResolver\ParameterResolver;
use Invoker\ParameterResolver\ResolverChain;
use Invoker\Reflection\CallableReflection;
/**
* Invoke a callable.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class Invoker implements InvokerInterface
{
/**
* @var CallableResolver|null
*/
private $callableResolver;
/**
* @var ParameterResolver
*/
private $parameterResolver;
/**
* @var ContainerInterface|null
*/
private $container;
public function __construct(ParameterResolver $parameterResolver = null, ContainerInterface $container = null)
{
$this->parameterResolver = $parameterResolver ?: $this->createParameterResolver();
$this->container = $container;
if ($container) {
$this->callableResolver = new CallableResolver($container);
}
}
/**
* {@inheritdoc}
*/
public function call($callable, array $parameters = array())
{
if ($this->callableResolver) {
$callable = $this->callableResolver->resolve($callable);
}
if (! is_callable($callable)) {
throw new NotCallableException(sprintf(
'%s is not a callable',
is_object($callable) ? 'Instance of ' . get_class($callable) : var_export($callable, true)
));
}
$callableReflection = CallableReflection::create($callable);
$args = $this->parameterResolver->getParameters($callableReflection, $parameters, array());
// Sort by array key because call_user_func_array ignores numeric keys
ksort($args);
// Check all parameters are resolved
$diff = array_diff_key($callableReflection->getParameters(), $args);
if (! empty($diff)) {
/** @var \ReflectionParameter $parameter */
$parameter = reset($diff);
throw new NotEnoughParametersException(sprintf(
'Unable to invoke the callable because no value was given for parameter %d ($%s)',
$parameter->getPosition() + 1,
$parameter->name
));
}
return call_user_func_array($callable, $args);
}
/**
* Create the default parameter resolver.
*
* @return ParameterResolver
*/
private function createParameterResolver()
{
return new ResolverChain(array(
new NumericArrayResolver,
new AssociativeArrayResolver,
new DefaultValueResolver,
));
}
/**
* @return ParameterResolver By default it's a ResolverChain
*/
public function getParameterResolver()
{
return $this->parameterResolver;
}
/**
* @return ContainerInterface|null
*/
public function getContainer()
{
return $this->container;
}
/**
* @return CallableResolver|null Returns null if no container was given in the constructor.
*/
public function getCallableResolver()
{
return $this->callableResolver;
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace Invoker;
use Invoker\Exception\InvocationException;
use Invoker\Exception\NotCallableException;
use Invoker\Exception\NotEnoughParametersException;
/**
* Invoke a callable.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
interface InvokerInterface
{
/**
* Call the given function using the given parameters.
*
* @param callable $callable Function to call.
* @param array $parameters Parameters to use.
*
* @return mixed Result of the function.
*
* @throws InvocationException Base exception class for all the sub-exceptions below.
* @throws NotCallableException
* @throws NotEnoughParametersException
*/
public function call($callable, array $parameters = array());
}

View File

@ -0,0 +1,39 @@
<?php
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Tries to map an associative array (string-indexed) to the parameter names.
*
* E.g. `->call($callable, ['foo' => 'bar'])` will inject the string `'bar'`
* in the parameter named `$foo`.
*
* Parameters that are not indexed by a string are ignored.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class AssociativeArrayResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
) {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
if (array_key_exists($parameter->name, $providedParameters)) {
$resolvedParameters[$index] = $providedParameters[$parameter->name];
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace Invoker\ParameterResolver\Container;
use Interop\Container\ContainerInterface;
use Invoker\ParameterResolver\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Inject entries from a DI container using the parameter names.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ParameterNameContainerResolver implements ParameterResolver
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @param ContainerInterface $container The container to get entries from.
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
) {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
$name = $parameter->name;
if ($name && $this->container->has($name)) {
$resolvedParameters[$index] = $this->container->get($name);
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace Invoker\ParameterResolver\Container;
use Interop\Container\ContainerInterface;
use Invoker\ParameterResolver\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Inject entries from a DI container using the type-hints.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class TypeHintContainerResolver implements ParameterResolver
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @param ContainerInterface $container The container to get entries from.
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
) {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
$parameterClass = $parameter->getClass();
if ($parameterClass && $this->container->has($parameterClass->name)) {
$resolvedParameters[$index] = $this->container->get($parameterClass->name);
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace Invoker\ParameterResolver;
use ReflectionException;
use ReflectionFunctionAbstract;
/**
* Finds the default value for a parameter, *if it exists*.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class DefaultValueResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
) {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
/** @var \ReflectionParameter $parameter */
if ($parameter->isOptional()) {
try {
$resolvedParameters[$index] = $parameter->getDefaultValue();
} catch (ReflectionException $e) {
// Can't get default values from PHP internal classes and functions
}
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Simply returns all the values of the $providedParameters array that are
* indexed by the parameter position (i.e. a number).
*
* E.g. `->call($callable, ['foo', 'bar'])` will simply resolve the parameters
* to `['foo', 'bar']`.
*
* Parameters that are not indexed by a number (i.e. parameter position)
* will be ignored.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class NumericArrayResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
) {
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$providedParameters = array_diff_key($providedParameters, $resolvedParameters);
}
foreach ($providedParameters as $key => $value) {
if (is_int($key)) {
$resolvedParameters[$key] = $value;
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Resolves the parameters to use to call the callable.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
interface ParameterResolver
{
/**
* Resolves the parameters to use to call the callable.
*
* `$resolvedParameters` contains parameters that have already been resolved.
*
* Each ParameterResolver must resolve parameters that are not already
* in `$resolvedParameters`. That allows to chain multiple ParameterResolver.
*
* @param ReflectionFunctionAbstract $reflection Reflection object for the callable.
* @param array $providedParameters Parameters provided by the caller.
* @param array $resolvedParameters Parameters resolved (indexed by parameter position).
*
* @return array
*/
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
);
}

View File

@ -0,0 +1,69 @@
<?php
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Dispatches the call to other resolvers until all parameters are resolved.
*
* Chain of responsibility pattern.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ResolverChain implements ParameterResolver
{
/**
* @var ParameterResolver[]
*/
private $resolvers = array();
public function __construct(array $resolvers = array())
{
$this->resolvers = $resolvers;
}
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
) {
$reflectionParameters = $reflection->getParameters();
foreach ($this->resolvers as $resolver) {
$resolvedParameters = $resolver->getParameters(
$reflection,
$providedParameters,
$resolvedParameters
);
$diff = array_diff_key($reflectionParameters, $resolvedParameters);
if (empty($diff)) {
// Stop traversing: all parameters are resolved
return $resolvedParameters;
}
}
return $resolvedParameters;
}
/**
* Push a parameter resolver after the ones already registered.
*
* @param ParameterResolver $resolver
*/
public function appendResolver(ParameterResolver $resolver)
{
$this->resolvers[] = $resolver;
}
/**
* Insert a parameter resolver before the ones already registered.
*
* @param ParameterResolver $resolver
*/
public function prependResolver(ParameterResolver $resolver)
{
array_unshift($this->resolvers, $resolver);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Invoker\ParameterResolver;
use Invoker\ParameterResolver\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Inject entries using type-hints.
*
* Tries to match type-hints with the parameters provided.
*
* @author Felix Becker <f.becker@outlook.com>
*/
class TypeHintResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
) {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
$parameterClass = $parameter->getClass();
if ($parameterClass && array_key_exists($parameterClass->name, $providedParameters)) {
$resolvedParameters[$index] = $providedParameters[$parameterClass->name];
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace Invoker\Reflection;
use Invoker\Exception\NotCallableException;
/**
* Create a reflection object from a callable.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class CallableReflection
{
/**
* @param callable $callable
*
* @return \ReflectionFunctionAbstract
*
* @throws NotCallableException
*
* TODO Use the `callable` type-hint once support for PHP 5.4 and up.
*/
public static function create($callable)
{
// Closure
if ($callable instanceof \Closure) {
return new \ReflectionFunction($callable);
}
// Array callable
if (is_array($callable)) {
list($class, $method) = $callable;
if (! method_exists($class, $method)) {
throw NotCallableException::fromInvalidCallable($callable);
}
return new \ReflectionMethod($class, $method);
}
// Callable object (i.e. implementing __invoke())
if (is_object($callable) && method_exists($callable, '__invoke')) {
return new \ReflectionMethod($callable, '__invoke');
}
// Callable class (i.e. implementing __invoke())
if (is_string($callable) && class_exists($callable) && method_exists($callable, '__invoke')) {
return new \ReflectionMethod($callable, '__invoke');
}
// Standard function
if (is_string($callable) && function_exists($callable)) {
return new \ReflectionFunction($callable);
}
throw new NotCallableException(sprintf(
'%s is not a callable',
is_string($callable) ? $callable : 'Instance of ' . get_class($callable)
));
}
}