Skip to content

Commit

Permalink
Merge pull request #433 from bearsunday/scrutinizer10
Browse files Browse the repository at this point in the history
Refactor Injector
  • Loading branch information
koriym authored Jun 9, 2024
2 parents 6e260eb + dcfde84 commit 46991d8
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions src/Injector/PackageInjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ private function __construct()
{
}

/**
* Returns an instance of InjectorInterface based on the given parameters
*
* - Injector instances are cached in memory and in the cache adapter.
* - The injector is re-used in subsequent calls in the same context in the unit test.
*/
public static function getInstance(AbstractAppMeta $meta, string $context, CacheInterface|null $cache): InjectorInterface
{
$injectorId = str_replace('\\', '_', $meta->name) . $context;
Expand All @@ -52,19 +58,19 @@ public static function getInstance(AbstractAppMeta $meta, string $context, Cache
[$injector, $fileUpdate] = $cache->getItem($injectorId)->get(); // @phpstan-ignore-line
$isCacheableInjector = $injector instanceof ScriptInjector || ($injector instanceof InjectorInterface && $fileUpdate instanceof FileUpdate && $fileUpdate->isNotUpdated($meta));
if (! $isCacheableInjector) {
$injector = self::factory($meta, $context);
$cache->save($cache->getItem($injectorId)->set([$injector, new FileUpdate($meta)]));
// Check the cache
if ($cache->getItem($injectorId)->get() === null) {
trigger_error('Failed to verify the injector cache. See https://github.com/bearsunday/BEAR.Package/issues/418', E_USER_WARNING);
}
$injector = self::getInjector($meta, $context, $cache, $injectorId);
}

self::$instances[$injectorId] = $injector;

return $injector;
}

/**
* Return an injector instance with the given override module
*
* This is useful for testing purposes, where you want to override a module with a mock or stub
*/
public static function factory(AbstractAppMeta $meta, string $context, AbstractModule|null $overrideModule = null): InjectorInterface
{
$scriptDir = $meta->tmpDir . '/di';
Expand All @@ -86,4 +92,16 @@ public static function factory(AbstractAppMeta $meta, string $context, AbstractM

return $injector;
}

private static function getInjector(AbstractAppMeta $meta, string $context, AdapterInterface $cache, string $injectorId): InjectorInterface
{
$injector = self::factory($meta, $context);
$cache->save($cache->getItem($injectorId)->set([$injector, new FileUpdate($meta)]));
// Check the cache
if ($cache->getItem($injectorId)->get() === null) {
trigger_error('Failed to verify the injector cache. See https://github.com/bearsunday/BEAR.Package/issues/418', E_USER_WARNING);
}

return $injector;
}
}

0 comments on commit 46991d8

Please sign in to comment.