generate.php 1.7 KB
Newer Older
1 2 3
<?php
require_once('config.php');
$directory = __DIR__ . '/json';
4 5 6 7 8
foreach (array($directory, "$directory/ext") as $dir) {
  if (!file_exists($dir)) {
    mkdir($dir);
  }
}
9 10 11 12

// Initialize database
$dbh = new PDO('mysql:dbname='.DBNAME.';host='.DBHOST, DBUSER, DBPASS);

13 14 15 16
// Remove the ONLY_FULL_GROUP_BY flag from SQL mode (MySQL 5.7.5 onwards)
// cf. https://stackoverflow.com/questions/37951742/1055-expression-of-select-list-is-not-in-group-by-clause-and-contains-nonaggr
$dbh->query("SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");

17 18 19 20 21 22 23 24 25 26 27 28
// Initialize the queries array from each subdirectories' include file
$queries = array();
$files = glob_recursive('generate.inc.php');
foreach ($files as $file) {
  require_once($file);
}

// Run the queries and generate target file
foreach ($queries as $query) {
  echo "Creating $query[file] ...";
  $count = 0;
  $out = '[';
cividesk's avatar
cividesk committed
29 30 31 32
  foreach ($dbh->query($query['query'], PDO::FETCH_ASSOC) as $row) {
    if (isset($query['subqueries'])) {
      foreach ($query['subqueries'] as $attr => $subquery) {
        $row[$attr] = array();
33 34 35 36
        if ($subresults = $dbh->query($subquery, PDO::FETCH_ASSOC)) {
          foreach ($subresults as $subrow) {
            $row[$attr][] = $subrow;
          }
cividesk's avatar
cividesk committed
37 38 39
        }
      }
    }
40 41 42
    $out .= json_encode($row) . ',';
    $count ++;
  }
cividesk's avatar
cividesk committed
43

44 45 46 47 48 49 50 51 52 53
  $out[strlen($out)-1] = ']';
  file_put_contents($directory . '/' . $query['file'], $out);
  echo " ($count records)" . PHP_EOL;
}

function glob_recursive($pattern, $flags = 0) {
  $files = glob($pattern, $flags);
  foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
    $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
  return $files;
54
}