Completed
Push — master ( d62687...0c8a8b )
by Aurimas
8s
created

Object.php ➔ toArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 3
rs 9.4285
1
<?php
2
3
namespace Funct\Object;
4
5
use Traversable;
6
7
/**
8
 * Creates array from objects using valueMethod as value and with/without keyMethod as key
9
 *
10
 * @param array|Traversable $objects
11
 * @param string            $valueMethod
12
 * @param string            $keyMethod
13
 *
14
 * @return array
15
 *
16
 * @author Aurimas Niekis <[email protected]>
17
 */
18
function toArray($objects, $valueMethod, $keyMethod = null)
19
{
20 1
    $results = [];
21
22 1
    foreach ($objects as $object) {
23 1
        $value = call_user_func([$object, $valueMethod]);
24 1
        if (null !== $keyMethod) {
25 1
            $key = call_user_func([$object, $keyMethod]);
26
27 1
            $results[$key] = $value;
28 1
        } else {
29 1
            $results[] = $value;
30
        }
31 1
    }
32
33 1
    return $results;
34
}
35
36
/**
37
 * Assign value to object from array if key exists
38
 *
39
 * @param object $object
40
 * @param string $property
41
 * @param array  $array
42
 * @param string $key
43
 *
44
 * @return array
45
 *
46
 * @author   Aurimas Niekis <[email protected]>
47
 */
48
function assignIfIsset($object, $property, $array, $key)
49
{
50 1
    if (array_key_exists($key, $array)) {
51 1
        $object->$property = $array[$key];
52 1
    }
53
}
54