Jacek Kowalski
2019-09-14 6a29bc17b45033233cbcf35a60f15d922b5c795d
commit | author | age
bcd661 1 <?php
JK 2 class Output {
3     static function createMapping($db, VehicleTypes $vehicleTypes, $saveConfig = FALSE) {
4         $mapping = [];
5         foreach($db->getAll() as $vehicle) {
6             $mapping[$vehicle['id']] = $vehicleTypes->getByNumber($vehicle['num']);
7         }
8         
9         if($saveConfig) {
10             $json = json_encode($mapping);
11             if(!file_put_contents($saveConfig['result_temp'], $json)) {
12                 throw new Exception('Result save failed');
13             }
14             rename($saveConfig['result_temp'], $saveConfig['result']);
15         }
16         
17         return $mapping;
18     }
19     
20     function createVehiclesList($trips, $mapping, $saveConfig = FALSE) {
21         $lines = [];
22         $vehicles = [];
23         foreach($trips as $trip) {
24             $vehicle = $mapping[$trip['id']] ?? [];
25             $vehicle += ['trip' => $trip['id']];
26             $lines[$trip['line']][] = [
27                 'trip' => $trip,
28                 'vehicle' => $vehicle,
29             ];
30             $vehicles[$vehicle['type'] ?? '?'][] = $vehicle;
31         }
32         foreach($lines as &$line) {
33             usort($line, function($a, $b) {
34                 return (substr($a['vehicle']['num'] ?? '', 2) <=> substr($b['vehicle']['num'] ?? '', 2)); 
35             });
36         }
37         unset($line);
38         ksort($lines);
39         foreach($vehicles as &$vehicle) {
40             usort($vehicle, function($a, $b) {
41                 return (substr($a['num'] ?? '', 2) <=> substr($b['num'] ?? '', 2));
42             });
43         }
44         unset($vehicle);
45         ksort($vehicles);
46         
47         if($saveConfig) {
48             $twigLoader = new \Twig\Loader\FilesystemLoader(__DIR__.'/../templates');
49             $twig = new \Twig\Environment($twigLoader);
50             
51             $vehiclesHtml = $twig->render('vehicles.html', [
52                 'lines' => $lines,
53                 'vehicles' => $vehicles,
54                 'prefix' => $saveConfig['prefix'],
55             ]);
56             if(!file_put_contents($saveConfig['result_vehicles_temp'], $vehiclesHtml)) {
57                 throw new Exception('Vehicles save failed');
58             }
59             rename($saveConfig['result_vehicles_temp'], $saveConfig['result_vehicles']);
60         }
61         
62         return $lines;
63     }
64 }