MDL-59638 analytics: Advance time splitting start instead of delay end
[moodle.git] / analytics / classes / local / time_splitting / equal_parts.php
CommitLineData
fbc18acd
DM
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 * X parts time splitting method.
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\local\time_splitting;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * X parts time splitting method.
31 *
32 * @package core_analytics
33 * @copyright 2017 David Monllao {@link http://www.davidmonllao.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36abstract class equal_parts extends base {
37
38 /**
39 * Returns the number of parts the analyser duration should be split in.
40 *
41 * @return int
42 */
43 abstract protected function get_number_parts();
44
45 /**
46 * Splits the analysable duration in X equal parts from the start to the end.
47 *
48 * @return array
49 */
50 protected function define_ranges() {
51
52 $nparts = $this->get_number_parts();
53
54 $rangeduration = intval(floor(($this->analysable->get_end() - $this->analysable->get_start()) / $nparts));
55
56 $ranges = array();
57 for ($i = 0; $i < $nparts; $i++) {
58 $start = $this->analysable->get_start() + ($rangeduration * $i);
59 $end = $this->analysable->get_start() + ($rangeduration * ($i + 1));
60
61 // Check the end of the previous time range.
62 if ($i > 0 && $start === $ranges[$i - 1]['end']) {
8f5a52b4
DM
63 // We add 1 second so each timestamp only belongs to 1 range.
64 $start = $start + 1;
fbc18acd
DM
65 }
66
67 if ($i === ($nparts - 1)) {
68 // Better to use the end for the last one as we are using floor above.
69 $end = $this->analysable->get_end();
70 }
71 $ranges[$i] = array(
72 'start' => $start,
73 'end' => $end,
74 'time' => $end
75 );
76 }
77
78 return $ranges;
79 }
80}