✈ Aviation Data Front End

CIS 51 Vibe Coding — OpenFlights Airline Route Access

Get Code — the PHP source of this web service

index.php

<?php
// Airline Route Access Web Service — CIS 51 "Vibe Coding" assignment.
// PHP 8 port of the C++ (cpp-httplib) service. Loads the provided
// OpenFlights-format data files (SB-airlines.txt, SB-airports.txt,
// SB-routes.txt) and serves the same browser front end.
//
// Run locally:  php -S localhost:8081 index.php
// On Hostinger shared hosting: upload this whole folder to public_html
// (see README.md); .htaccess routes clean URLs to this file.
//
//   GET /airline?code=AA            1.1  full Airline entity for an IATA code
//   GET /airport?code=SFO           1.2  full Airport entity for an IATA code
//   GET /airline-airports?code=AA   2.1a airports reached by an airline,
//                                        ordered by # routes to/from each
//   GET /airport-airlines?code=DEN  2.1b airlines serving an airport,
//                                        ordered by # routes to/from it
//   GET /airlines                   2.2a all airlines ordered by IATA code
//   GET /airports                   2.2b all airports ordered by IATA code
//   GET /get-id                     2.3  site owner's De Anza student ID + name
//   GET /get-owner                       student ID (site ownership check)
//   GET /get-code                        scrollable view of this PHP source
//   GET /one-hop?from=SFO&to=ORD         S->X->D direct-route pairs ordered
//                                        by total air miles + map of the
//                                        top 5 intermediate cities
//   GET /airline-routes?code=AA           JSON: an airline's airports +
//                                        route segments, for the homepage map
//   GET /airlines-into?airport=DEN       airlines flying into an airport
//   GET /top-cities?airline=AA&n=3       an airline's top destination cities
//   GET /distance?from=SFO&to=ORD        great-circle distance in miles/km
//   GET /health                          {"ok":true}
declare(strict_types=1);

require_once __DIR__ . '/src/Util.php';
require_once __DIR__ . '/src/Airline.php';
require_once __DIR__ . '/src/Airport.php';
require_once __DIR__ . '/src/Route.php';
require_once __DIR__ . '/src/DataStore.php';
require_once __DIR__ . '/src/Renderer.php';

// ---------------------------------------------------------------------------
// Site owner (assignment sections 2.3 "Get ID" and C.1 "Get Owner").
// Can also be supplied at runtime with the STUDENT_ID / STUDENT_NAME
// environment variables (Hostinger: set them in .htaccess or hPanel).
// ---------------------------------------------------------------------------
function studentName(): string
{
    $e = getenv('STUDENT_NAME');
    return ($e === false || $e === '') ? 'Bo Engstrom' : $e;
}

function studentId(): string
{
    $e = getenv('STUDENT_ID');
    return ($e === false || $e === '') ? '20640900' : $e;
}

// ---------------------------------------------------------------------------
// Load the data once per request. On shared hosting the files are small
// (7 airlines, 439 airports, 7,762 routes) so this is fast; the OS page
// cache keeps repeat loads cheap.
// ---------------------------------------------------------------------------
$db = new DataStore();
if (!$db->load(__DIR__ . '/data')) {
    http_response_code(500);
    echo Renderer::page('Error', '<h2>Error</h2><p>Failed to load the data files.</p>');
    exit;
}

// ---------------------------------------------------------------------------
// Tiny router: match the request path exactly, like the C++ service.
// ---------------------------------------------------------------------------
function html(string $title, string $body, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: text/html; charset=utf-8');
    echo Renderer::page($title, $body);
}

function json(string $body, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json');
    echo $body;
}

function param(string $name): string
{
    return $_GET[$name] ?? '';
}

$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
if ($path !== '/' && str_ends_with($path, '/')) {
    $path = rtrim($path, '/');
}
if ($path === '/index.php') {
    $path = '/';
}

