diff --git a/src/Font/Ttf/TtfSubsetter.php b/src/Font/Ttf/TtfSubsetter.php index f30aaf7..dd61de6 100644 --- a/src/Font/Ttf/TtfSubsetter.php +++ b/src/Font/Ttf/TtfSubsetter.php @@ -50,6 +50,16 @@ final class TtfSubsetter /** LRU cache size limit (oldest entries evicted on overflow). */ private const CACHE_MAX = 32; + /** + * Each source font's id in cache keys. Ids are never reused, and an + * entry goes away with its font. + * + * @var \WeakMap|null + */ + private static ?\WeakMap $sourceIds = null; + + private static int $nextSourceId = 0; + /** Force-clear cache (mostly for testing). */ public static function clearCache(): void { @@ -87,13 +97,15 @@ public function subset(TtfFile $source, array $usedGlyphIds, ?VariableInstance $ // Glyph 0 (.notdef) — ALWAYS. $used[0] = true; - // Cache key — source instance ID + sorted glyphs + axes. + // Cache key — source font id + sorted glyphs + axes. $glyphList = array_keys($used); sort($glyphList); $axesKey = $variableInstance !== null ? serialize($variableInstance->userCoords) : ''; - $cacheKey = spl_object_id($source).'|'.implode(',', $glyphList).'|'.$axesKey; + self::$sourceIds ??= new \WeakMap; + $sourceId = self::$sourceIds[$source] ??= ++self::$nextSourceId; + $cacheKey = $sourceId.'|'.implode(',', $glyphList).'|'.$axesKey; if (isset(self::$cache[$cacheKey])) { // LRU touch — move to end (most recently used). diff --git a/tests/Font/Ttf/TtfSubsetterCacheTest.php b/tests/Font/Ttf/TtfSubsetterCacheTest.php index c47c3e7..5d61892 100644 --- a/tests/Font/Ttf/TtfSubsetterCacheTest.php +++ b/tests/Font/Ttf/TtfSubsetterCacheTest.php @@ -175,4 +175,28 @@ public function clear_cache_resets_state(): void TtfSubsetter::clearCache(); self::assertSame(0, TtfSubsetter::cacheSize()); } + + #[Test] + public function a_freed_font_s_subsets_are_not_served_for_the_next_font(): void + { + // PHP reuses a freed object's id. Keyed by spl_object_id, the cache + // handed Bold the subset of a Regular freed just before: both have + // the same glyph order, so the same text meant the same key. + $dir = dirname($this->fontPath()).'/'; + $glyphs = static fn (TtfFile $f): array => array_map( + static fn (string $c): int => $f->glyphIdForChar(mb_ord($c)), + mb_str_split('Invoice 42'), + ); + + $regular = new TtfFile((string) file_get_contents($dir.'LiberationSans-Regular.ttf')); + $regularSubset = (new TtfSubsetter)->subset($regular, $glyphs($regular)); + unset($regular); + + $bold = new TtfFile((string) file_get_contents($dir.'LiberationSans-Bold.ttf')); + $boldSubset = (new TtfSubsetter)->subset($bold, $glyphs($bold)); + TtfSubsetter::clearCache(); + + self::assertNotSame($regularSubset, $boldSubset); + self::assertSame((new TtfSubsetter)->subset($bold, $glyphs($bold)), $boldSubset); + } }