Passed
Push — extents ( f35511...ba1d5f )
by Doug
61:44
created

NADCON5Grid::getValues()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 7
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * PHPCoord.
4
 *
5
 * @author Doug Wright
6
 */
7
declare(strict_types=1);
8
9
namespace PHPCoord\CoordinateOperation;
10
11
use SplFileObject;
12
use UnexpectedValueException;
13
use function unpack;
14
15
class NADCON5Grid extends Grid
16
{
17
    use BiquadraticInterpolation;
18
19
    private string $gridDataType;
20
21
    public function __construct($filename)
22
    {
23
        $this->gridFile = new SplFileObject($filename);
24
25
        $header = $this->getHeader();
26 36
        $this->startX = $header['xlonsw'];
27
        $this->startY = $header['xlatsw'];
28 36
        $this->columnGridInterval = $header['dlon'];
29
        $this->rowGridInterval = $header['dlat'];
30 36
        $this->numberOfColumns = $header['nlon'];
31 36
        $this->numberOfRows = $header['nlat'];
32 36
33 36
        $this->gridDataType = match ($header['ikind']) {
34 36
            1 => 'G',
35 36
            default => throw new UnexpectedValueException("Unknown ikind: {$header['ikind']}"),
36 36
        };
37
    }
38 36
39 36
    protected function getRecord(int $longitudeIndex, int $latitudeIndex): GridValues
40 36
    {
41 36
        $startBytes = 52;
42
        $dataTypeBytes = $this->gridDataType === 'n' ? 2 : 4;
43
        $recordLength = 4 + $this->numberOfColumns * $dataTypeBytes + 4;
44
45 36
        $this->gridFile->fseek($startBytes + $recordLength * $latitudeIndex);
46
        $rawRow = $this->gridFile->fread($recordLength);
47 36
        $row = unpack("Gstartbuffer/{$this->gridDataType}{$this->numberOfColumns}lon/Gendbuffer", $rawRow);
48
49 36
        return new GridValues(
50
            $longitudeIndex * $this->columnGridInterval + $this->startX,
51
            $latitudeIndex * $this->rowGridInterval + $this->startY,
52
            [$row['lon' . ($longitudeIndex + 1)]]
53
        );
54
    }
55 36
56
    private function getHeader(): array
57 36
    {
58 31
        $this->gridFile->fseek(0);
59
        $rawData = $this->gridFile->fread(52);
60
        $data = unpack('Gstartbuffer/Exlatsw/Exlonsw/Edlat/Edlon/Nnlat/Nnlon/Nikind/Gendbuffer/', $rawData);
61
62
        return $data;
63
    }
64
65
    public function getValues(float $x, float $y): array
66
    {
67
        if ($x < 0) {
68
            $x += 360; // NADCON5 uses 0 = 360 = Greenwich
69 36
        }
70 36
71 36
        return $this->interpolate($x, $y);
72 36
    }
73
}
74