Skip to content

Commit

Permalink
Add callable support to loggers map
Browse files Browse the repository at this point in the history
  • Loading branch information
samizdam committed Nov 30, 2024
1 parent 25c5895 commit 412f564
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Implicitly marking parameters as nullable is deprecated, the explicit nullable type must be used instead

### Added
- Loggers map callable members
- PHP 8.4 mainline support
- PHP 8.5 experimental support

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ return [
],
'loggers' => [
// For suitable logger injections use map, where keys are your services, that implement LoggerAwareInterface
// and value is logger instances
// and value is logger instances or callable with logic for instantiate it.
LoggerAwareClass::class => $logger,
AnotherLoggerAwareClass::class => $anotherLogger,
AnotherLoggerAwareClass::class => fn(\Psr\Container\ContainerInterface $container) => new \Psr\Log\NullLogger(),
],
];
```
Expand Down
3 changes: 3 additions & 0 deletions src/Injector.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ public function createInstance($class): object
if ($this->isLoggerInjectionRequired($instance)) {
if(array_key_exists($class, $this->loggersMap)) {
$logger = $this->loggersMap[$class];
if(!$logger instanceof LoggerInterface && is_callable($logger)) {
$logger = $logger($this);
}
} else {
$logger = $this->getService(LoggerInterface::class);
}
Expand Down
3 changes: 2 additions & 1 deletion tests/InjectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -232,13 +232,14 @@ public function testLoggerMap()
{
$logger = new NullLogger();
$anotherLogger = new NullLogger();
$anotherLoggerCallable = fn() => $anotherLogger;

$injector = new Injector();
$injector->allowInstantiateNotRegisteredTypes(true);
$injector->enableLoggerAwareInjection();
$injector->setLoggersMap([
LoggerAwareClass::class => $logger,
AnotherLoggerAwareClass::class => $anotherLogger,
AnotherLoggerAwareClass::class => $anotherLoggerCallable,
]);

/** @var LoggerAwareClass $loggerAwareInstance */
Expand Down

0 comments on commit 412f564

Please sign in to comment.