Completed
Push — master ( 86f660...4836ad )
by Artem
04:55
created

DataTransferObjectTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 36
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 28 6
1
<?php
2
3
//----------------------------------------------------------------------
4
//
5
//  Copyright (C) 2017 Artem Rodygin
6
//
7
//  You should have received a copy of the MIT License along with
8
//  this file. If not, see <http://opensource.org/licenses/MIT>.
9
//
10
//----------------------------------------------------------------------
11
12
namespace Webinarium;
13
14
/**
15
 * Trait to initialize Data Transfer Objects right on creation.
16
 */
17
trait DataTransferObjectTrait
18
{
19
    /**
20
     * Initializes object properties with values from provided array.
21
     *
22
     * @param array $values Initial values.
23
     */
24
    public function __construct(array $values = null)
25
    {
26
        /**
27
         * Replaces empty strings with nulls.
28
         *
29
         * @param mixed $value A value to be updated. Can be an array.
30
         *
31
         * @return mixed Updated value.
32
         */
33 3
        $empty2null = function ($value) use (&$empty2null) {
34
35 3
            if (is_array($value)) {
36 3
                return array_map($empty2null, $value);
37
            }
38
39 2
            return is_string($value) && mb_strlen($value) === 0 ? null : $value;
40 3
        };
41
42
        $data = $empty2null($values ?? []);
43
44
        $properties = array_keys(get_object_vars($this));
45
46
        foreach ($properties as $property) {
47
            if (array_key_exists($property, $data)) {
48
                $this->$property = $data[$property];
49
            }
50
        }
51
    }
52
}
53