Skip to content
This repository was archived by the owner on Mar 12, 2024. It is now read-only.

Commit 2746eb6

Browse files
committed
add configurable logging
1 parent ab65938 commit 2746eb6

File tree

4 files changed

+68
-2
lines changed

4 files changed

+68
-2
lines changed

config/model-mapper.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
return [
4+
5+
/*
6+
|--------------------------------------------------------------------------
7+
| Model Mapper Configuration
8+
|--------------------------------------------------------------------------
9+
|
10+
| Determine if you want to log failed assignments.
11+
|
12+
*/
13+
14+
'log' => true,
15+
16+
];

src/ModelMapperServiceProvider.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ class ModelMapperServiceProvider extends PackageServiceProvider
1818
*/
1919
public function configurePackage(Package $package): void
2020
{
21-
$package->name('laravel-model-mapper');
21+
$package
22+
->name('laravel-model-mapper')
23+
->hasConfigFile();
2224
}
2325
}

src/Traits/WithModelMapping.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@ public function mapModelAttributes(?Model $model = null): void
2020
if (! is_null($model)) {
2121
collect($model->getAttributes())->each(function ($value, $property) use ($model) {
2222
if (property_exists($this, $property)) {
23-
rescue(fn () => $this->{$property} = $model->{$property});
23+
rescue(
24+
fn () => $this->{$property} = $model->{$property},
25+
fn () => null,
26+
config('model-mapper.log') ?? false
27+
);
2428
}
2529
});
2630
}

tests/LoggingTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace MichaelRubel\ModelMapper\Tests;
4+
5+
use Illuminate\Support\Facades\Log;
6+
use MichaelRubel\ModelMapper\Tests\Boilerplate\TestModel;
7+
use MichaelRubel\ModelMapper\Traits\WithModelMapping;
8+
9+
class LoggingTest extends TestCase
10+
{
11+
use WithModelMapping;
12+
13+
public int $number;
14+
15+
/** @test */
16+
public function testMapperCanLog()
17+
{
18+
Log::shouldReceive('error')
19+
->once()
20+
->withArgs(function ($message) {
21+
return str_contains($message, 'Cannot assign');
22+
});
23+
24+
$model = new TestModel([
25+
'number' => false,
26+
]);
27+
28+
$this->mapModelAttributes($model);
29+
}
30+
31+
/** @test */
32+
public function testMapperDoesntLogIfDisabled()
33+
{
34+
config(['model-mapper.log' => false]);
35+
36+
Log::shouldReceive('error')->never();
37+
38+
$model = new TestModel([
39+
'number' => false,
40+
]);
41+
42+
$this->mapModelAttributes($model);
43+
}
44+
}

0 commit comments

Comments
 (0)