switch ($path) {
    // --------------------------------------------------------------- /health
    case '/health':
        json('{"ok":true}');
        break;

    // --------------------------------------------------------------- / (home)
    case '/':
        // Hero band: airlines / global-travel theme, decorative inline SVG
        // flight arc with a plane — no new external dependencies.
        $b = "<div class='hero'><div><h2 class='hero-title'>Explore airline routes around the world</h2>"
            . "<p class='hero-tag'>Every airline, every airport, every route — pick an airline below and watch its whole network light up on the map.</p></div>"
            . "<svg width='300' height='110' viewBox='0 0 300 110' aria-hidden='true'>"
            . "<path d='M15 95 Q 150 -10 285 80' fill='none' stroke='rgba(255,255,255,.75)' stroke-width='2' stroke-dasharray='7 8'/>"
            . "<circle cx='15' cy='95' r='5' fill='#fff'/><circle cx='285' cy='80' r='5' fill='#fff'/>"
            . "<text x='256' y='64' font-size='26' fill='#fff'>✈</text>"
            . '</svg></div>';
        $b .= "<div class='stats'>"
            . "<div class='stat'><div class='stat-num'>" . $db->airlineCount() . "</div><div class='stat-label'>Airlines</div></div>"
            . "<div class='stat'><div class='stat-num'>" . $db->airportCount() . "</div><div class='stat-label'>Airports</div></div>"
            . "<div class='stat'><div class='stat-num'>" . $db->routeCount() . "</div><div class='stat-label'>Routes</div></div>"
            . "</div>";
        // Route map: pick an airline, see all of its routes on the map.
        $b .= "<h2>Route map — pick an airline</h2>"
            . "<p class='note'>Every route of the airline you select, drawn on the map.</p>"
            . "<form onsubmit='return false'><label for='airlineSelect'>Airline </label>"
            . "<select id='airlineSelect' name='airlineSelect'>";
        foreach ($db->airlinesByIataOrder() as $al) {
            if (Util::isNull($al->iata)) {
                continue;
            }
            $b .= "<option value='" . Util::esc($al->iata) . "'"
                . (strtoupper($al->iata) === 'SB' ? ' selected' : '') . '>'
                . Util::esc($al->iata) . ' — ' . Util::esc($al->name) . '</option>';
        }
        $b .= "</select></form>"
            . "<div id='map' style='height:420px;border:1px solid #c9d4dd'></div>"
            . "<p class='note' id='mapNote'>Loading routes…</p>"
            . "<link rel='stylesheet' href='https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'>"
            . "<script src='https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'></script>"
            . <<<'JS'
<script>window.addEventListener('load',function(){var sel=document.getElementById('airlineSelect');var note=document.getElementById('mapNote');var map=L.map('map',{center:[20,0],zoom:2,minZoom:1,scrollWheelZoom:false});L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{attribution:'© OpenStreetMap contributors'}).addTo(map);var layer=L.layerGroup().addTo(map);function show(code){note.textContent='Loading routes…';fetch('/airline-routes?code='+encodeURIComponent(code)).then(function(r){if(!r.ok)throw new Error('not found');return r.json();}).then(function(d){layer.clearLayers();var pts=[];var byIata={};d.airports.forEach(function(a){byIata[a.iata]=a;var m=L.circleMarker([a.lat,a.lon],{radius:3,color:'#0b3d66',weight:1,fillColor:'#0b6fa4',fillOpacity:.9}).addTo(layer);m.bindPopup(a.iata+' — '+a.city);pts.push([a.lat,a.lon]);});d.segments.forEach(function(s){var a=byIata[s[0]],c=byIata[s[1]];if(!a||!c)return;L.polyline([[a.lat,a.lon],[c.lat,c.lon]],{color:'#0b6fa4',weight:1,opacity:.45}).addTo(layer);});note.textContent=d.airline.name+' ('+d.airline.iata+'): '+d.routes.toLocaleString()+' routes, '+d.airports.length+' airports.';if(pts.length){map.fitBounds(pts,{padding:[30,30]});}map.invalidateSize();}).catch(function(){note.textContent='Could not load the route map. Try the “Airports reached by this airline” report below.';});}sel.addEventListener('change',function(){show(sel.value);});show(sel.value);setTimeout(function(){map.invalidateSize();},500);});</script>
JS;
        $b .= "<h2>1. Look up one airline or airport (full entity)</h2>"
            . "<form action='/airline'><input name='code' placeholder='Airline IATA, e.g. AA' required>"
            . "<button>Find airline</button></form>"
            . "<form action='/airport'><input name='code' placeholder='Airport IATA, e.g. SFO' required>"
            . "<button>Find airport</button></form>"
            . "<h2>2. Reports ordered by # routes</h2>"
            . "<form action='/airline-airports'><input name='code' placeholder='Airline IATA, e.g. AA' required>"
            . "<button>Airports reached by this airline</button></form>"
            . "<form action='/airport-airlines'><input name='code' placeholder='Airport IATA, e.g. SFO' required>"
            . "<button>Airlines serving this airport</button></form>"
            . "<h2>3. Full reports ordered by IATA code</h2>"
            . "<p><a href='/airlines'>All airlines</a> · <a href='/airports'>All airports</a></p>"
            . "<h2>4. One-hop report (via one intermediate airport)</h2>"
            . "<form action='/one-hop'><input name='from' placeholder='From, e.g. SFO' required>"
            . "<input name='to' placeholder='To, e.g. ORD' required>"
            . "<button>Find one-hop routes</button></form>"
            . "<h2>5. Sample queries</h2>"
            . "<form action='/airlines-into'><input name='airport' placeholder='SFO or San Francisco' required>"
            . "<button>Airlines flying into an airport</button></form>"
            . "<form action='/top-cities'><input name='airline' placeholder='AA' required>"
            . "<input name='n' type='number' value='3' min='1' max='25' style='width:4em'>"
            . "<button>Top cities an airline flies into</button></form>"
            . "<form action='/distance'><input name='from' placeholder='SFO' required>"
            . "<input name='to' placeholder='ORD' required>"
            . "<button>Distance between two airports</button></form>"
            . "<h2>6. Site ownership &amp; source</h2>"
            . "<p><a href='/get-id'>Get ID</a> · <a href='/get-owner'>Get Owner</a> · "
            . "<a href='/get-code'>Get Code (the PHP source of this site)</a></p>";
        html('Aviation Data Front End', $b);
        break;

    // ------------------------------------------------------- 1.1 /airline
    case '/airline':
        $code = param('code');
        $al = $db->airlineByIata($code);
        $b = '';
        if (!$al) {
            $b .= "<h2>Not found</h2><p>No airline with IATA code '" . Util::esc($code) . "'.</p>";
        } else {
            $b .= '<h2>Airline: ' . Util::esc($al->name) . '</h2>' . Renderer::airlineTable($al);
        }
        $b .= Renderer::backLink();
        html('Airline', $b);
        break;

    // ------------------------------------------------------- 1.2 /airport
    case '/airport':
        $code = param('code');
        $ap = $db->airportByIata($code);
        $b = '';
        if (!$ap) {
            $b .= "<h2>Not found</h2><p>No airport with IATA code '" . Util::esc($code) . "'.</p>";
        } else {
            $b .= '<h2>Airport: ' . Util::esc($ap->name) . '</h2>' . Renderer::airportTable($ap);
        }
        $b .= Renderer::backLink();
        html('Airport', $b);
        break;

    // ---------------------------------------------- 2.1a /airline-airports
    case '/airline-airports':
        $code = param('code');
        $al = $db->airlineByIata($code);
        $b = '';
        if (!$al) {
            $b .= "<h2>Not found</h2><p>No airline with IATA code '" . Util::esc($code) . "'.</p>";
        } else {
            $rows = $db->airportsForAirline($al);
            $b .= '<h2>' . Util::esc($al->name) . ' (' . Util::esc($al->iata)
                . ") — airports reached, by # routes</h2>"
                . "<p class='note'>" . count($rows)
                . " airport(s). “# routes” = routes of this airline to or from the airport.</p>"
                . "<div class='scroll'><table>" . Renderer::AIRPORT_HEAD;
            foreach ($rows as $r) {
                $b .= Renderer::airportRow($r['airport'], $r['routes']);
            }
            $b .= '</table></div>';
        }
        $b .= Renderer::backLink();
        html('Airline airports by # routes', $b);
        break;

    // ---------------------------------------------- 2.1b /airport-airlines
    case '/airport-airlines':
        $code = param('code');
        $ap = $db->airportByIata($code);
        $b = '';
        if (!$ap) {
            $b .= "<h2>Not found</h2><p>No airport with IATA code '" . Util::esc($code) . "'.</p>";
        } else {
            $rows = $db->airlinesForAirport($ap);
            $b .= '<h2>' . Util::esc($ap->name) . ' (' . Util::esc($ap->iata)
                . ") — airlines, by # routes</h2>"
                . "<p class='note'>" . count($rows)
                . " airline(s). “# routes” = routes of the airline to or from this airport.</p>"
                . "<div class='scroll'><table>" . Renderer::AIRLINE_HEAD_WITH_COUNT;
            foreach ($rows as $r) {
                $b .= Renderer::airlineRow($r['airline'], $r['routes']);
            }
            $b .= '</table></div>';
        }
        $b .= Renderer::backLink();
        html('Airport airlines by # routes', $b);
        break;

    // ------------------------------------------- /airline-routes (JSON map)
    case '/airline-routes':
        $code = param('code');
        $al = $db->airlineByIata($code);
        if (!$al) {
            json('{"error":"No airline with IATA code \'' . Util::jsonEsc($code) . '\'."}', 404);
            break;
        }
        $pairs = $db->routesForAirline($al);
        $airports = []; // id -> Airport (sorted by id, like C++ std::map)
        foreach ($pairs as $p) {
            $airports[$p['src']->id] = $p['src'];
            $airports[$p['dst']->id] = $p['dst'];
        }
        ksort($airports);
        $j = '{"airline":{"iata":"' . Util::jsonEsc($al->iata)
            . '","name":"' . Util::jsonEsc($al->name)
            . '"},"routes":' . count($pairs) . ',"airports":[';
        $first = true;
        foreach ($airports as $a) {
            if (!$first) {
                $j .= ',';
            }
            $first = false;
            $j .= '{"iata":"' . Util::jsonEsc($a->iata)
                . '","city":"' . Util::jsonEsc($a->city)
                . '","lat":' . Util::num($a->lat) . ',"lon":' . Util::num($a->lon) . '}';
        }
        $j .= '],"segments":[';
        $first = true;
        foreach ($pairs as $p) {
            if (!$first) {
                $j .= ',';
            }
            $first = false;
            $j .= '["' . Util::jsonEsc($p['src']->iata) . '","' . Util::jsonEsc($p['dst']->iata) . '"]';
        }
        $j .= ']}';
        json($j);
        break;

    // ------------------------------------------------------ 2.2a /airlines
    case '/airlines':
        $b = '<h2>All airlines, ordered by IATA code</h2>'
            . "<p class='note'>" . $db->airlineCount() . ' airline(s).</p>'
            . "<div class='scroll'><table>" . Renderer::AIRLINE_HEAD;
        foreach ($db->airlinesByIataOrder() as $al) {
            $b .= Renderer::airlineRow($al);
        }
        $b .= '</table></div>' . Renderer::backLink();
        html('All airlines', $b);
        break;

    // ------------------------------------------------------ 2.2b /airports
    case '/airports':
        $b = '<h2>All airports, ordered by IATA code</h2>'
            . "<p class='note'>" . $db->airportCount() . ' airport(s).</p>'
            . "<div class='scroll'><table>" . Renderer::AIRPORT_HEAD_NO_COUNT;
        foreach ($db->airportsByIataOrder() as $ap) {
            $b .= Renderer::airportRowNoCount($ap);
        }
        $b .= '</table></div>' . Renderer::backLink();
        html('All airports', $b);
        break;

    // --------------------------------------------------------- 2.3 /get-id
    case '/get-id':
        $id = studentId();
        $b = '<h2>Get ID</h2><table>'
            . '<tr><th>Student name</th><td>' . Util::esc(studentName()) . '</td></tr>'
            . '<tr><th>De Anza student ID</th><td>'
            . ($id === '' ? '(not yet configured)' : Util::esc($id))
            . '</td></tr></table>' . Renderer::backLink();
        html('Get ID', $b);
        break;

    // ------------------------------------------------------ C.1 /get-owner
    case '/get-owner':
        $id = studentId();
        $b = '<h2>Site owner</h2><p>This site belongs to <b>' . Util::esc(studentName())
            . '</b>, De Anza student ID <b>'
            . ($id === '' ? '(not yet configured)' : Util::esc($id))
            . '</b>.</p>' . Renderer::backLink();
        html('Get Owner', $b);
        break;

    // ------------------------------------------- C.2 /get-code (PHP source)
    case '/get-code':
        $b = '<h2>Get Code — the PHP source of this web service</h2>';
        $files = [__FILE__];
        foreach (glob(__DIR__ . '/src/*.php') as $f) {
            $files[] = $f;
        }
        foreach ($files as $f) {
            $src = @file_get_contents($f);
            if ($src === false || $src === '') {
                continue;
            }
            $b .= '<h2>' . Util::esc(basename($f)) . '</h2>'
                . "<div class='scroll' style='max-height:75vh'><pre class='code'>"
                . Util::esc($src) . '</pre></div>';
        }
        if ($b === '<h2>Get Code — the PHP source of this web service</h2>') {
            $b .= '<p>Source file not available on the server right now.</p>';
        }
        $b .= Renderer::backLink();
        html('Get Code', $b);
        break;

    // ------------------------------------------------------- C.3 /one-hop
    case '/one-hop':
        $s = $db->airportByIata(param('from'));
        $d = $db->airportByIata(param('to'));
        $b = '';
        if (!$s || !$d) {
            $b .= '<h2>Not found</h2><p>One or both airport codes were not found.</p>';
        } else {
            $hops = $db->oneHop($s, $d);
            $b .= '<h2>One-hop routes: ' . Util::esc($s->iata) . ' (' . Util::esc($s->city)
                . ') → ' . Util::esc($d->iata) . ' (' . Util::esc($d->city) . ')</h2>';
            if ($db->hasDirectRoute($s, $d)) {
                $b .= "<p class='note'>Note: a nonstop route also exists for this pair.</p>";
            }
            if (empty($hops)) {
                $b .= '<p>No one-hop route pairs (both legs nonstop) connect these airports.</p>';
            } else {
                $b .= "<p class='note'>" . count($hops)
                    . ' intermediate airport(s), ordered by total air miles.</p>'
                    . "<div class='scroll'><table>"
                    . '<tr><th>Via</th><th>City</th><th>Country</th><th>Route pairs</th>'
                    . '<th>Total air miles</th><th>Airlines ' . Util::esc($s->iata)
                    . '→via</th><th>Airlines via→' . Util::esc($d->iata) . '</th></tr>';
                foreach ($hops as $h) {
                    $b .= '<tr><td>' . Util::esc($h['via']->iata) . '</td><td>'
                        . Util::esc($h['via']->city) . '</td><td>' . Util::esc($h['via']->country)
                        . '</td><td>' . $h['pairs'] . '</td><td>'
                        . Util::roundMiles($h['miles']) . '</td><td>'
                        . Util::esc($h['leg1']) . '</td><td>'
                        . Util::esc($h['leg2']) . '</td></tr>';
                }
                $b .= '</table></div>';

                // Top 5 intermediate cities by # of route pairs -> map.
                $byPairs = $hops;
                usort($byPairs, static function ($a, $c) {
                    if ($a['pairs'] !== $c['pairs']) {
                        return $c['pairs'] <=> $a['pairs'];
                    }
                    return $a['miles'] <=> $c['miles'];
                });
                $byPairs = array_slice($byPairs, 0, 5);
                $b .= '<h2>Map — top ' . count($byPairs) . ' intermediate cities by # of routes</h2>'
                    . "<div id='map' style='height:420px;border:1px solid #c9d4dd'></div>"
                    . "<link rel='stylesheet' href='https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'>"
                    . "<script src='https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'></script>"
                    . "<script>window.addEventListener('load',function(){var map=L.map('map',{center:["
                    . Util::num(($s->lat + $d->lat) / 2) . ',' . Util::num(($s->lon + $d->lon) / 2)
                    . "],zoom:2,minZoom:1,scrollWheelZoom:false});"
                    . "L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',"
                    . "{attribution:'© OpenStreetMap contributors'}).addTo(map);"
                    . "var pts=[];function mark(lat,lon,label){var m=L.marker([lat,lon]).addTo(map);"
                    . "m.bindPopup(label);pts.push([lat,lon]);}"
                    . 'mark(' . Util::num($s->lat) . ',' . Util::num($s->lon) . ",'"
                    . Util::esc($s->iata) . ' — ' . Util::esc($s->city) . " (start)');"
                    . 'mark(' . Util::num($d->lat) . ',' . Util::num($d->lon) . ",'"
                    . Util::esc($d->iata) . ' — ' . Util::esc($d->city) . " (destination)');";
                foreach ($byPairs as $h) {
                    $b .= 'mark(' . Util::num($h['via']->lat) . ',' . Util::num($h['via']->lon) . ",'"
                        . Util::esc($h['via']->iata) . ' — ' . Util::esc($h['via']->city)
                        . ' (' . $h['pairs'] . ' route pairs, '
                        . Util::roundMiles($h['miles']) . " mi total)');"
                        . 'L.polyline([[' . Util::num($s->lat) . ',' . Util::num($s->lon) . '],['
                        . Util::num($h['via']->lat) . ',' . Util::num($h['via']->lon) . '],['
                        . Util::num($d->lat) . ',' . Util::num($d->lon)
                        . "]],{color:'#0b6fa4',weight:1.5,opacity:.6}).addTo(map);";
                }
                $b .= 'map.fitBounds(pts,{padding:[30,30]});map.invalidateSize();'
                    . "setTimeout(function(){map.invalidateSize();map.fitBounds(pts,{padding:[30,30]});},500);});</script>";
                // Same top-5 data as a plain table, so the information is
                // readable even if the map tiles or scripts do not load.
                $b .= "<div class='scroll'><table>"
                    . '<tr><th>Rank</th><th>Via</th><th>City</th><th>Country</th>'
                    . '<th>Route pairs</th><th>Total air miles</th></tr>';
                $rank = 1;
                foreach ($byPairs as $h) {
                    $b .= '<tr><td>' . $rank++ . '</td><td>' . Util::esc($h['via']->iata)
                        . '</td><td>' . Util::esc($h['via']->city) . '</td><td>'
                        . Util::esc($h['via']->country) . '</td><td>' . $h['pairs']
                        . '</td><td>' . Util::roundMiles($h['miles'])
                        . '</td></tr>';
                }
                $b .= '</table></div>';
            }
        }
        $b .= Renderer::backLink();
        html('One-hop report', $b);
        break;

    // ----------------------------------------------------- /airlines-into
    case '/airlines-into':
        $q = param('airport');
        $ap = $db->findAirport($q);
        $b = '';
        if (!$ap) {
            $b .= "<h2>Not found</h2><p>No airport matching '" . Util::esc($q) . "'.</p>";
        } else {
            $airlines = $db->airlinesInto($ap);
            $b .= '<h2>Airlines flying into ' . Util::esc($ap->city) . ' ('
                . Util::esc($ap->iata) . ')</h2><p>' . Util::esc($ap->name) . '</p><ul>';
            foreach ($airlines as $al) {
                $b .= '<li>' . Util::esc($al->name) . ' (' . Util::esc($al->iata) . ')</li>';
            }
            $b .= '</ul><p>' . count($airlines) . ' airline(s).</p>';
        }
        $b .= Renderer::backLink();
        html('Airlines into airport', $b);
        break;

    // -------------------------------------------------------- /top-cities
    case '/top-cities':
        $code = param('airline');
        $n = 3;
        if (isset($_GET['n'])) {
            $n = max(1, min(25, Util::toInt($_GET['n'], 3)));
        }
        $al = $db->airlineByIata($code);
        $b = '';
        if (!$al) {
            $b .= "<h2>Not found</h2><p>No airline with code '" . Util::esc($code) . "'.</p>";
        } else {
            $top = $db->topCitiesInto($al, $n);
            $b .= '<h2>Top ' . count($top) . ' cities ' . Util::esc($al->name) . ' ('
                . Util::esc($al->iata) . ') flies into</h2>'
                . '<table><tr><th>City</th><th>Airport</th><th>Routes in</th></tr>';
            foreach ($top as $tc) {
                $b .= '<tr><td>' . Util::esc($tc['airport']->city) . '</td><td>'
                    . Util::esc($tc['airport']->iata) . '</td><td>' . $tc['count'] . '</td></tr>';
            }
            $b .= '</table>';
        }
        $b .= Renderer::backLink();
        html('Top cities', $b);
        break;

    // ---------------------------------------------------------- /distance
    case '/distance':
        $a = $db->airportByIata(param('from'));
        $c = $db->airportByIata(param('to'));
        $b = '';
        if (!$a || !$c) {
            $b .= '<h2>Not found</h2><p>One or both airport codes were not found.</p>';
        } else {
            $mi = DataStore::distanceMiles($a, $c);
            $b .= '<h2>' . Util::esc($a->iata) . ' to ' . Util::esc($c->iata) . '</h2>'
                . '<p>' . Util::esc($a->city) . ' (' . Util::esc($a->name) . ') to '
                . Util::esc($c->city) . ' (' . Util::esc($c->name) . ')</p>'
                . '<p><b>' . Util::roundMiles($mi) . ' miles</b> ('
                . Util::roundMiles($mi * 1.60934) . ' km), great-circle distance.</p>';
        }
        $b .= Renderer::backLink();
        html('Distance', $b);
        break;

    // ------------------------------------------------------------- unknown
    default:
        $b = '<h2>Not found</h2><p>No page at this address.</p>' . Renderer::backLink();
        html('Not found', $b, 404);
        break;
}

