diff --git a/block_coursenotes.php b/block_coursenotes.php index f3a0ee8..40bac2a 100644 --- a/block_coursenotes.php +++ b/block_coursenotes.php @@ -41,7 +41,7 @@ public function init(): void { * */ public function get_content(): object { - global $USER, $DB, $COURSE, $OUTPUT; + global $COURSE, $OUTPUT; if ($this->content !== null) { return $this->content; @@ -57,15 +57,10 @@ public function get_content(): object { 'courseid' => $COURSE->id, ]; - // Fetch notes from the database. - $conditions = [ - 'userid' => $USER->id, - 'courseid' => $COURSE->id, - ]; - $notes = $DB->get_records('block_coursenotes', $conditions, 'timecreated DESC', '*', 0, 1); + // Fetch the latest coursenote. + $latestnote = helper::fetch_latest_coursenote_for_user(); - if ($notes) { - $latestnote = reset($notes); // Get the first (latest) record. + if ($latestnote) { $data['coursenote'] = $latestnote->coursenote; } diff --git a/classes/helper.php b/classes/helper.php index 4273f3e..c93b6aa 100644 --- a/classes/helper.php +++ b/classes/helper.php @@ -98,4 +98,38 @@ public static function isduplicate($params, $notes): bool { } return false; } + + /** + * Fetches the latest course note for a user and course. + * + * @return mixed The latest course note or false if none found. + */ + public static function fetch_latest_coursenote_for_user(): mixed { + global $DB, $COURSE, $USER; + + $conditions = [ + 'userid' => $USER->id, + 'courseid' => $COURSE->id, + ]; + + $notes = $DB->get_records('block_coursenotes', $conditions, 'timecreated DESC', '*', 0, 1); + + return $notes ? reset($notes) : false; + } + + /** + * Fetches all notes for a user and course. + * + * @return array An array of course notes. + */ + public static function fetch_all_coursenotes_for_user(): array { + global $DB, $COURSE, $USER; + + $conditions = [ + 'userid' => $USER->id, + 'courseid' => $COURSE->id, + ]; + + return $DB->get_records('block_coursenotes', $conditions, 'timecreated ASC'); + } }