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

DataTransferObjectTrait::__construct()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 28
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 5
cts 5
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 10
nc 3
nop 1
crap 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