Airline.php

<?php
// Airline entity — every element from SB-airlines.txt is kept.
// Columns: id, name, alias, IATA, ICAO, callsign, country, active.
declare(strict_types=1);

class Airline
{
    public int $id = 0;
    public string $name = '';
    public string $alias = '';
    public string $iata = '';
    public string $icao = '';
    public string $callsign = '';
    public string $country = '';
    public string $active = '';

    /** Build from one parsed CSV row (8+ fields). */
    public static function fromCsv(array $f): self
    {
        $a = new self();
        $a->id = Util::toInt($f[0]);
        $a->name = $f[1];
        $a->alias = $f[2];
        $a->iata = $f[3];
        $a->icao = $f[4];
        $a->callsign = $f[5];
        $a->country = $f[6];
        $a->active = $f[7];
        return $a;
    }
}

Airport.php

<?php
// Airport entity — every element from SB-airports.txt is kept.
// Columns: id, name, city, country, IATA, ICAO, latitude, longitude,
// altitude, timezone offset, DST, tz database, type, source.
declare(strict_types=1);

class Airport
{
    public int $id = 0;
    public string $name = '';
    public string $city = '';
    public string $country = '';
    public string $iata = '';
    public string $icao = '';
    public string $latRaw = '';   // exactly as in the data file
    public string $lonRaw = '';   // exactly as in the data file
    public float $lat = 0.0;      // parsed, for distance math
    public float $lon = 0.0;      // parsed, for distance math
    public string $altitude = '';
    public string $tzOffset = '';
    public string $dst = '';
    public string $tzDb = '';
    public string $type = '';
    public string $source = '';

