Completed
Push — master ( a08928...43ef3a )
by Rasmus
03:24
created

TypeMapper::map()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.2742

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 7
cts 9
cp 0.7778
rs 8.8571
cc 5
eloc 9
nc 5
nop 1
crap 5.2742
1
<?php
2
3
namespace mindplay\sql\model\components;
4
5
use mindplay\sql\framework\Mapper;
6
use mindplay\sql\model\schema\Type;
7
use OutOfBoundsException;
8
use UnexpectedValueException;
9
10
/**
11
 * This Mapper performs Type conversions on return variables (columns) returned by
12
 * a returning database query, e.g. SELECT or UPDATE RETURNING queries.
13
 * 
14
 * @see ReturningQuery::getMappers()
15
 */
16
class TypeMapper implements Mapper
17
{
18
    /**
19
     * @var Type[] map where return variable name maps to Type
20
     */
21
    private $types;
22
23
    /**
24
     * @param $types Type[] map where return variable name maps to Type
25
     */
26 1
    public function __construct(array $types)
27
    {
28 1
        $this->types = $types;
29 1
    }
30
31
    /**
32
     * @param array $record_set
33
     *
34
     * @return array
35
     */
36 1
    public function map(array $record_set)
37
    {
38 1
        foreach ($record_set as $index => &$record) {
39 1
            if (! is_array($record)) {
40
                throw new UnexpectedValueException("unexpected record type: " . gettype($record));
41
            }
42
43 1
            foreach ($this->types as $name => $type) {
44 1
                if (! array_key_exists($name, $record)) {
45
                    throw new OutOfBoundsException("undefined record field: {$name}");
46
                }
47
48 1
                $record[$name] = $type->convertToPHP($record[$name]);
49
            }
50
        }
51
52 1
        return $record_set;
53
    }
54
}
55