Skip to content

Commit

Permalink
Cache descriptions in ObjectType and UnionType
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Dec 9, 2022
1 parent 4f7e20b commit da8413c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/Type/ObjectType.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ class ObjectType implements TypeWithClassName, SubtractableType
/** @var array<string, self|null> */
private array $currentAncestors = [];

private ?string $cachedDescription = null;

/** @api */
public function __construct(
private string $className,
Expand Down Expand Up @@ -449,8 +451,12 @@ protected function describeAdditionalCacheKey(): string

private function describeCache(): string
{
if ($this->cachedDescription !== null) {
return $this->cachedDescription;
}

if (static::class !== self::class) {
return $this->describe(VerbosityLevel::cache());
return $this->cachedDescription = $this->describe(VerbosityLevel::cache());
}

$description = $this->className;
Expand All @@ -475,7 +481,7 @@ private function describeCache(): string
$description .= '-';
}

return $description;
return $this->cachedDescription = $description;
}

public function toNumber(): Type
Expand Down
8 changes: 7 additions & 1 deletion src/Type/UnionType.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ class UnionType implements CompoundType

private bool $sortedTypes = false;

/** @var array<int, string> */
private array $cachedDescriptions = [];

/**
* @api
* @param Type[] $types
Expand Down Expand Up @@ -208,6 +211,9 @@ public function equals(Type $type): bool

public function describe(VerbosityLevel $level): string
{
if (isset($this->cachedDescriptions[$level->getLevelValue()])) {
return $this->cachedDescriptions[$level->getLevelValue()];
}
$joinTypes = static function (array $types) use ($level): string {
$typeNames = [];
foreach ($types as $i => $type) {
Expand Down Expand Up @@ -240,7 +246,7 @@ public function describe(VerbosityLevel $level): string
return implode('|', $typeNames);
};

return $level->handle(
return $this->cachedDescriptions[$level->getLevelValue()] = $level->handle(
function () use ($joinTypes): string {
$types = TypeCombinator::union(...array_map(static function (Type $type): Type {
if (
Expand Down

0 comments on commit da8413c

Please sign in to comment.