    /** Build from one parsed CSV row (14+ fields). */
    public static function fromCsv(array $f): self
    {
        $a = new self();
        $a->id = Util::toInt($f[0]);
        $a->name = $f[1];
        $a->city = $f[2];
        $a->country = $f[3];
        $a->iata = $f[4];
        $a->icao = $f[5];
        $a->latRaw = $f[6];
        $a->lonRaw = $f[7];
        $a->lat = Util::toFloat($f[6]);
        $a->lon = Util::toFloat($f[7]);
        $a->altitude = $f[8];
        $a->tzOffset = $f[9];
        $a->dst = $f[10];
        $a->tzDb = $f[11];
        $a->type = $f[12];
        $a->source = $f[13];
        return $a;
    }
}

DataStore.php

<?php
// DataStore — loads the three provided OpenFlights-format data files and
// answers every query the web service needs. Mirrors the C++ AirTravelDB.
declare(strict_types=1);

class DataStore
{
    /** @var Airline[] */
    private array $airlines = [];
    /** @var Airport[] */
    private array $airports = [];
    /** @var Route[] */
    private array $routes = [];

    /** @var array<string, Airline> IATA (upper) -> Airline */
    private array $airlineByIata = [];
    /** @var array<int, Airline> id -> Airline */
    private array $airlineById = [];
    /** @var array<string, Airport> IATA (upper) -> Airport */
    private array $airportByIata = [];
    /** @var array<int, Airport> id -> Airport */
    private array $airportById = [];

