From da8413c493cbb9d800228f996836207e9598920c Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Fri, 9 Dec 2022 14:19:41 +0100 Subject: [PATCH] Cache descriptions in ObjectType and UnionType --- src/Type/ObjectType.php | 10 ++++++++-- src/Type/UnionType.php | 8 +++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/Type/ObjectType.php b/src/Type/ObjectType.php index bc10ad9224..af3f04e4b8 100644 --- a/src/Type/ObjectType.php +++ b/src/Type/ObjectType.php @@ -87,6 +87,8 @@ class ObjectType implements TypeWithClassName, SubtractableType /** @var array */ private array $currentAncestors = []; + private ?string $cachedDescription = null; + /** @api */ public function __construct( private string $className, @@ -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; @@ -475,7 +481,7 @@ private function describeCache(): string $description .= '-'; } - return $description; + return $this->cachedDescription = $description; } public function toNumber(): Type diff --git a/src/Type/UnionType.php b/src/Type/UnionType.php index 05c6ec40a7..0c1b6c20e7 100644 --- a/src/Type/UnionType.php +++ b/src/Type/UnionType.php @@ -38,6 +38,9 @@ class UnionType implements CompoundType private bool $sortedTypes = false; + /** @var array */ + private array $cachedDescriptions = []; + /** * @api * @param Type[] $types @@ -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) { @@ -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 (