Skip to content

[12.x] Add Context::scope() #54799

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 27, 2025
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
29 changes: 29 additions & 0 deletions src/Illuminate/Log/Context/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,35 @@ protected function isHiddenStackable($key)
(is_array($this->hidden[$key]) && array_is_list($this->hidden[$key]));
}

/**
* Run the callback function with the given context values and restore the original context state when complete.
*
* @param callable $callback
* @param array<string, mixed> $data
* @param array<string, mixed> $hidden
* @return mixed
*/
public function scope(callable $callback, array $data = [], array $hidden = [])
{
$dataBefore = $this->data;
$hiddenBefore = $this->hidden;

if ($data !== []) {
$this->add($data);
}

if ($hidden !== []) {
$this->addHidden($hidden);
}

try {
return $callback();
} finally {
$this->data = $dataBefore;
$this->hidden = $hiddenBefore;
}
}

/**
* Determine if the repository is empty.
*
Expand Down
50 changes: 50 additions & 0 deletions tests/Log/ContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,56 @@ public function test_it_adds_context_to_logged_exceptions()
file_put_contents($path, '');
Str::createUuidsNormally();
}

public function test_scope_sets_keys_and_restores()
{
$contextInClosure = [];
$callback = function () use (&$contextInClosure) {
$contextInClosure = ['data' => Context::all(), 'hidden' => Context::allHidden()];

throw new Exception('test_with_sets_keys_and_restores');
};

Context::add('key1', 'value1');
Context::add('key2', 123);
Context::addHidden([
'hiddenKey1' => 'hello',
'hiddenKey2' => 'world',
]);

try {
Context::scope(
$callback,
['key1' => 'with', 'key3' => 'also-with'],
['hiddenKey3' => 'foobar'],
);

$this->fail('No exception was thrown.');
} catch (Exception) {
}

$this->assertEqualsCanonicalizing([
'data' => [
'key1' => 'with',
'key2' => 123,
'key3' => 'also-with',
],
'hidden' => [
'hiddenKey1' => 'hello',
'hiddenKey2' => 'world',
'hiddenKey3' => 'foobar',
],
], $contextInClosure);

$this->assertEqualsCanonicalizing([
'key1' => 'value1',
'key2' => 123,
], Context::all());
$this->assertEqualsCanonicalizing([
'hiddenKey1' => 'hello',
'hiddenKey2' => 'world',
], Context::allHidden());
}
}

enum Suit
Expand Down
Loading