    /** @var Airline[] ordered by IATA code (no-code entries last) */
    private array $airlinesSorted = [];
    /** @var Airport[] ordered by IATA code (no-code entries last) */
    private array $airportsSorted = [];

    public function load(string $dir): bool
    {
        return $this->loadAirlines($dir . '/SB-airlines.txt')
            && $this->loadAirports($dir . '/SB-airports.txt')
            && $this->loadRoutes($dir . '/SB-routes.txt');
    }

    public function airlineByIata(string $iata): ?Airline
    {
        return $this->airlineByIata[strtoupper($iata)] ?? null;
    }

    public function airlineById(int $id): ?Airline
    {
        return $this->airlineById[$id] ?? null;
    }

    public function airportByIata(string $iata): ?Airport
    {
        return $this->airportByIata[strtoupper($iata)] ?? null;
    }

    public function airportById(int $id): ?Airport
    {
        return $this->airportById[$id] ?? null;
    }

    /** Find an airport by IATA code, else by city name (case-insensitive substring). */
    public function findAirport(string $q): ?Airport
    {
        if ($a = $this->airportByIata($q)) {
            return $a;
        }
        foreach ($this->airports as $a) { // file order = id order, as in C++
            if (stripos($a->city, $q) !== false) {
                return $a;
            }
        }
        return null;
    }

    /** All airlines, ordered by IATA code (entries without a code go last). */
    public function airlinesByIataOrder(): array
    {
        return $this->airlinesSorted;
    }

    /** All airports, ordered by IATA code (entries without a code go last). */
    public function airportsByIataOrder(): array
    {
        return $this->airportsSorted;
    }

    /**
     * 2.1a: airports reached by an airline, counted by # routes to/from each.
     * @return array<int, array{airport: Airport, routes: int}>
     */
    public function airportsForAirline(Airline $al): array
    {
        $counts = [];
        foreach ($this->routes as $r) {
            if ($r->airlineId !== $al->id) {
                continue;
            }
            $counts[$r->srcId] = ($counts[$r->srcId] ?? 0) + 1;
            if ($r->dstId !== $r->srcId) {
                $counts[$r->dstId] = ($counts[$r->dstId] ?? 0) + 1;
            }
        }
        $out = [];
        foreach ($counts as $id => $n) {
            if ($ap = $this->airportById($id)) {
                $out[] = ['airport' => $ap, 'routes' => $n];
            }
        }
        usort($out, static function ($a, $b) {
            if ($a['routes'] !== $b['routes']) {
                return $b['routes'] <=> $a['routes'];
            }
            return strcmp($a['airport']->iata, $b['airport']->iata);
        });
        return $out;
    }

    /**
     * Distinct route pairs (src -> dst) flown by an airline, for the
     * homepage route map. Each pair appears once, even if the data file
     * lists it more than once. Pairs with a missing airport, or an airport
     * with no coordinates (0,0), are skipped.
     * @return array<int, array{src: Airport, dst: Airport}>
     */
    public function routesForAirline(Airline $al): array
    {
        $seen = [];
        $out = [];
        foreach ($this->routes as $r) {
            if ($r->airlineId !== $al->id) {
                continue;
            }
            $key = $r->srcId . ':' . $r->dstId;
            if (isset($seen[$key])) {
                continue;
            }
            $seen[$key] = true;
            $s = $this->airportById($r->srcId);
            $d = $this->airportById($r->dstId);
            if (!$s || !$d) {
                continue;
            }
            if (($s->lat == 0 && $s->lon == 0) || ($d->lat == 0 && $d->lon == 0)) {
                continue;
            }
            $out[] = ['src' => $s, 'dst' => $d];
        }
        return $out;
    }

    /**
     * 2.1b: airlines with routes that include an airport, counted by # routes.
     * @return array<int, array{airline: Airline, routes: int}>
     */
    public function airlinesForAirport(Airport $ap): array
    {
        $counts = [];
        foreach ($this->routes as $r) {
            if ($r->srcId === $ap->id || $r->dstId === $ap->id) {
                $counts[$r->airlineId] = ($counts[$r->airlineId] ?? 0) + 1;
            }
        }
        $out = [];
        foreach ($counts as $id => $n) {
            if ($al = $this->airlineById($id)) {
                $out[] = ['airline' => $al, 'routes' => $n];
            }
        }
        usort($out, static function ($a, $b) {
            if ($a['routes'] !== $b['routes']) {
                return $b['routes'] <=> $a['routes'];
            }
            return strcmp($a['airline']->iata, $b['airline']->iata);
        });
        return $out;
    }

    /** Distinct airlines flying INTO the given airport (sample-query helper). */
    public function airlinesInto(Airport $ap): array
    {
        $seen = [];
        $out = [];
        foreach ($this->routes as $r) {
            if ($r->dstId === $ap->id && !isset($seen[$r->airlineId])) {
                $seen[$r->airlineId] = true;
                if ($al = $this->airlineById($r->airlineId)) {
                    $out[] = $al;
                }
            }
        }
        usort($out, static fn (Airline $a, Airline $b) => strcmp($a->name, $b->name));
        return $out;
    }

    /**
     * Top destination cities for an airline: (airport, route count).
     * @return array<int, array{airport: Airport, count: int}>
     */
    public function topCitiesInto(Airline $al, int $n): array
    {
        $counts = [];
        foreach ($this->routes as $r) {
            if ($r->airlineId === $al->id) {
                $counts[$r->dstId] = ($counts[$r->dstId] ?? 0) + 1;
            }
        }
        $out = [];
        foreach ($counts as $id => $c) {
            if ($ap = $this->airportById($id)) {
                $out[] = ['airport' => $ap, 'count' => $c];
            }
        }
        usort($out, static function ($a, $b) {
            if ($a['count'] !== $b['count']) {
                return $b['count'] <=> $a['count'];
            }
            return strcmp($a['airport']->city, $b['airport']->city);
        });
        return array_slice($out, 0, $n);
    }

