1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * JSON data format writer
19 *
20 * @package    dataformat_json
21 * @copyright  2016 Brendan Heywood (brendan@catalyst-au.net)
22 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace dataformat_json;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * JSON data format writer
31 *
32 * @package    dataformat_json
33 * @copyright  2016 Brendan Heywood (brendan@catalyst-au.net)
34 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class writer extends \core\dataformat\base {
37
38    /** @var $mimetype */
39    public $mimetype = "application/json";
40
41    /** @var $extension */
42    public $extension = ".json";
43
44    /** @var $sheetstarted */
45    public $sheetstarted = false;
46
47    /** @var $sheetdatadded */
48    public $sheetdatadded = false;
49
50    /**
51     * Write the start of the file.
52     */
53    public function start_output() {
54        echo "[";
55    }
56
57    /**
58     * Write the start of the sheet we will be adding data to.
59     *
60     * @param array $columns
61     */
62    public function start_sheet($columns) {
63        if ($this->sheetstarted) {
64            echo ",";
65        } else {
66            $this->sheetstarted = true;
67        }
68        $this->sheetdatadded = false;
69        echo "[";
70    }
71
72    /**
73     * Write a single record
74     *
75     * @param array $record
76     * @param int $rownum
77     */
78    public function write_record($record, $rownum) {
79        if ($this->sheetdatadded) {
80            echo ",";
81        }
82
83        echo json_encode($this->format_record($record), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
84
85        $this->sheetdatadded = true;
86    }
87
88    /**
89     * Write the end of the sheet containing the data.
90     *
91     * @param array $columns
92     */
93    public function close_sheet($columns) {
94        echo "]";
95    }
96
97    /**
98     * Write the end of the file.
99     */
100    public function close_output() {
101        echo "]";
102    }
103}
104