Passed
Push — main ( 290834...047c8d )
by Michael
11:03
created

WithModelMapping   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
wmc 4
eloc 14
c 5
b 1
f 0
dl 0
loc 26
ccs 14
cts 14
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A mapModelAttributes() 0 17 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\ModelMapper\Traits;
6
7
use Illuminate\Database\Eloquent\Model;
8
9
trait WithModelMapping
10
{
11
    /**
12
     * Maps your model attributes to local class properties.
13
     *
14
     * @param Model|null $model
15
     *
16
     * @return void
17
     */
18 8
    public function mapModelAttributes(?Model $model = null): void
19
    {
20 8
        if (! is_null($model)) {
21 8
            $toIgnore = config('model-mapper.ignore_attributes');
22
23 8
            $ignores = is_array($toIgnore)
24 7
                ? $toIgnore
25 1
                : ['id', 'password'];
26
27 8
            collect($model->getAttributes())
28 8
                ->except($ignores)
29 8
                ->each(function ($value, $property) use ($model) {
30 8
                    if (property_exists($this, $property)) {
31 8
                        rescue(
32 8
                            fn () => $this->{$property} = $model->{$property},
33 8
                            fn () => null,
34 8
                            config('model-mapper.log') ?? false
35
                        );
36
                    }
37 8
                });
38
        }
39 8
    }
40
}
41