    /**
     * One-hop report: intermediate airports X with a direct (0-stop) route
     * S->X and a direct route X->D. Aggregated per X: number of route pairs
     * and total air miles S->X->D, ordered by total miles.
     * @return array<int, array{via: Airport, pairs: int, miles: float, leg1: string, leg2: string}>
     */
    public function oneHop(Airport $src, Airport $dst): array
    {
        $leg1 = []; // dstId -> set of airline IATA codes on S->X
        $leg2 = []; // srcId -> set of airline IATA codes on X->D
        foreach ($this->routes as $r) {
            if ($r->stops !== 0) {
                continue;
            }
            if ($r->srcId === $src->id && $r->dstId !== $src->id && $r->dstId !== $dst->id) {
                $leg1[$r->dstId][$r->airlineIata] = true;
            }
            if ($r->dstId === $dst->id && $r->srcId !== $src->id && $r->srcId !== $dst->id) {
                $leg2[$r->srcId][$r->airlineIata] = true;
            }
        }
        $out = [];
        foreach ($leg1 as $viaId => $a1) {
            if (!isset($leg2[$viaId])) {
                continue;
            }
            $via = $this->airportById($viaId);
            if (!$via) {
                continue;
            }
            $a2 = $leg2[$viaId];
            ksort($a1);
            ksort($a2);
            $out[] = [
                'via' => $via,
                'pairs' => count($a1) * count($a2),
                'miles' => self::distanceMiles($src, $via) + self::distanceMiles($via, $dst),
                'leg1' => implode(', ', array_keys($a1)),
                'leg2' => implode(', ', array_keys($a2)),
            ];
        }
        usort($out, static function ($a, $b) {
            if ($a['miles'] != $b['miles']) {
                return $a['miles'] <=> $b['miles'];
            }
            return strcmp($a['via']->iata, $b['via']->iata);
        });
        return $out;
    }

    public function hasDirectRoute(Airport $a, Airport $b): bool
    {
        foreach ($this->routes as $r) {
            if ($r->stops === 0 && $r->srcId === $a->id && $r->dstId === $b->id) {
                return true;
            }
        }
        return false;
    }

    /** Great-circle distance in miles (haversine, Earth radius 3958.8 mi). */
    public static function distanceMiles(Airport $a, Airport $b): float
    {
        $r = 3958.8;
        $dLat = deg2rad($b->lat - $a->lat);
        $dLon = deg2rad($b->lon - $a->lon);
        $la1 = deg2rad($a->lat);
        $la2 = deg2rad($b->lat);
        $h = sin($dLat / 2) * sin($dLat / 2)
            + cos($la1) * cos($la2) * sin($dLon / 2) * sin($dLon / 2);
        return 2 * $r * asin(sqrt($h));
    }

    public function airlineCount(): int { return count($this->airlines); }
    public function airportCount(): int { return count($this->airports); }
    public function routeCount(): int { return count($this->routes); }

    private function loadAirlines(string $path): bool
    {
        $lines = $this->readLines($path);
        if ($lines === null) {
            return false;
        }
        foreach ($lines as $line) {
            $f = str_getcsv($line);
            if (count($f) < 8) {
                continue;
            }
            $this->airlines[] = Airline::fromCsv($f);
        }
        foreach ($this->airlines as $a) {
            $this->airlineById[$a->id] = $a;
            if (!Util::isNull($a->iata)) {
                $this->airlineByIata[strtoupper($a->iata)] = $a;
            }
        }
        $this->airlinesSorted = $this->airlines;
        usort($this->airlinesSorted, [self::class, 'cmpIataAirline']);
        return true;
    }

    private function loadAirports(string $path): bool
    {
        $lines = $this->readLines($path);
        if ($lines === null) {
            return false;
        }
        foreach ($lines as $line) {
            $f = str_getcsv($line);
            if (count($f) < 14) {
                continue;
            }
            $this->airports[] = Airport::fromCsv($f);
        }
        foreach ($this->airports as $a) {
            $this->airportById[$a->id] = $a;
            if (!Util::isNull($a->iata)) {
                $this->airportByIata[strtoupper($a->iata)] = $a;
            }
        }
        $this->airportsSorted = $this->airports;
        usort($this->airportsSorted, [self::class, 'cmpIataAirport']);
        return true;
    }

    private function loadRoutes(string $path): bool
    {
        $lines = $this->readLines($path);
        if ($lines === null) {
            return false;
        }
        foreach ($lines as $line) {
            $f = str_getcsv($line);
            if (count($f) < 9) {
                continue;
            }
            $this->routes[] = Route::fromCsv($f);
        }
        return true;
    }

    /** IATA sort key: entries without a code sort last ("~" sentinel, as in C++). */
    private static function cmpIataAirline(Airline $x, Airline $y): int
    {
        $a = Util::isNull($x->iata) ? '~' : strtoupper($x->iata);
        $b = Util::isNull($y->iata) ? '~' : strtoupper($y->iata);
        return strcmp($a, $b);
    }

    private static function cmpIataAirport(Airport $x, Airport $y): int
    {
        $a = Util::isNull($x->iata) ? '~' : strtoupper($x->iata);
        $b = Util::isNull($y->iata) ? '~' : strtoupper($y->iata);
        return strcmp($a, $b);
    }

    /** Read a data file into non-empty lines (strips trailing \r like the C++ loader). */
    private function readLines(string $path): ?array
    {
        if (!is_readable($path)) {
            error_log("cannot open $path");
            return null;
        }
        $lines = file($path, FILE_IGNORE_NEW_LINES);
        if ($lines === false) {
            return null;
        }
        $out = [];
        foreach ($lines as $line) {
            $line = rtrim($line, "\r");
            if ($line === '') {
                continue;
            }
            $out[] = $line;
        }
        return $out;
    }
}

Renderer.php

<?php
// Renderer — HTML page chrome and table builders. Mirrors the C++ service's
// page(), CSS, and entity/report table helpers exactly.
declare(strict_types=1);

