avm99963 | 5b8dde4 | 2020-09-24 18:18:16 +0200 | [diff] [blame] | 1 | <?php |
| 2 | // add_subjects.php - A PHP script used to add subjects to the subjects list |
| 3 | // saved in the DB. |
| 4 | |
| 5 | require_once(__DIR__.'/../core.php'); |
| 6 | |
| 7 | if (php_sapi_name() != 'cli') |
| 8 | exit(); |
| 9 | |
| 10 | $subjects = []; |
| 11 | |
| 12 | if ($argc == 2 && $argv[1] == '--stdin') { |
| 13 | $stdin = file_get_contents('php://stdin'); |
| 14 | $subjects = json_decode($stdin, true); |
| 15 | } elseif ($argc == 3) { |
| 16 | $subjects[] = [ |
| 17 | 'friendly_name' => $argv[1], |
| 18 | 'calendar_name' => $argv[2] |
| 19 | ]; |
| 20 | } else { |
| 21 | echo "Usage: php add_subjects.php friendly_name calendar_name\n"; |
| 22 | echo "php add_subjects.json --stdin < subjects.json\n"; |
| 23 | exit(); |
| 24 | } |
| 25 | |
| 26 | $con->beginTransaction(); |
| 27 | |
| 28 | $query = $con->prepare('INSERT INTO subjects (friendly_name, calendar_name) VALUES (:friendly_name, :calendar_name)'); |
| 29 | foreach ($subjects as $subject) { |
| 30 | if (!isset($subject['friendly_name']) || !isset($subject['calendar_name']) || empty($subject['friendly_name']) || empty($subject['calendar_name'])) { |
| 31 | $con->rollback(); |
| 32 | echo "The JSON file passed is malformed. It should be an array consisting of objects which have non-empty 'friendly_name' and 'calendar_name' properties.\n"; |
| 33 | exit(); |
| 34 | } |
| 35 | |
| 36 | if (!$query->execute($subject)) { |
| 37 | echo "An error occurred while adding the subject '".$subject['friendly_name']."' to the database. This doesn't affect the other subjects.\n"; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | $con->commit(); |
| 42 | |
| 43 | echo "Success.\n"; |