TypeMapper::map()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.2742

Importance

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