class Renderer
{
    // Fresh airlines / global-travel theme: sky-inspired gradient header,
    // modern rounded cards with soft shadows, sticky pill nav, card tables,
    // footer. Structure and class names are unchanged, so every page's
    // markup and data output stay the same.
    public const CSS =
        "body{font-family:ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;margin:0;background:#edf3f8;color:#1c2733;line-height:1.55}"
        . "header{background:linear-gradient(115deg,#061a3a 0%,#0b3d66 45%,#0e7490 72%,#38bdf8 100%);color:#fff;padding:1.7em 1.5em 1.5em}"
        . "header h1{margin:.1em 0;font-size:1.65em;letter-spacing:-.02em}"
        . "nav{background:#072f4f;padding:.55em 1.5em;position:sticky;top:0;z-index:10;box-shadow:0 2px 8px rgba(11,61,102,.3)}"
        . "nav a{color:#cfe6f5;margin-right:.3em;padding:.35em .8em;border-radius:999px;text-decoration:none;font-size:.93em;background:rgba(255,255,255,.08);transition:background .15s}"
        . "nav a:hover{background:rgba(255,255,255,.18);color:#fff}"
        . "main{max-width:72em;margin:0 auto;padding:1.4em 1.5em 3em}"
        . "h2{margin:1.6em 0 .6em;color:#0b3d66;font-size:1.25em;letter-spacing:-.01em}"
        . "h2:first-child{margin-top:.2em}"
        . "a{color:#0b6fa4}"
        . "table{border-collapse:separate;border-spacing:0;background:#fff;width:100%;border-radius:14px;overflow:hidden;box-shadow:0 4px 14px rgba(11,61,102,.08)}"
        . "td,th{border-bottom:1px solid #dbe4ec;padding:.5em .8em;text-align:left;font-size:.93em}"
        . "th{background:#e6f1f8;color:#33506a;font-size:.8em;text-transform:uppercase;letter-spacing:.05em;white-space:nowrap}"
        . "tr:last-child td{border-bottom:0}"
        . "tbody tr:hover{background:#f0f8fd}"
        . "form{margin:.8em 0}"
        . "input{padding:.5em .7em;border:1px solid #b8c9d6;border-radius:10px;font-size:.95em;background:#fff}"
        . "input:focus{outline:2px solid #38bdf8;outline-offset:1px;border-color:#0ea5e9}"
        . "select{padding:.5em .7em;border:1px solid #b8c9d6;border-radius:10px;font-size:.95em;background:#fff}"
        . "button{padding:.5em 1.2em;background:linear-gradient(135deg,#0284c7,#0ea5e9);color:#fff;border:0;border-radius:10px;cursor:pointer;font-weight:600;font-size:.95em;box-shadow:0 1px 3px rgba(11,61,102,.3)}"
        . "button:hover{background:#0369a1}"
        . ".scroll{max-height:65vh;overflow:auto;border:1px solid #dbe4ec;border-radius:14px;box-shadow:0 4px 14px rgba(11,61,102,.08);background:#fff}"
        . ".scroll table{box-shadow:none;border-radius:0}"
        . ".scroll th{position:sticky;top:0}"
        . "#map{border-radius:16px;box-shadow:0 8px 24px rgba(11,61,102,.18)}"
        . "pre.code{background:#10222e;color:#d7e8f0;padding:1em;border-radius:10px;overflow:auto}"
        . ".note{color:#5a6b78;font-size:.92em}"
        . ".stats{display:grid;grid-template-columns:repeat(3,1fr);gap:1em;margin:0 0 1.4em}"
        . ".stat{background:#fff;border:1px solid #dbe4ec;border-radius:16px;padding:1.1em .5em;text-align:center;box-shadow:0 6px 18px rgba(11,61,102,.10);transition:transform .15s}"
        . ".stat:hover{transform:translateY(-2px)}"
        . ".stat-num{font-size:1.9em;font-weight:700;color:#0b3d66;line-height:1.1}"
        . ".stat:nth-child(1) .stat-num::before{content:'✈ '}"
        . ".stat:nth-child(2) .stat-num::before{content:'🌍 '}"
        . ".stat:nth-child(3) .stat-num::before{content:'🛫 '}"
        . ".stat-label{color:#5a6b78;font-size:.9em;margin-top:.2em}"
        . ".hero{display:flex;align-items:center;gap:1em;background:linear-gradient(120deg,#0b3d66,#0e7490 55%,#38bdf8);color:#fff;border-radius:16px;padding:1.2em 1.5em;margin:0 0 1.2em;box-shadow:0 8px 24px rgba(11,61,102,.25)}"
        . "h2.hero-title{color:#fff;margin:0 0 .25em;font-size:1.5em}"
        . ".hero-tag{color:#dbeeff;margin:0;font-size:.98em}"
        . ".hero svg{flex:0 0 auto;opacity:.95}"
        . "@media(max-width:640px){.hero{flex-direction:column;align-items:flex-start}.hero svg{display:none}.stats{grid-template-columns:1fr}}"
        . "footer{text-align:center;color:#5a6b78;font-size:.85em;padding:1.5em 1em 2em;border-top:1px solid #dbe4ec}";

    public static function page(string $title, string $body): string
    {
        return "<!doctype html><html><head><meta charset='utf-8'>"
            . "<meta name='viewport' content='width=device-width,initial-scale=1'>"
            . "<link rel='icon' href='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22%3E%3Ctext y=%22.9em%22 font-size=%2290%22%3E✈️%3C/text%3E%3C/svg%3E'>"
            . "<title>" . $title . "</title><style>" . self::CSS . "</style></head><body>"
            . "<header><h1>✈ Aviation Data Front End</h1>"
            . "<div class='note' style='color:#cfe6f5'>CIS 51 Vibe Coding — OpenFlights Airline Route Access</div></header>"
            . "<nav><a href='/'>Home</a><a href='/airlines'>All Airlines</a>"
            . "<a href='/airports'>All Airports</a><a href='/get-id'>Get ID</a>"
            . "<a href='/get-owner'>Get Owner</a><a href='/get-code'>Get Code</a></nav>"
            . "<main>" . $body . "</main>"
            . "<footer>Built by Bo Engstrom · CIS 51 Vibe Coding · De Anza College</footer></body></html>";
    }

    public static function backLink(): string
    {
        return "<p><a href='/'>← Back to home</a></p>";
    }

    // Full entity tables: every element of the entity is shown.
    public static function airlineTable(Airline $a): string
    {
        $e = [Util::class, 'esc'];
        $s = [Util::class, 'show'];
        return "<table>"
            . "<tr><th>Name</th><td>" . $e($a->name) . "</td></tr>"
            . "<tr><th>Alias</th><td>" . $e($s($a->alias)) . "</td></tr>"
            . "<tr><th>IATA</th><td>" . $e($s($a->iata)) . "</td></tr>"
            . "<tr><th>ICAO</th><td>" . $e($s($a->icao)) . "</td></tr>"
            . "<tr><th>Callsign</th><td>" . $e($s($a->callsign)) . "</td></tr>"
            . "<tr><th>Country</th><td>" . $e($a->country) . "</td></tr>"
            . "<tr><th>Active</th><td>" . $e($a->active) . "</td></tr>"
            . "</table>";
    }

    public static function airportTable(Airport $a): string
    {
        $e = [Util::class, 'esc'];
        $s = [Util::class, 'show'];
        return "<table>"
            . "<tr><th>Name</th><td>" . $e($a->name) . "</td></tr>"
            . "<tr><th>City</th><td>" . $e($a->city) . "</td></tr>"
            . "<tr><th>Country</th><td>" . $e($a->country) . "</td></tr>"
            . "<tr><th>IATA</th><td>" . $e($s($a->iata)) . "</td></tr>"
            . "<tr><th>ICAO</th><td>" . $e($s($a->icao)) . "</td></tr>"
            . "<tr><th>Latitude</th><td>" . $e($a->latRaw) . "</td></tr>"
            . "<tr><th>Longitude</th><td>" . $e($a->lonRaw) . "</td></tr>"
            . "<tr><th>Altitude (ft)</th><td>" . $e($a->altitude) . "</td></tr>"
            . "<tr><th>Timezone (UTC offset)</th><td>" . $e($a->tzOffset) . "</td></tr>"
            . "<tr><th>DST</th><td>" . $e($a->dst) . "</td></tr>"
            . "<tr><th>Tz database timezone</th><td>" . $e($a->tzDb) . "</td></tr>"
            . "<tr><th>Type</th><td>" . $e($a->type) . "</td></tr>"
            . "<tr><th>Source</th><td>" . $e($a->source) . "</td></tr>"
            . "</table>";
    }

