File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1010
1111class TagEngine
1212{
13+ /**
14+ * @var self|null
15+ */
16+ private static ?TagEngine $ instance = null ;
17+
1318 /**
1419 * Holds the options array
1520 *
@@ -36,6 +41,11 @@ class TagEngine
3641 */
3742 protected array $ data = [];
3843
44+ /**
45+ * @var array
46+ */
47+ protected array $ discovery_cache = [];
48+
3949 /**
4050 * Initialize TagEngine
4151 *
@@ -60,6 +70,18 @@ public function __construct(array $options = [])
6070 }
6171 }
6272
73+ /**
74+ * @return self
75+ */
76+ public static function getInstance (?array $ options = null ): self
77+ {
78+ if (self ::$ instance === null ) {
79+ self ::$ instance = new self ($ options ?? []);
80+ }
81+
82+ return self ::$ instance ;
83+ }
84+
6385 /**
6486 * The regex pattern is quite insane, so let's break it down
6587 *
@@ -96,6 +118,12 @@ protected function registerTags(): void
96118 {
97119 if ($ this ->options ['tag_directories ' ]) {
98120 foreach ($ this ->options ['tag_directories ' ] as $ tag_directory ) {
121+ if (isset ($ this ->discovery_cache [$ tag_directory ])) {
122+ continue ;
123+ }
124+ $ this ->discovery_cache [$ tag_directory ] = true ;
125+
126+ // This is quite expensive, so only do it once
99127 $ classes = Discover::in ($ tag_directory )->classes ()
100128 ->extending (CustomTag::class)->get ();
101129 /** @var \LordSimal\CustomHtmlElements\CustomTag|string $class */
Original file line number Diff line number Diff line change 1+ <?php
2+ declare (strict_types=1 );
3+
4+ namespace LordSimal \CustomHtmlElements \Test \TagEngine ;
5+
6+ use LordSimal \CustomHtmlElements \TagEngine ;
7+ use PHPUnit \Framework \TestCase ;
8+
9+ /**
10+ * @see \LordSimal\CustomHtmlElements\TagEngine
11+ */
12+ class TagEngineTest extends TestCase
13+ {
14+ /**
15+ * Test singleton instance creation
16+ *
17+ * @return void
18+ */
19+ public function testGetInstance (): void
20+ {
21+ $ options = [
22+ 'tag_directories ' => [
23+ dirname (__DIR__ ) . DIRECTORY_SEPARATOR . 'Tags ' . DIRECTORY_SEPARATOR ,
24+ dirname (__DIR__ ) . DIRECTORY_SEPARATOR . 'plugins ' . DIRECTORY_SEPARATOR ,
25+ ],
26+ ];
27+ $ instance = TagEngine::getInstance ($ options );
28+ $ this ->assertInstanceOf (TagEngine::class, $ instance );
29+
30+ $ sameInstance = TagEngine::getInstance ();
31+ $ this ->assertSame ($ instance , $ sameInstance );
32+ }
33+ }
You can’t perform that action at this time.
0 commit comments