Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/Font/Ttf/TtfSubsetter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<TtfFile, int>|null
*/
private static ?\WeakMap $sourceIds = null;

private static int $nextSourceId = 0;

/** Force-clear cache (mostly for testing). */
public static function clearCache(): void
{
Expand Down Expand Up @@ -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).
Expand Down
24 changes: 24 additions & 0 deletions tests/Font/Ttf/TtfSubsetterCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Loading