Skip to content

Commit 5a4d32e

Browse files
committed
[12.x] Add counter method to Context
1 parent e6753fc commit 5a4d32e

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

src/Illuminate/Log/Context/Repository.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,23 @@ public function popHidden($key)
369369
return array_pop($this->hidden[$key]);
370370
}
371371

372+
/**
373+
* Add or update a context counter.
374+
*
375+
* @param string $key
376+
* @param int $increment
377+
* @return $this
378+
*/
379+
public function counter(string $key, int $increment = 1)
380+
{
381+
$this->add(
382+
$key,
383+
(int) $this->get($key, 0) + $increment,
384+
);
385+
386+
return $this;
387+
}
388+
372389
/**
373390
* Determine if the given value is in the given stack.
374391
*

src/Illuminate/Support/Facades/Context.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
* @method static mixed pop(string $key)
2626
* @method static \Illuminate\Log\Context\Repository pushHidden(string $key, mixed ...$values)
2727
* @method static mixed popHidden(string $key)
28+
* @method static mixed counter(string $key, int $increment)
2829
* @method static bool stackContains(string $key, mixed $value, bool $strict = false)
2930
* @method static bool hiddenStackContains(string $key, mixed $value, bool $strict = false)
3031
* @method static mixed scope(callable $callback, array $data = [], array $hidden = [])

tests/Log/ContextTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -602,6 +602,24 @@ public function test_can_rebind_to_separate_class()
602602

603603
file_put_contents($path, '');
604604
}
605+
606+
public function test_it_adds_counters()
607+
{
608+
Context::counter('foo');
609+
$this->assertSame(1, Context::get('foo'));
610+
611+
Context::counter('foo');
612+
$this->assertSame(2, Context::get('foo'));
613+
}
614+
615+
public function test_it_custom_increments_counters()
616+
{
617+
Context::counter('foo', 2);
618+
$this->assertSame(2, Context::get('foo'));
619+
620+
Context::counter('foo', 3);
621+
$this->assertSame(5, Context::get('foo'));
622+
}
605623
}
606624

607625
enum Suit

0 commit comments

Comments
 (0)