Skip to content

Commit

Permalink
Optimize InvocationMocker by using cached hash table lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
sanmai authored and sebastianbergmann committed Jan 11, 2022
1 parent 716824d commit beb4d5c
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions src/Framework/MockObject/Builder/InvocationMocker.php
Expand Up @@ -12,7 +12,6 @@
use function array_map;
use function array_merge;
use function count;
use function in_array;
use function is_string;
use function strtolower;
use PHPUnit\Framework\Constraint\Constraint;
Expand Down Expand Up @@ -51,6 +50,11 @@ final class InvocationMocker implements InvocationStubber, MethodNameMatch
*/
private array $configurableMethods;

/**
* @psalm-var ?array<string, int>
*/
private ?array $configurableMethodNames = null;

public function __construct(InvocationHandler $handler, Matcher $matcher, ConfigurableMethod ...$configurableMethods)
{
$this->invocationHandler = $handler;
Expand Down Expand Up @@ -225,16 +229,18 @@ public function method(Constraint|string $constraint): self
throw new MethodNameAlreadyConfiguredException;
}

$configurableMethodNames = array_map(
static function (ConfigurableMethod $configurable)
{
return strtolower($configurable->getName());
},
$this->configurableMethods
);

if (is_string($constraint) && !in_array(strtolower($constraint), $configurableMethodNames, true)) {
throw new MethodCannotBeConfiguredException($constraint);
if (is_string($constraint)) {
$this->configurableMethodNames ??= array_flip(array_map(
static function (ConfigurableMethod $configurable)
{
return strtolower($configurable->getName());
},
$this->configurableMethods
));

if (!array_key_exists(strtolower($constraint), $this->configurableMethodNames)) {
throw new MethodCannotBeConfiguredException($constraint);
}
}

$this->matcher->setMethodNameRule(new Rule\MethodName($constraint));
Expand Down

0 comments on commit beb4d5c

Please sign in to comment.