commit | author | age
|
ced309
|
1 |
<?php |
JK |
2 |
include(__DIR__.'/stops/common.php'); |
|
3 |
include(__DIR__.'/stops/stops.php'); |
|
4 |
|
|
5 |
try { |
|
6 |
// Reject invalid input |
|
7 |
if(!isset($_GET['query'])) throw new UnexpectedValueException(); |
|
8 |
if(empty($_GET['query'])) throw new UnexpectedValueException(); |
|
9 |
if(strlen($_GET['query']) > 50) throw new UnexpectedValueException(); |
|
10 |
|
|
11 |
// Initialize DB connection an query |
|
12 |
$pdo = new PDO('sqlite:stops/stops.db', NULL, NULL, array( |
|
13 |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION |
|
14 |
)); |
|
15 |
$st = $pdo->prepare('SELECT DISTINCT id FROM stop_search WHERE word LIKE ?'); |
|
16 |
|
|
17 |
// Split stop name into words |
|
18 |
$words = split_stop_name($_GET['query']); |
|
19 |
|
|
20 |
// Find relevant stop IDs |
|
21 |
$ids = NULL; |
|
22 |
foreach($words as $word) { |
|
23 |
if(empty($word)) continue; |
|
24 |
|
|
25 |
// Find stop IDs with names matching the word |
|
26 |
$st->execute(array($word.'%')); |
|
27 |
$results = $st->fetchAll(PDO::FETCH_COLUMN); |
|
28 |
$st->closeCursor(); |
|
29 |
|
|
30 |
// Merge results with previous searches |
|
31 |
if(is_array($ids)) { |
|
32 |
$ids = array_intersect($ids, $results); |
|
33 |
} else { |
|
34 |
$ids = $results; |
|
35 |
} |
|
36 |
|
|
37 |
// No results will be found |
|
38 |
if(count($ids) == 0) break; |
|
39 |
} |
|
40 |
|
|
41 |
// Close DB connection |
|
42 |
unset($st, $pdo); |
|
43 |
|
|
44 |
// No query was executed |
|
45 |
if(!is_array($ids)) throw new UnexpectedValueException(); |
|
46 |
|
|
47 |
// Build structure for UI |
|
48 |
$stop_list = []; |
|
49 |
foreach($ids as $id) { |
|
50 |
$stop_list[] = [ |
|
51 |
'id' => $id, |
|
52 |
'name' => $stops[$id], |
|
53 |
'type' => 'stop', |
|
54 |
'relevance' => similar_text($_GET['query'], $stops[$id]) |
|
55 |
]; |
|
56 |
} |
|
57 |
|
|
58 |
// Sort stops by relevence |
|
59 |
usort($stop_list, function($a, $b) { |
|
60 |
return $b['relevance'] - $a['relevance']; |
|
61 |
}); |
|
62 |
|
|
63 |
// Return JSON |
|
64 |
echo json_encode($stop_list); |
|
65 |
} catch(UnexpectedValueException $e) { |
|
66 |
echo '[]'; |
|
67 |
} catch(Exception $e) { |
|
68 |
header('HTTP/1.1 503 Service Unavailable'); |
|
69 |
echo $e->getMessage(); |
|
70 |
} |