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

Commit 2cadb19

Browse files
committed
add array to properties mapping
1 parent 38516b7 commit 2cadb19

File tree

2 files changed

+55
-4
lines changed

2 files changed

+55
-4
lines changed

src/Traits/WithModelMapping.php

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ trait WithModelMapping
1212
* Maps your model attributes to local class properties.
1313
*
1414
* @param Model|null $model
15-
* @param mixed $failure
15+
* @param mixed $rescue
1616
*
1717
* @return void
1818
*/
19-
public function mapModelAttributes(?Model $model = null, mixed $failure = null): void
19+
public function mapModelAttributes(?Model $model = null, mixed $rescue = null): void
2020
{
2121
if (! is_null($model)) {
2222
$toIgnore = config('model-mapper.ignore_attributes');
@@ -27,15 +27,36 @@ public function mapModelAttributes(?Model $model = null, mixed $failure = null):
2727

2828
collect($model->getAttributes())
2929
->except($ignores)
30-
->each(function ($value, $property) use ($model, $failure) {
30+
->each(function ($value, $property) use ($model, $rescue) {
3131
if (property_exists($this, $property)) {
3232
rescue(
3333
fn () => $this->{$property} = $model->{$property},
34-
$failure,
34+
$rescue,
3535
config('model-mapper.log') ?? false
3636
);
3737
}
3838
});
3939
}
4040
}
41+
42+
/**
43+
* Map array data to class properties.
44+
*
45+
* @param array $data
46+
* @param mixed|null $rescue
47+
*
48+
* @return void
49+
*/
50+
public function arrayToProperties(array $data, mixed $rescue = null): void
51+
{
52+
collect($data)->each(function ($value, $key) use ($rescue) {
53+
if (property_exists($this, $key)) {
54+
rescue(
55+
fn () => $this->{$key} = $value,
56+
$rescue,
57+
config('model-mapper.log') ?? false
58+
);
59+
}
60+
});
61+
}
4162
}

tests/ArrayMappingTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
namespace MichaelRubel\ModelMapper\Tests;
4+
5+
use MichaelRubel\ModelMapper\Traits\WithModelMapping;
6+
7+
class ArrayMappingTest extends TestCase
8+
{
9+
use WithModelMapping;
10+
11+
public bool $test;
12+
public string $name;
13+
public string $password;
14+
15+
/** @test */
16+
public function testCanMapAnArrayToProperties()
17+
{
18+
$array = [
19+
'test' => true,
20+
'name' => 'Michael Rubel',
21+
'password' => 'p@$$w0rd',
22+
];
23+
24+
$this->arrayToProperties($array);
25+
26+
$this->assertTrue($this->test);
27+
$this->assertStringContainsString('Michael', $this->name);
28+
$this->assertStringContainsString('$$', $this->password);
29+
}
30+
}

0 commit comments

Comments
 (0)