File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 2525 */
2626final class ConventionDetector
2727{
28+ /**
29+ * Cache of matched conventions per segment string. Segments (e.g. "label",
30+ * "title") repeat heavily across keys, so caching avoids re-running every
31+ * convention regex for the same segment.
32+ *
33+ * @var array<string, array<string>>
34+ */
35+ private array $ segmentConventionCache = [];
36+
2837 /**
2938 * Detect which conventions a key matches.
3039 *
@@ -84,6 +93,10 @@ public function detectKeyConventions(string $key): array
8493 */
8594 public function detectSegmentConventions (string $ segment ): array
8695 {
96+ if (isset ($ this ->segmentConventionCache [$ segment ])) {
97+ return $ this ->segmentConventionCache [$ segment ];
98+ }
99+
87100 $ matchingConventions = [];
88101
89102 foreach (KeyNamingConvention::cases () as $ convention ) {
@@ -97,7 +110,7 @@ public function detectSegmentConventions(string $segment): array
97110 $ matchingConventions [] = 'unknown ' ;
98111 }
99112
100- return $ matchingConventions ;
113+ return $ this -> segmentConventionCache [ $ segment ] = $ matchingConventions ;
101114 }
102115
103116 /**
Original file line number Diff line number Diff line change @@ -33,6 +33,14 @@ protected function setUp(): void
3333 $ this ->detector = new ConventionDetector ();
3434 }
3535
36+ public function testDetectSegmentConventionsIsMemoized (): void
37+ {
38+ $ first = $ this ->detector ->detectSegmentConventions ('label ' );
39+ $ second = $ this ->detector ->detectSegmentConventions ('label ' );
40+
41+ $ this ->assertSame ($ first , $ second );
42+ }
43+
3644 /**
3745 * @param array<string> $expectedContains
3846 * @param array<string> $expectedNotContains
You can’t perform that action at this time.
0 commit comments