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 * Extension to show an error message if the selected predictor is not available.
19 *
20 * @package   core_analytics
21 * @copyright 2017 David Monllao {@link http://www.davidmonllao.com}
22 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_analytics;
26
27defined('MOODLE_INTERNAL') || die();
28
29require_once(__DIR__ . '/../../lib/adminlib.php');
30
31/**
32 * Extension to show an error message if the selected predictor is not available.
33 *
34 * @package   core_analytics
35 * @copyright 2017 David Monllao {@link http://www.davidmonllao.com}
36 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 */
38class admin_setting_predictor extends \admin_setting_configselect {
39
40    /**
41     * Save a setting
42     *
43     * @param string $data
44     * @return string empty of error string
45     */
46    public function write_setting($data) {
47        if (!$this->load_choices() or empty($this->choices)) {
48            return '';
49        }
50        if (!array_key_exists($data, $this->choices)) {
51            return '';
52        }
53
54        // Calling it here without checking if it is ready because we check it below and show it as a controlled case.
55        $selectedprocessor = \core_analytics\manager::get_predictions_processor($data, false);
56        $isready = $selectedprocessor->is_ready();
57        if ($isready !== true) {
58            return get_string('errorprocessornotready', 'analytics', $isready);
59        }
60
61        $currentvalue = get_config('analytics', 'predictionsprocessor');
62        if (!empty($currentvalue) && $currentvalue != str_replace('\\\\', '\\', $data)) {
63            // Clear all models data.
64            $models = \core_analytics\manager::get_all_models();
65            foreach ($models as $model) {
66                $model->clear();
67            }
68        }
69
70        return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
71    }
72}
73