mirror of
https://github.com/pestphp/pest.git
synced 2026-03-07 00:07:22 +01:00
Adds tap for Higher Order tests
This commit is contained in:
33
src/Support/HigherOrderCallables.php
Normal file
33
src/Support/HigherOrderCallables.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Support;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class HigherOrderCallables
|
||||
{
|
||||
/**
|
||||
* @var object
|
||||
*/
|
||||
private $target;
|
||||
|
||||
public function __construct(object $target)
|
||||
{
|
||||
$this->target = $target;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TValue
|
||||
*
|
||||
* @param callable(): TValue $callable
|
||||
*
|
||||
* @return TValue|object
|
||||
*/
|
||||
public function tap(callable $callable)
|
||||
{
|
||||
return Reflection::bindCallable($callable) ?? $this->target;
|
||||
}
|
||||
}
|
||||
@ -70,6 +70,10 @@ final class HigherOrderMessage
|
||||
*/
|
||||
public function call(object $target)
|
||||
{
|
||||
if (($value = $this->retrieveHigherOrderCallable($target)) !== null) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
try {
|
||||
return Reflection::call($target, $this->methodName, $this->arguments);
|
||||
} catch (Throwable $throwable) {
|
||||
@ -88,6 +92,21 @@ final class HigherOrderMessage
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to call one of the available Higher Order callables if it exists.
|
||||
*
|
||||
* @return mixed|null
|
||||
*/
|
||||
private function retrieveHigherOrderCallable(object $target)
|
||||
{
|
||||
if (in_array($this->methodName, get_class_methods(HigherOrderCallables::class), true)) {
|
||||
/* @phpstan-ignore-next-line */
|
||||
return (new HigherOrderCallables($target))->{$this->methodName}(...$this->arguments);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function getUndefinedMethodMessage(object $target, string $methodName): string
|
||||
{
|
||||
if (\PHP_MAJOR_VERSION >= 8) {
|
||||
|
||||
@ -41,15 +41,25 @@ final class Reflection
|
||||
}
|
||||
|
||||
if (is_callable($method)) {
|
||||
return Closure::fromCallable($method)->bindTo(
|
||||
TestSuite::getInstance()->test
|
||||
)(...$args);
|
||||
return static::bindCallable($method, $args);
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a callable to the TestCase and return the result.
|
||||
*
|
||||
* @param array<int, mixed> $args
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public static function bindCallable(callable $callable, array $args = [])
|
||||
{
|
||||
return Closure::fromCallable($callable)->bindTo(TestSuite::getInstance()->test)(...$args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Infers the file name from the given closure.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user