Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/Test/TestLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,22 @@ class TestLogger implements LoggerInterface
public array $records = [];
public array $recordsByLevel = [];

private bool $placeholderInterpolation;

public function __construct(bool $placeholderInterpolation = false)
{
$this->placeholderInterpolation = $placeholderInterpolation;
}

/**
* @inheritdoc
*/
public function log($level, string|\Stringable $message, array $context = []): void
{
if ($this->placeholderInterpolation === true) {
$message = $this->interpolate($message, $context);
}

$record = [
'level' => $level,
'message' => $message,
Expand Down Expand Up @@ -325,4 +336,27 @@ public function reset()
$this->records = [];
$this->recordsByLevel = [];
}

/**
* Interpolates context values into the message placeholders.
*
* @param string|\Stringable $message
* @param array $context
* @return string
*/
private function interpolate($message, array $context = []) : string
{
// build a replacement array with braces around the context keys
$replace = array();
foreach ($context as $key => $val) {
// check that the value can be cast to string
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
$replace['{' . $key . '}'] = $val;
}
}

// interpolate replacement values into the message and return
return strtr($message, $replace);
}

}
8 changes: 8 additions & 0 deletions tests/Test/TestLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,12 @@ public function testFalseHasRecord(): void
$this->assertFalse($logger->hasDebugThatMatches('/warning message/'));
$this->assertFalse($logger->hasDebugThatPasses(fn (array $record) => 'warning message' === $record['message']));
}

public function testPlaceholderInterpolation() : void
{
$logger = new TestLogger(true);
$message = 'User {username} created';
$logger->debug($message, ['username' => 'bolivar']);
$this->assertTrue($logger->hasDebugThatContains('User bolivar created'));
}
}