TypeMapper::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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