Skip to content

Commit

Permalink
Add optional RenameIdFieldProcessor
Browse files Browse the repository at this point in the history
Close #33
  • Loading branch information
hedii committed Jan 13, 2022
1 parent 049976a commit 470c787
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ return [
// Default is an empty array.
'processors' => [
\Hedii\LaravelGelfLogger\Processors\NullStringProcessor::class,
\Hedii\LaravelGelfLogger\Processors\RenameIdFieldProcessor::class,
// another processor...
],

Expand Down
24 changes: 24 additions & 0 deletions src/Processors/RenameIdFieldProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace Hedii\LaravelGelfLogger\Processors;

class RenameIdFieldProcessor
{
/**
* Rename "id" field to "_id" (additional field 'id' is not allowed).
*
* @see https://github.com/hedii/laravel-gelf-logger/issues/33
*/
public function __invoke(array $record): array
{
foreach ($record['context'] as $key => $value) {
if ($key === 'id' && ! array_key_exists('_id', $record['context'])) {
unset($record['context']['id']);

$record['context']['_id'] = $value;
}
}

return $record;
}
}
21 changes: 21 additions & 0 deletions tests/Processors/RenameIdFieldProcessorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Hedii\LaravelGelfLogger\Tests\Processors;

use Hedii\LaravelGelfLogger\Processors\RenameIdFieldProcessor;
use PHPUnit\Framework\TestCase;

class RenameIdFieldProcessorTest extends TestCase
{
/** @test */
public function it_should_rename_id_field(): void
{
$payload = [
'context' => ['id' => 'bar']
];

$processor = new RenameIdFieldProcessor();

$this->assertSame(['context' => ['_id' => 'bar']], $processor($payload));
}
}

0 comments on commit 470c787

Please sign in to comment.