helpers.php ➔ map()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 5
nop 2
dl 0
loc 14
ccs 7
cts 7
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Helper functions for Mastodon API Entity
5
 *
6
 * @author    USAMI Kenta <[email protected]>
7
 * @copyright 2017 Baguette HQ
8
 * @license   https://www.gnu.org/licenses/gpl-3.0.html GPL-3.0
9
 */
10
namespace Baguette\Mastodon\Entity
11
{
12
    const DATETIME_FORMAT = 'Y-m-d\TH:i:s.uO';
13
14
    /**
15
     * @param  mixed $value
16
     * @return string|array
17
     */
18
    function toArrayValue($value)
19
    {
20 22
        if ($value instanceof \DateTimeInterface) {
21 3
            return $value->format(\DateTime::W3C);
22
        }
23
24 22
        return \Teto\Object\Helper::toArray($value);
25
    }
26
27
    /**
28
     * Mapping value to object
29
     *
30
     * @param  string|string[] $class
31
     * @param  mixed           $values
32
     * @return Entity|Entity[]|\DateTimeImmutable
33
     */
34
    function map($class, $values)
35
    {
36 5
        if (!is_array($class)) {
37 4
            return ($values instanceof $class) ? $values : new $class($values);
38
        }
39
40 2
        $class = array_pop($class);
41 2
        $retval = [];
42 2
        foreach ($values as $obj) {
43 1
            $retval[] = ($obj instanceof $class) ? $obj : new $class($obj);
44
        }
45
46 2
        return $retval;
47
    }
48
49
    /**
50
     * Mapping values to object by class map
51
     *
52
     * @param  array|\ArrayAccess $input_values
53
     * @param  array|iterable     $class_map
54
     * @return array
55
     */
56
    function mapValues($input_values, $class_map)
57
    {
58 9
        foreach ($class_map as $prop_name => $class) {
59 9
            if (isset($input_values[$prop_name])) {
60 9
                $input_values[$prop_name] = map($class, $input_values[$prop_name]);
61
            }
62
        }
63
64 9
        return $input_values;
65
    }
66
}
67