Skip to content

Commit

Permalink
Fix failed Monolog test; add Reflection cache in LoggerInjector
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk committed Apr 25, 2024
1 parent d99fd14 commit 10f0e8c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
8 changes: 4 additions & 4 deletions src/Bridge/Monolog/tests/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Spiral\Config\ConfiguratorInterface;
use Spiral\Config\LoaderInterface;
use Spiral\Core\Container;
use Spiral\Logger\LogsInterface;
use Spiral\Monolog\Bootloader\MonologBootloader;
use Spiral\Monolog\LogFactory;

Expand All @@ -39,15 +40,14 @@ public function load(string $section): array
));

$this->container->bind(FinalizerInterface::class, $finalizer = new Finalizer());
$this->container->bind(LogFactory::class, $factory = m::mock(Container\InjectorInterface::class));

$logger = m::mock(Logger::class);
$logger->shouldReceive('reset')->once();

$factory->shouldReceive('getLogger')->twice()->andReturn($logger);

$this->container->get(StrategyBasedBootloadManager::class)->bootload([MonologBootloader::class]);
$this->container->get(LoggerInterface::class);

$this->container->bind(LogsInterface::class, $factory = m::mock(LogsInterface::class));
$factory->shouldReceive('getLogger')->once()->andReturn($logger);

$finalizer->finalize();
}
Expand Down
17 changes: 13 additions & 4 deletions src/Logger/src/LoggerInjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,19 @@ public function createInjection(
): LoggerInterface {
$channel = \is_object($context) ? $this->extractChannelAttribute($context) : null;

// Check that null argument is available
$channel ??= (new \ReflectionMethod($this->factory, 'getLogger'))->getParameters()[0]->allowsNull()
? null
: self::DEFAULT_CHANNEL;
if ($channel === null) {
/**
* Array of flags to check if the logger allows null argument
*
* @var array<class-string<LogsInterface>, bool> $cache
*/
static $cache = [];

$cache[$this->factory::class] = (new \ReflectionMethod($this->factory, 'getLogger'))
->getParameters()[0]->allowsNull();

$channel = $cache[$this->factory::class] ? null : self::DEFAULT_CHANNEL;
}

return $this->factory->getLogger($channel);
}
Expand Down

0 comments on commit 10f0e8c

Please sign in to comment.