    // One row of a report: all elements of an airport plus its "# routes" value.
    public static function airportRow(Airport $a, int $routes): string
    {
        $e = [Util::class, 'esc'];
        $s = [Util::class, 'show'];
        return "<tr><td><b>" . $routes . "</b></td>"
            . "<td>" . $e($s($a->iata)) . "</td>"
            . "<td>" . $e($a->name) . "</td>"
            . "<td>" . $e($a->city) . "</td>"
            . "<td>" . $e($a->country) . "</td>"
            . "<td>" . $e($s($a->icao)) . "</td>"
            . "<td>" . $e($a->latRaw) . "</td>"
            . "<td>" . $e($a->lonRaw) . "</td>"
            . "<td>" . $e($a->altitude) . "</td>"
            . "<td>" . $e($a->tzOffset) . "</td>"
            . "<td>" . $e($a->dst) . "</td>"
            . "<td>" . $e($a->tzDb) . "</td>"
            . "<td>" . $e($a->type) . "</td>"
            . "<td>" . $e($a->source) . "</td></tr>";
    }

    public const AIRPORT_HEAD =
        "<tr><th># routes</th><th>IATA</th><th>Name</th><th>City</th><th>Country</th>"
        . "<th>ICAO</th><th>Latitude</th><th>Longitude</th><th>Altitude (ft)</th>"
        . "<th>TZ offset</th><th>DST</th><th>Tz database</th><th>Type</th><th>Source</th></tr>";

    /** $routes < 0 omits the "# routes" cell (all-airlines list). */
    public static function airlineRow(Airline $a, int $routes = -1): string
    {
        $e = [Util::class, 'esc'];
        $s = [Util::class, 'show'];
        $row = "<tr>";
        if ($routes >= 0) {
            $row .= "<td><b>" . $routes . "</b></td>";
        }
        $row .= "<td>" . $e($s($a->iata)) . "</td>"
            . "<td>" . $e($a->name) . "</td>"
            . "<td>" . $e($s($a->alias)) . "</td>"
            . "<td>" . $e($s($a->icao)) . "</td>"
            . "<td>" . $e($s($a->callsign)) . "</td>"
            . "<td>" . $e($a->country) . "</td>"
            . "<td>" . $e($a->active) . "</td></tr>";
        return $row;
    }

    public const AIRLINE_HEAD_WITH_COUNT =
        "<tr><th># routes</th><th>IATA</th><th>Name</th><th>Alias</th><th>ICAO</th>"
        . "<th>Callsign</th><th>Country</th><th>Active</th></tr>";

    public const AIRLINE_HEAD =
        "<tr><th>IATA</th><th>Name</th><th>Alias</th><th>ICAO</th>"
        . "<th>Callsign</th><th>Country</th><th>Active</th></tr>";

    public const AIRPORT_HEAD_NO_COUNT =
        "<tr><th>IATA</th><th>Name</th><th>City</th><th>Country</th>"
        . "<th>ICAO</th><th>Latitude</th><th>Longitude</th><th>Altitude (ft)</th>"
        . "<th>TZ offset</th><th>DST</th><th>Tz database</th><th>Type</th><th>Source</th></tr>";

    public static function airportRowNoCount(Airport $a): string
    {
        $e = [Util::class, 'esc'];
        $s = [Util::class, 'show'];
        return "<tr>"
            . "<td>" . $e($s($a->iata)) . "</td>"
            . "<td>" . $e($a->name) . "</td>"
            . "<td>" . $e($a->city) . "</td>"
            . "<td>" . $e($a->country) . "</td>"
            . "<td>" . $e($s($a->icao)) . "</td>"
            . "<td>" . $e($a->latRaw) . "</td>"
            . "<td>" . $e($a->lonRaw) . "</td>"
            . "<td>" . $e($a->altitude) . "</td>"
            . "<td>" . $e($a->tzOffset) . "</td>"
            . "<td>" . $e($a->dst) . "</td>"
            . "<td>" . $e($a->tzDb) . "</td>"
            . "<td>" . $e($a->type) . "</td>"
            . "<td>" . $e($a->source) . "</td></tr>";
    }
}

Route.php

<?php
// Route entity — one row of SB-routes.txt.
// Columns: airline IATA, airline id, source IATA, source id,
// destination IATA, destination id, codeshare, stops, equipment.
declare(strict_types=1);

class Route
{
    public string $airlineIata = '';
    public int $airlineId = 0;
    public string $srcIata = '';
    public int $srcId = 0;
    public string $dstIata = '';
    public int $dstId = 0;
    public string $codeshare = '';
    public int $stops = 0;
    public string $equipment = '';

    /** Build from one parsed CSV row (9+ fields). */
    public static function fromCsv(array $f): self
    {
        $r = new self();
        $r->airlineIata = $f[0];
        $r->airlineId = Util::toInt($f[1]);
        $r->srcIata = $f[2];
        $r->srcId = Util::toInt($f[3]);
        $r->dstIata = $f[4];
        $r->dstId = Util::toInt($f[5]);
        $r->codeshare = $f[6];
        $r->stops = Util::toInt($f[7]);
        $r->equipment = $f[8];
        return $r;
    }
}

Util.php

<?php
// Small shared helpers: number parsing, nulls, escaping, number formatting.
// Mirrors the helpers in the C++ service (toInt/toDouble, isNull/show,
// htmlEscape, jsonEscape, num).
declare(strict_types=1);

class Util
{
    /** Parse an int the way C++ std::stoi does: leading digits, else $dflt. */
    public static function toInt(string $s, int $dflt = 0): int
    {
        if (preg_match('/^\s*[+-]?\d+/', $s, $m)) {
            return (int)$m[0];
        }
        return $dflt;
    }

    /** Parse a float the way C++ std::stod does: leading number, else $dflt. */
    public static function toFloat(string $s, float $dflt = 0.0): float
    {
        if (preg_match('/^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?/', $s, $m)) {
            return (float)$m[0];
        }
        return $dflt;
    }

    /** OpenFlights uses \N for "no value". */
    public static function isNull(string $s): bool
    {
        return $s === '' || $s === '\\N';
    }

    public static function show(string $s): string
    {
        return self::isNull($s) ? '(none)' : $s;
    }

    /** Escape for HTML text (same set as the C++ htmlEscape: & < > "). */
    public static function esc(string $s): string
    {
        return str_replace(
            ['&', '<', '>', '"'],
            ['&amp;', '&lt;', '&gt;', '&quot;'],
            $s
        );
    }

    /** Escape a string for use inside a JSON double-quoted string. */
    public static function jsonEsc(string $s): string
    {
        $out = '';
        $len = strlen($s);
        for ($i = 0; $i < $len; $i++) {
            $c = $s[$i];
            $o = ord($c);
            switch ($c) {
                case '"':  $out .= '\\"'; break;
                case '\\': $out .= '\\\\'; break;
                case "\n": $out .= '\\n'; break;
                case "\r": $out .= '\\r'; break;
                case "\t": $out .= '\\t'; break;
                default:
                    if ($o < 0x20) {
                        $out .= sprintf('\\u%04x', $o);
                    } else {
                        $out .= $c;
                    }
            }
        }
        return $out;
    }

    /**
     * Format a double the way it appears in the data files (no trailing
     * zeros): C++ std::setprecision(10) default formatting = 10 significant
     * digits, which is PHP's %.10g.
     */
    public static function num(float $v): string
    {
        return sprintf('%.10g', $v);
    }

    /** Round a positive mile value to the nearest whole mile (C++ (long)(x+0.5)). */
    public static function roundMiles(float $v): int
    {
        return (int)($v + 0.5);
    }
}

← Back to home