diff --git a/classes/edit_form.php b/classes/edit_form.php index 481e498..7f607a2 100644 --- a/classes/edit_form.php +++ b/classes/edit_form.php @@ -58,15 +58,15 @@ public function definition() { $mform->addHelpButton('workflowname', 'workflowname', 'tool_trigger'); // Workflow description. - $editoroptions = array( + $editoroptions = [ 'subdirs' => 0, 'maxbytes' => 0, 'maxfiles' => 0, 'changeformat' => 0, 'context' => \context_system::instance(), 'noclean' => 0, - 'trusttext' => 0 - ); + 'trusttext' => 0, + ]; $mform->addElement('editor', 'workflowdescription', get_string ('workflowdescription', 'tool_trigger'), $editoroptions); $mform->setType('workflowdescription', PARAM_RAW_TRIMMED); $mform->addHelpButton('workflowdescription', 'workflowdescription', 'tool_trigger'); @@ -95,7 +95,7 @@ public function definition() { $mform->addElement('advcheckbox', 'workflowactive', get_string ('workflowactive', 'tool_trigger'), - 'Enable', array(), array(0, 1)); + 'Enable', [], [0, 1]); $mform->setType('workflowactive', PARAM_INT); $mform->addHelpButton('workflowactive', 'workflowactive', 'tool_trigger'); $mform->setDefault('workflowactive', 1); @@ -104,7 +104,7 @@ public function definition() { $mform->addElement('advcheckbox', 'workflowrealtime', get_string ('workflowrealtime', 'tool_trigger'), - 'Enable', array(), array(0, 1)); + 'Enable', [], [0, 1]); $mform->setType('workflowrealtime', PARAM_INT); $mform->addHelpButton('workflowrealtime', 'workflowrealtime', 'tool_trigger'); $mform->setDefault('workflowrealtime', 0); @@ -113,7 +113,7 @@ public function definition() { $mform->addElement('advcheckbox', 'workflowdebug', get_string('workflowdebug', 'tool_trigger'), - 'Enable', array(), array(0, 1)); + 'Enable', [], [0, 1]); $mform->setType('workflowdebug', PARAM_INT); $mform->addHelpButton('workflowdebug', 'workflowdebug', 'tool_trigger'); $mform->setDefault('workflowdebug', 0); diff --git a/classes/event_processor.php b/classes/event_processor.php index ea5ed36..bba6aab 100644 --- a/classes/event_processor.php +++ b/classes/event_processor.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Process trigger system events. - * - * @package tool_trigger - * @copyright Matt Porritt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; use tool_trigger\helper\processor_helper; @@ -138,7 +130,7 @@ protected function is_event_ignored(\core\event\base $event) { // If we do not have the triggers in the cache then return them from the DB. if ($sitesubscriptions === false) { // Set the array for the cache. - $sitesubscriptions = array(); + $sitesubscriptions = []; if ($subscriptions = $DB->get_records_sql($sql)) { foreach ($subscriptions as $subscription) { $sitesubscriptions[$subscription->event] = true; @@ -198,6 +190,21 @@ private function process_realtime_workflows($evententry) { } } + /** + * Processes a real-time workflow by executing its steps immediately in response to an event. + * + * This method: + * - Marks the workflow as triggered and updates its record in the database. + * - Records the workflow trigger in history. + * - Restores the triggering event from stored data. + * - Iterates through workflow steps in order, executing each step and recording results. + * - Stops execution early if a step fails or throws an error. + * - Handles transactional safety for each step to prevent partial writes. + * - If an error occurs, records the failed step and queues the workflow for retry via cron. + * + * @param \stdClass $workflow The workflow object containing workflow metadata. + * @param \stdClass $evententry The event entry object representing the trigger event data. + */ private function process_realtime_workflow($workflow, $evententry) { global $DB; @@ -292,20 +299,20 @@ public static function record_workflow_trigger(int $workflowid, $event, int $att // Get new run number. $sqlfrag = "SELECT MAX(number) FROM {tool_trigger_workflow_hist} WHERE workflowid = :wfid"; - $runnumber = $DB->get_field_sql($sqlfrag, array('wfid' => $workflowid)) + 1; + $runnumber = $DB->get_field_sql($sqlfrag, ['wfid' => $workflowid]) + 1; // Encode event data as JSON. $eventdata = json_encode($event); - $id = $DB->insert_record('tool_trigger_workflow_hist', array( + $id = $DB->insert_record('tool_trigger_workflow_hist', [ 'workflowid' => $workflowid, 'number' => $runnumber, 'timecreated' => time(), 'event' => $eventdata, 'eventid' => $event->id, 'userid' => $event->userid, - 'attemptnum' => $attemptnum - ), true); + 'attemptnum' => $attemptnum, + ], true); // Return the id for use in other tables. return $id; @@ -488,7 +495,7 @@ public static function execute_next_step_historic(int $stepid, int $origrun = 0, 'workflow' => $step->workflowid, 'run' => $origrun, 'number' => $step->number + 1, - 'previd' => $step->id + 'previd' => $step->id, ]; $nextstep = $DB->get_record_sql($nextstepsql, $params); @@ -529,7 +536,7 @@ public static function execute_next_step_historic(int $stepid, int $origrun = 0, 'workflow' => $nextstep->workflowid, 'run' => $runid, 'stepname' => $nextstep->name, - 'previd' => $previd + 'previd' => $previd, ]); // Return the ID just executed for use in moving through the historic chain. @@ -559,7 +566,7 @@ public static function execute_next_step_current(int $stepid) { $nextstep = $DB->get_record_sql($nextstepsql, [ 'workflow' => $step->workflowid, 'run' => $step->runid, - 'number' => $step->number + 1 + 'number' => $step->number + 1, ]); // If no nextstep is found, jump out. @@ -582,7 +589,7 @@ public static function execute_next_step_current(int $stepid) { $newstepid = $DB->get_field_sql($newstepsql, [ 'workflow' => $nextstep->workflowid, 'run' => $nextstep->runid, - 'stepname' => $nextstep->name + 'stepname' => $nextstep->name, ]); return $newstepid; } @@ -619,7 +626,7 @@ public static function execute_step_and_continue_historic(int $stepid, bool $com $newstep = $DB->get_record_sql($newstepsql, [ 'workflow' => $step->workflowid, 'run' => $newrunid, - 'stepname' => $step->name + 'stepname' => $step->name, ]); // Now execute the next step in the historic chain. @@ -660,7 +667,7 @@ public static function execute_step_and_continue_current(int $stepid, bool $comp $newstep = $DB->get_record_sql($newstepsql, [ 'workflow' => $step->workflowid, 'run' => $step->runid, - 'stepname' => $step->name + 'stepname' => $step->name, ]); // Now execute the next step, based on the step we just created. @@ -809,7 +816,7 @@ public static function record_cancelled_workflow($workflowid, $event, $runid = n // Get new run number. $sqlfrag = "SELECT MAX(number) FROM {tool_trigger_workflow_hist} WHERE workflowid = :wfid"; - $runnumber = $DB->get_field_sql($sqlfrag, array('wfid' => $workflowid)) + 1; + $runnumber = $DB->get_field_sql($sqlfrag, ['wfid' => $workflowid]) + 1; // Encode event data as JSON. $eventdata = json_encode($event); @@ -822,7 +829,7 @@ public static function record_cancelled_workflow($workflowid, $event, $runid = n 'timecreated' => time(), 'event' => $eventdata, 'eventid' => $event->id, - 'failedstep' => $status + 'failedstep' => $status, ]; if (empty($runid)) { diff --git a/classes/helper/datafield_manager.php b/classes/helper/datafield_manager.php index 71fa316..cec7533 100644 --- a/classes/helper/datafield_manager.php +++ b/classes/helper/datafield_manager.php @@ -14,15 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * A lookup step that takes a user's ID and adds standard data about the user. - * - * @package tool_trigger - * @author Aaron Wells - * @copyright Catalyst IT, 2018 - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\helper; /** @@ -36,6 +27,10 @@ */ trait datafield_manager { + /** + * Data fields. + * @var array + */ protected $datafields = []; /** @var string regex to determine data fields - should ideally be readonly */ diff --git a/classes/helper/processor_helper.php b/classes/helper/processor_helper.php index 6b4cf0f..a93bc31 100644 --- a/classes/helper/processor_helper.php +++ b/classes/helper/processor_helper.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger\helper; + /** * trait to help in processing events. * @@ -22,9 +24,6 @@ * @copyright 2019 Catalyst IT * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger\helper; - trait processor_helper { /** @@ -37,11 +36,11 @@ public function restore_event(\stdClass $data) { if (empty((array)$data)) { return null; } - $extra = array('origin' => $data->origin, 'ip' => $data->ip, 'realuserid' => $data->realuserid); + $extra = ['origin' => $data->origin, 'ip' => $data->ip, 'realuserid' => $data->realuserid]; $data = (array)$data; $data['other'] = unserialize($data['other']); if ($data['other'] === false) { - $data['other'] = array(); + $data['other'] = []; } // Insert eventid into other data. diff --git a/classes/import_form.php b/classes/import_form.php index 1fd5903..f93c7b3 100644 --- a/classes/import_form.php +++ b/classes/import_form.php @@ -58,7 +58,7 @@ public function definition() { // Workflow file. $mform->addElement('filepicker', 'userfile', get_string('workflowfile', 'tool_trigger'), null, - array('maxbytes' => 256000, 'accepted_types' => '.json')); + ['maxbytes' => 256000, 'accepted_types' => '.json']); $mform->addRule('userfile', get_string('required'), 'required'); } @@ -73,7 +73,7 @@ public function definition() { public function validation($data, $files) { global $USER; - $validationerrors = array(); + $validationerrors = []; // Get the file from the filestystem. $files will always be empty. $fs = get_file_storage(); diff --git a/classes/json/json_export.php b/classes/json/json_export.php index 1971fc7..c38c077 100644 --- a/classes/json/json_export.php +++ b/classes/json/json_export.php @@ -132,7 +132,7 @@ private function get_workflow_json($workflowrecord) { * * @param string $workflowjson */ - private function print_json_data ($workflowjson) { + private function print_json_data($workflowjson) { echo $workflowjson; } diff --git a/classes/learn_process.php b/classes/learn_process.php index 9d11b9a..7d38282 100644 --- a/classes/learn_process.php +++ b/classes/learn_process.php @@ -37,7 +37,7 @@ class learn_process { * * @var array */ - private $typearray = array(); + private $typearray = []; /** * Get a list of all the distinct events names in the learning table. @@ -64,7 +64,7 @@ private function get_learnt_events() { private function get_learnt_records($learntevent) { global $DB; - $learntrecords = $DB->get_recordset('tool_trigger_learn_events', array('eventname' => $learntevent)); + $learntrecords = $DB->get_recordset('tool_trigger_learn_events', ['eventname' => $learntevent]); return $learntrecords; } @@ -161,7 +161,7 @@ public function store_json_fields($learntevent, $jsonfields) { $transaction = $DB->start_delegated_transaction(); // Check for existing record in DB. - $exists = $DB->get_record('tool_trigger_event_fields', array('eventname' => $learntevent), '*', IGNORE_MISSING); + $exists = $DB->get_record('tool_trigger_event_fields', ['eventname' => $learntevent], '*', IGNORE_MISSING); if ($exists) { // If record exists update. $record->id = $exists->id; @@ -180,7 +180,7 @@ public function store_json_fields($learntevent, $jsonfields) { /** * Process the learnt events and extract the field names. */ - public function process () { + public function process() { global $DB; // Get a list of the event types from the learn table. @@ -188,16 +188,16 @@ public function process () { // For each type of event get all the entries for that event from the learn table. foreach ($learntevents as $learntevent) { - $processedrecords = array(); + $processedrecords = []; $learntrecords = $this->get_learnt_records($learntevent); foreach ($learntrecords as $record) { - $this->typearray = array(); // Reset typearray before calling convert_record_type. + $this->typearray = []; // Reset typearray before calling convert_record_type. // Convert each record into an array where key is field name and value is type. $processedrecords[] = $this->convert_record_type($record, false); // Remove learnt event from DB. - $DB->delete_records('tool_trigger_learn_events', array('id' => $record->id)); + $DB->delete_records('tool_trigger_learn_events', ['id' => $record->id]); } $learntrecords->close(); // Don't forget to close the recordset! @@ -239,7 +239,7 @@ public function get_event_fields_json($eventname) { global $DB; $jsonfields = $DB->get_record( 'tool_trigger_event_fields', - array('eventname' => $eventname), 'jsonfields', IGNORE_MISSING); + ['eventname' => $eventname], 'jsonfields', IGNORE_MISSING); return $jsonfields; } @@ -252,30 +252,30 @@ public function get_event_fields_json($eventname) { */ public function get_event_fields_with_type($eventname) { global $DB; - $fieldarray = array(); + $fieldarray = []; $jsonfields = $DB->get_record( 'tool_trigger_event_fields', - array('eventname' => $eventname), 'jsonfields', IGNORE_MISSING); + ['eventname' => $eventname], 'jsonfields', IGNORE_MISSING); if ($jsonfields) { $fields = json_decode($jsonfields->jsonfields, true); foreach ($fields as $field => $type) { - $fieldarray[] = array( + $fieldarray[] = [ 'field' => $field, - 'type' => $type - ); + 'type' => $type, + ]; } } - $fieldarray[] = array( + $fieldarray[] = [ 'field' => 'wwwroot', - 'type' => 'string' - ); - $fieldarray[] = array( + 'type' => 'string', + ]; + $fieldarray[] = [ 'field' => 'wwwroot_domain', - 'type' => 'string' - ); + 'type' => 'string', + ]; return $fieldarray; } diff --git a/classes/output/manageworkflows/renderable.php b/classes/output/manageworkflows/renderable.php index 72d3bc8..1a57c97 100644 --- a/classes/output/manageworkflows/renderable.php +++ b/classes/output/manageworkflows/renderable.php @@ -59,7 +59,7 @@ public function __construct($uniqueid, \moodle_url $url, $perpage = 100) { $this->set_attribute('id', 'tooltriggerrules_table'); $this->set_attribute('class', 'tooltrigger managerules generaltable generalbox'); - $this->define_columns(array( + $this->define_columns([ 'name', 'description', 'eventname', @@ -68,9 +68,9 @@ public function __construct($uniqueid, \moodle_url $url, $perpage = 100) { 'numsteps', 'lasttriggered', 'triggerhistory', - 'manage' - )); - $this->define_headers(array( + 'manage', + ]); + $this->define_headers([ get_string('name', 'tool_trigger'), get_string('description', 'tool_trigger'), get_string('event', 'tool_trigger'), @@ -80,7 +80,7 @@ public function __construct($uniqueid, \moodle_url $url, $perpage = 100) { get_string('lasttriggered', 'tool_trigger'), get_string('triggerhistory', 'tool_trigger'), get_string('manage', 'tool_trigger'), - ) + ] ); $this->pagesize = $perpage; $systemcontext = \context_system::instance(); @@ -101,7 +101,7 @@ public function __construct($uniqueid, \moodle_url $url, $perpage = 100) { public function col_name(\tool_trigger\workflow $workflow) { global $OUTPUT; - $editurl = new \moodle_url('/admin/tool/trigger/edit.php', array('workflowid' => $workflow->id)); + $editurl = new \moodle_url('/admin/tool/trigger/edit.php', ['workflowid' => $workflow->id]); return \html_writer::link($editurl, $workflow->get_name($this->context)); } @@ -125,6 +125,8 @@ public function col_lasttriggered(\tool_trigger\workflow $workflow) { if (!empty($workflow->lasttriggered)) { return userdate($workflow->lasttriggered); } + + return '-'; } /** @@ -141,8 +143,14 @@ public function col_eventname(\tool_trigger\workflow $workflow) { } } + /** + * Generate content for triggerhistor column. + * + * @param \tool_trigger\workflow $workflow rule object + * @return string html used to display the column field. + */ public function col_triggerhistory(\tool_trigger\workflow $workflow) { - $url = new \moodle_url('/admin/tool/trigger/history.php', array('workflow' => $workflow->id)); + $url = new \moodle_url('/admin/tool/trigger/history.php', ['workflow' => $workflow->id]); return \html_writer::link($url, get_string('workflowviewhistory', 'tool_trigger')); } @@ -157,29 +165,35 @@ public function col_manage(\tool_trigger\workflow $workflow) { $manage = ''; - $editurl = new \moodle_url('/admin/tool/trigger/edit.php', array('workflowid' => $workflow->id)); + $editurl = new \moodle_url('/admin/tool/trigger/edit.php', ['workflowid' => $workflow->id]); $icon = $OUTPUT->render(new \pix_icon('t/edit', get_string('editrule', 'tool_trigger'))); - $manage .= \html_writer::link($editurl, $icon, array('class' => 'action-icon')); + $manage .= \html_writer::link($editurl, $icon, ['class' => 'action-icon']); // The user should always be able to copy the rule if they are able to view the page. $copyurl = new \moodle_url('/admin/tool/trigger/manageworkflow.php', - array('workflowid' => $workflow->id, 'action' => 'copy', 'sesskey' => sesskey())); + ['workflowid' => $workflow->id, 'action' => 'copy', 'sesskey' => sesskey()]); $icon = $OUTPUT->render(new \pix_icon('t/copy', get_string('duplicaterule', 'tool_trigger'))); - $manage .= \html_writer::link($copyurl, $icon, array('class' => 'action-icon')); + $manage .= \html_writer::link($copyurl, $icon, ['class' => 'action-icon']); - $deleteurl = new \moodle_url('/admin/tool/trigger/manageworkflow.php', array('workflowid' => $workflow->id, - 'action' => 'delete', 'sesskey' => sesskey())); + $deleteurl = new \moodle_url('/admin/tool/trigger/manageworkflow.php', ['workflowid' => $workflow->id, + 'action' => 'delete', 'sesskey' => sesskey()]); $icon = $OUTPUT->render(new \pix_icon('t/delete', get_string('deleterule', 'tool_trigger'))); - $manage .= \html_writer::link($deleteurl, $icon, array('class' => 'action-icon')); + $manage .= \html_writer::link($deleteurl, $icon, ['class' => 'action-icon']); - $downloadurl = new \moodle_url('/admin/tool/trigger/export.php', array('workflowid' => $workflow->id, - 'action' => 'download', 'sesskey' => sesskey())); + $downloadurl = new \moodle_url('/admin/tool/trigger/export.php', ['workflowid' => $workflow->id, + 'action' => 'download', 'sesskey' => sesskey()]); $icon = $OUTPUT->render(new \pix_icon('t/download', get_string('downloadrule', 'tool_trigger'))); - $manage .= \html_writer::link($downloadurl, $icon, array('class' => 'action-icon')); + $manage .= \html_writer::link($downloadurl, $icon, ['class' => 'action-icon']); return $manage; } + /** + * Generate content for active column. + * + * @param \tool_trigger\workflow $workflow rule object + * @return string html used to display the manage column field. + */ public function col_active($row) { if ($row->active) { return get_string('active'); diff --git a/classes/output/manageworkflows/renderer.php b/classes/output/manageworkflows/renderer.php index 190a149..f0fa66e 100644 --- a/classes/output/manageworkflows/renderer.php +++ b/classes/output/manageworkflows/renderer.php @@ -75,7 +75,7 @@ protected function render_add_button() { global $CFG; $button = \html_writer::tag('button', get_string('addworkflow', 'tool_trigger'), ['class' => 'btn btn-primary']); - $addurl = new \moodle_url($CFG->wwwroot. '/admin/tool/trigger/edit.php', array('workflowid' => 0)); + $addurl = new \moodle_url($CFG->wwwroot. '/admin/tool/trigger/edit.php', ['workflowid' => 0]); return \html_writer::link($addurl, $button); } @@ -131,7 +131,7 @@ public function render_workflow_steps($stepdatajson) { foreach ($stepdata as $step) { $row = [ 'name' => $step['name'], - 'steporder' => $step['steporder'] + 'steporder' => $step['steporder'], ]; if ($wfm->validate_step_class($step['stepclass'])) { $row['typedesc'] = $step['stepclass']::get_step_type_desc(); diff --git a/classes/output/workflowhistory/filter_form.php b/classes/output/workflowhistory/filter_form.php index fb85ed5..6f9f876 100644 --- a/classes/output/workflowhistory/filter_form.php +++ b/classes/output/workflowhistory/filter_form.php @@ -14,15 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Filter form class for workflowhistory. - * - * @package tool_trigger - * @copyright Catalyst IT, 2021 - * @author Nicholas Hoobin - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\output\workflowhistory; defined('MOODLE_INTERNAL') || die(); @@ -39,6 +30,9 @@ */ class filter_form extends \moodleform { + /** + * Form definition. + */ public function definition() { $mform = $this->_form; diff --git a/classes/output/workflowhistory/renderer.php b/classes/output/workflowhistory/renderer.php index 8455a14..ac26a54 100644 --- a/classes/output/workflowhistory/renderer.php +++ b/classes/output/workflowhistory/renderer.php @@ -56,7 +56,7 @@ public function render_runhistory_table($workflowid, $run, $download = null) { $sqlwhere = 'workflowid = :workflow AND runid = :run'; $sqlparams = [ 'workflow' => $workflowid, - 'run' => $run + 'run' => $run, ]; $renderable->set_sql($sqlfields, $sqlfrom, $sqlwhere, $sqlparams); @@ -146,6 +146,19 @@ public function render_workflowhistory_table($workflowid, $searchparams = [], $d $renderable->out($renderable->pagesize, false); } + /** + * Generates the HTML for the "Step Actions" button group. + * + * Produces a primary "View step info" button and a dropdown menu of actions + * for both current and historic workflow step executions. This includes + * rerunning the step, rerunning the step and following steps, rerunning until + * the workflow is finished, and executing the next step directly. + * + * The available actions are grouped into "current" and "historic" sections. + * + * @param \stdClass $step Step record containing step information. + * @return string HTML markup for the step actions button group. + */ public function step_actions_button($step) { $workflow = required_param('workflow', PARAM_INT); $run = required_param('run', PARAM_INT); @@ -223,9 +236,24 @@ public function step_actions_button($step) { return $btn; } + /** + * Generates the HTML for the "Run Actions" button group. + * + * Produces a primary "View detailed run" button and a dropdown menu of actions + * to rerun the workflow either for the current run state or from historic state. + * If the user has the appropriate capability, an option to download run details + * is also provided. + * + * If $statusonly is true, only the "View detailed run" button is displayed. + * + * @param \stdClass $run Run record containing workflow run information. + * @param bool $statusonly Whether to show only the status (no dropdown actions). + * @param array $searchparams Additional search parameters to include in URLs. + * @return string HTML markup for the run actions button group. + */ public function run_actions_button($run, $statusonly = false, $searchparams = []) { $btn = ''; - $viewurl = new \moodle_url('/admin/tool/trigger/history.php', array('run' => $run->id, 'workflow' => $run->workflowid)); + $viewurl = new \moodle_url('/admin/tool/trigger/history.php', ['run' => $run->id, 'workflow' => $run->workflowid]); $viewbtn = \html_writer::link($viewurl, get_string('viewdetailedrun', 'tool_trigger'), ['class' => 'btn btn-primary']); // For deferred and cancelled runs, show only details. diff --git a/classes/output/workflowhistory/run.php b/classes/output/workflowhistory/run.php index 2cf6833..70fab65 100644 --- a/classes/output/workflowhistory/run.php +++ b/classes/output/workflowhistory/run.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Renderable class for run history page. - * - * @package tool_trigger - * @copyright Peter Burnett - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\output\workflowhistory; use html_writer; @@ -31,6 +23,13 @@ require_once($CFG->libdir . '/tablelib.php'); +/** + * Renderable class for run history page. + * + * @package tool_trigger + * @copyright Peter Burnett + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ class runhistory_renderable extends \table_sql implements \renderable { /** * @var \context_course|\context_system context of the page to be rendered. @@ -59,24 +58,24 @@ public function __construct($uniqueid, \moodle_url $url, $perpage = 100) { $this->set_attribute('id', 'tooltriggerrunhistory_table'); $this->set_attribute('class', 'tooltrigger runhistory generaltable generalbox'); - $this->define_columns(array( + $this->define_columns([ 'step', 'id', 'name', 'type', 'executed', 'prevstep', - 'actions' - )); - $this->define_headers(array( + 'actions', + ]); + $this->define_headers([ get_string('stepnumber', 'tool_trigger'), get_string('stepid', 'tool_trigger'), get_string('name'), get_string('type', 'search'), get_string('timeexecuted', 'tool_trigger'), get_string('prevstep', 'tool_trigger'), - get_string('actions') - ) + get_string('actions'), + ] ); $this->pagesize = $perpage; $systemcontext = \context_system::instance(); @@ -89,28 +88,70 @@ public function __construct($uniqueid, \moodle_url $url, $perpage = 100) { $this->stepcounter = 1; } + /** + * Column renderer for step number. + * + * Adds 1 to the stored step number for human readability. + * + * @param \stdClass $step Step record. + * @return int Human-readable step number. + */ public function col_step($step) { // Add 1 to be human readable. return $step->number + 1; } + /** + * Column renderer for step ID. + * + * @param \stdClass $step Step record. + * @return int Step ID. + */ public function col_id($step) { return $step->id; } + /** + * Column renderer for step name. + * + * @param \stdClass $step Step record. + * @return string Step name. + */ public function col_name($step) { return $step->name; } + /** + * Column renderer for step type. + * + * @param \stdClass $step Step record. + * @return string Step type. + */ public function col_type($step) { return $step->type; } + /** + * Column renderer for executed time. + * + * Formats the timestamp using the short date/time format. + * + * @param \stdClass $step Step record. + * @return string Formatted execution date/time. + */ public function col_executed($step) { $format = get_string('strftimedatetimeshort', 'langconfig'); return userdate($step->executed, $format); } + /** + * Column renderer for previous step ID. + * + * Returns the previous step ID if available, or "none" otherwise. + * + * @param \stdClass $step Step record. + * @return string|int Previous step ID or "none". + */ public function col_prevstep($step) { if (!empty($step->prevstepid)) { return $step->prevstepid; @@ -119,6 +160,15 @@ public function col_prevstep($step) { } } + /** + * Column renderer for step actions. + * + * Uses the workflow history renderer to produce the actions + * available for the given step. + * + * @param \stdClass $step Step record. + * @return string HTML for step action buttons. + */ public function col_actions($step) { global $PAGE; diff --git a/classes/output/workflowhistory/workflow.php b/classes/output/workflowhistory/workflow.php index 075da94..bb99c4e 100644 --- a/classes/output/workflowhistory/workflow.php +++ b/classes/output/workflowhistory/workflow.php @@ -14,6 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger\output\workflowhistory; + +defined('MOODLE_INTERNAL') || die; + +require_once($CFG->libdir . '/tablelib.php'); + + /** * Renderable class for workflow history page. * @@ -21,13 +28,6 @@ * @copyright Peter Burnett * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger\output\workflowhistory; - -defined('MOODLE_INTERNAL') || die; - -require_once($CFG->libdir . '/tablelib.php'); - class workflowhistory_renderable extends \table_sql implements \renderable { /** * @var \context_course|\context_system context of the page to be rendered. @@ -101,22 +101,55 @@ public function __construct($uniqueid, \moodle_url $url, $searchparams = [], $do } } + /** + * Column renderer for run ID. + * + * @param \stdClass $run Run record. + * @return int Run ID. + */ public function col_id($run) { return $run->id; } + /** + * Column renderer for run number. + * + * @param \stdClass $run Run record. + * @return int Run number. + */ public function col_number($run) { return $run->number; } + /** + * Column renderer for event ID. + * + * @param \stdClass $run Run record. + * @return int Event ID. + */ public function col_eventid($run) { return $run->eventid; } + /** + * Column renderer for the username. + * + * @param \stdClass $run Run record (must contain user fields for fullname()). + * @return string Full name of the user. + */ public function col_username($run) { return fullname($run); } + /** + * Column renderer for event description. + * + * Decodes the stored event JSON, restores the event object, + * and retrieves its human-readable description. + * + * @param \stdClass $run Run record. + * @return string Event description. + */ public function col_description($run) { // Get the event class from info. $evententry = json_decode($run->event); @@ -126,11 +159,30 @@ public function col_description($run) { return $eventobject->get_description(); } + /** + * Column renderer for run time. + * + * @param \stdClass $run Run record. + * @return string Formatted date/time string. + */ public function col_time($run) { $format = get_string('strftimedatetimeshort', 'langconfig'); return userdate($run->timecreated, $format); } + /** + * Column renderer for run status. + * + * Produces a status badge (or plain text when downloading) + * indicating the outcome of the run: + * - Warning badge with retry info if error step encountered. + * - Info badge for cancelled or deferred steps. + * - Danger badge for failed steps. + * - Success badge for passed runs. + * + * @param \stdClass $run Run record. + * @return string HTML for badge or plain text for downloads. + */ public function col_runstatus($run) { global $DB; @@ -173,6 +225,15 @@ public function col_runstatus($run) { } } + /** + * Column renderer for available actions on a run. + * + * Uses the workflow history renderer to produce action buttons. + * Status-only actions are shown if the run is cancelled or deferred. + * + * @param \stdClass $run Run record. + * @return string HTML for action buttons. + */ public function col_actions($run) { global $PAGE; @@ -180,7 +241,7 @@ public function col_actions($run) { $statusonly = !empty($run->failedstep) && ((int) $run->failedstep === \tool_trigger\task\process_workflows::STATUS_CANCELLED || - (int) $run->failedstep === \tool_trigger\task\process_workflows::STATUS_DEFERRED); + (int) $run->failedstep === \tool_trigger\task\process_workflows::STATUS_DEFERRED); return $renderer->run_actions_button($run, $statusonly, $this->searchparams); } diff --git a/classes/privacy/provider.php b/classes/privacy/provider.php index fcaf22a..7445b1c 100644 --- a/classes/privacy/provider.php +++ b/classes/privacy/provider.php @@ -27,8 +27,8 @@ use core_privacy\local\metadata\collection; use core_privacy\local\request\contextlist; use core_privacy\local\request\approved_contextlist; -use \core_privacy\local\request\approved_userlist; -use \core_privacy\local\request\userlist; +use core_privacy\local\request\approved_userlist; +use core_privacy\local\request\userlist; /** * Provider for the tool_trigger plugin. @@ -58,7 +58,7 @@ class provider implements * @param collection $collection The initialised collection to add items to. * @return collection A listing of user data stored through this system. */ - public static function get_metadata(collection $collection) : collection { + public static function get_metadata(collection $collection): collection { $wfm = new \tool_trigger\workflow_manager(); $steplist = $wfm->get_step_class_names(); @@ -141,7 +141,7 @@ public static function get_metadata(collection $collection) : collection { * @param int $userid The user to search. * @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin. */ - public static function get_contexts_for_userid(int $userid) : contextlist { + public static function get_contexts_for_userid(int $userid): contextlist { $contextlist = new \core_privacy\local\request\contextlist(); $sql = " diff --git a/classes/steps/actions/assign_cohort_action_step.php b/classes/steps/actions/assign_cohort_action_step.php index 7097870..276ff2d 100644 --- a/classes/steps/actions/assign_cohort_action_step.php +++ b/classes/steps/actions/assign_cohort_action_step.php @@ -14,6 +14,11 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger\steps\actions; + +defined('MOODLE_INTERNAL') || die; +require_once($CFG->dirroot.'/cohort/lib.php'); + /** * Cohort assignment action step class. * @@ -21,12 +26,6 @@ * @copyright Paul Damiani * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger\steps\actions; - -defined('MOODLE_INTERNAL') || die; -require_once($CFG->dirroot.'/cohort/lib.php'); - class assign_cohort_action_step extends base_action_step { use \tool_trigger\helper\datafield_manager; @@ -46,7 +45,7 @@ class assign_cohort_action_step extends base_action_step { * * @var array */ - private static $stepfields = array(); + private static $stepfields = []; /** * Returns the step name. @@ -66,25 +65,20 @@ public static function get_step_desc() { return get_string('assigncohortactionstepdesc', 'tool_trigger'); } + #[\Override] protected function init() { $this->useridfield = $this->data['useridfield']; $this->cohortidfield = $this->data['cohortidfield']; } - /** - * @param $step - * @param $trigger - * @param $event - * @param $stepresults - result of previousstep to include in processing this step. - * @return array if execution was succesful and the response from the execution. - */ + #[\Override] public function execute($step, $trigger, $event, $stepresults) { $datafields = $this->get_datafields($event, $stepresults); cohort_add_member($this->cohortidfield, $datafields[$this->useridfield]); - return array(true, $stepresults); + return [true, $stepresults]; } /** diff --git a/classes/steps/actions/email_action_step.php b/classes/steps/actions/email_action_step.php index 1ccdb9c..ccac070 100644 --- a/classes/steps/actions/email_action_step.php +++ b/classes/steps/actions/email_action_step.php @@ -14,15 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * email action step class. - * - * @package tool_trigger - * @copyright Catalyst IT - * @author Dan Marsden - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\steps\actions; /** @@ -61,7 +52,7 @@ class email_action_step extends base_action_step { * * @var array */ - private static $stepfields = array( + private static $stepfields = [ 'email_action_messageid', 'email_action_courseid', 'email_action_subject', @@ -72,8 +63,8 @@ class email_action_step extends base_action_step { 'email_action_userfrom_id', 'email_action_userfrom_email', 'email_action_userto_id', - 'email_action_userto_email' - ); + 'email_action_userto_email', + ]; /** * {@inheritDoc} @@ -105,13 +96,7 @@ public static function get_step_desc() { return get_string('emailactionstepdesc', 'tool_trigger'); } - /** - * @param $step - * @param $trigger - * @param $event - * @param $stepresults - result of previousstep to include in processing this step. - * @return array if execution was succesful and the response from the execution. - */ + #[\Override] public function execute($step, $trigger, $event, $stepresults) { global $DB; @@ -125,7 +110,7 @@ public function execute($step, $trigger, $event, $stepresults) { if ($emailto == clean_param($emailto, PARAM_EMAIL)) { // Check if user exists and use user record. - $user = $DB->get_record('user', array('email' => $emailto, 'deleted' => 0)); + $user = $DB->get_record('user', ['email' => $emailto, 'deleted' => 0]); // If user not found, use noreply as a base. if (empty($user)) { @@ -169,7 +154,7 @@ public function execute($step, $trigger, $event, $stepresults) { $stepresults['email_action_messageid'] = false; } - return array(true, $stepresults); + return [true, $stepresults]; } /** @@ -191,7 +176,7 @@ public function form_definition_extra($form, $mform, $customdata) { $mform->addHelpButton('emailsubject', 'emailsubject', 'tool_trigger'); // Params! - $attributes = array( + $attributes = [ 'subdirs' => false, 'maxbytes' => 0, 'maxfiles' => 0, @@ -199,8 +184,8 @@ public function form_definition_extra($form, $mform, $customdata) { 'context' => null, 'noclean' => 0, 'trusttext' => true, - 'enable_filemanagement' => false - ); + 'enable_filemanagement' => false, + ]; // Message! $mform->addElement('editor', 'emailcontent_editor', get_string('emailcontent', 'tool_trigger'), null, $attributes); diff --git a/classes/steps/actions/http_post_action_step.php b/classes/steps/actions/http_post_action_step.php index 4cddc4b..d8bcba1 100644 --- a/classes/steps/actions/http_post_action_step.php +++ b/classes/steps/actions/http_post_action_step.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * HTTP action step class. - * - * @package tool_trigger - * @copyright Matt Porritt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\steps\actions; /** @@ -45,12 +37,39 @@ class http_post_action_step extends base_action_step { 'PATCH' => 'PATCH', ]; + /** + * @var string The target URL for the HTTP request. + */ protected $url; + + /** + * @var string The HTTP method to use (e.g., GET, POST, PUT, DELETE). + */ protected $httpmethod; + + /** + * @var array|null An associative array of HTTP headers to send with the request. + */ protected $headers; + + /** + * @var array|null Parameters to include in the HTTP request body or query string. + */ protected $params; + + /** + * @var mixed|null Handler instance or resource for executing the HTTP request. + */ private $httphandler = null; + + /** + * @var mixed Expected format or value of the HTTP response. + */ private $expectedresponse; + + /** + * @var bool Whether to JSON-encode the request body before sending. + */ private $jsonencode; /** @@ -58,12 +77,13 @@ class http_post_action_step extends base_action_step { * * @var array */ - private static $stepfields = array( + private static $stepfields = [ 'http_response_status_code', 'http_response_status_message', 'http_response_body', - ); + ]; + #[\Override] protected function init() { $this->url = $this->data['url']; $this->httpmethod = !empty($this->data['httpmethod']) ? $this->data['httpmethod'] : 'POST'; @@ -120,13 +140,7 @@ public function get_http_client() { return new \GuzzleHttp\Client($clientconfig); } - /** - * @param $step - * @param $trigger - * @param $event - * @param $stepresults - result of previousstep to include in processing this step. - * @return array if execution was succesful and the response from the execution. - */ + #[\Override] public function execute($step, $trigger, $event, $stepresults) { $this->update_datafields($event, $stepresults); @@ -173,17 +187,14 @@ public function execute($step, $trigger, $event, $stepresults) { ); } - return array(true, $stepresults); + return [true, $stepresults]; } - /** - * {@inheritDoc} - * @see \tool_trigger\steps\base\base_step::add_extra_form_fields() - */ + #[\Override] public function form_definition_extra($form, $mform, $customdata) { // URL. - $attributes = array('size' => '50', 'placeholder' => 'https://www.example.com/api', 'type' => 'url'); + $attributes = ['size' => '50', 'placeholder' => 'https://www.example.com/api', 'type' => 'url']; $mform->addElement('text', 'url', get_string ('httpostactionurl', 'tool_trigger'), $attributes); // PARAM_URL will reject some templated urls. // TODO: Put some validation on this field? @@ -197,36 +208,33 @@ public function form_definition_extra($form, $mform, $customdata) { $mform->addHelpButton('httpmethod', 'httpostmethod', 'tool_trigger'); // Headers. - $attributes = array('cols' => '50', 'rows' => '2'); + $attributes = ['cols' => '50', 'rows' => '2']; $mform->addElement('textarea', 'httpheaders', get_string ('httpostactionheaders', 'tool_trigger'), $attributes); $mform->setType('httpheaders', PARAM_RAW_TRIMMED); $mform->addHelpButton('httpheaders', 'httpostactionheaders', 'tool_trigger'); // Params. - $attributes = array('cols' => '50', 'rows' => '5'); + $attributes = ['cols' => '50', 'rows' => '5']; $mform->addElement('textarea', 'httpparams', get_string ('httpostactionparams', 'tool_trigger'), $attributes); $mform->setType('httpparams', PARAM_RAW_TRIMMED); $mform->addHelpButton('httpparams', 'httpostactionparams', 'tool_trigger'); // Params as JSON. $mform->addElement('advcheckbox', 'jsonencode', get_string ('jsonencode', 'tool_trigger'), - 'Enable', array(), array(0, 1)); + 'Enable', [], [0, 1]); $mform->setType('jsonencode', PARAM_INT); $mform->addHelpButton('jsonencode', 'jsonencode', 'tool_trigger'); $mform->setDefault('jsonencode', 0); // Expected header response. - $attributes = array('size' => 3); + $attributes = ['size' => 3]; $mform->addElement('text', 'expectedresponse', get_string('expectedresponse', 'tool_trigger'), $attributes); $mform->setType('expectedresponse', PARAM_INT); $mform->addHelpButton('expectedresponse', 'expectedresponse', 'tool_trigger'); $mform->setDefault('expectedresponse', 200); } - /** - * {@inheritDoc} - * @see \tool_trigger\steps\base\base_step::add_privacy_metadata() - */ + #[\Override] public static function add_privacy_metadata($collection, $privacyfields) { return $collection->add_external_location_link( 'http_post_action_step', diff --git a/classes/steps/actions/logdump_action_step.php b/classes/steps/actions/logdump_action_step.php index 4c2f009..1fbaae8 100644 --- a/classes/steps/actions/logdump_action_step.php +++ b/classes/steps/actions/logdump_action_step.php @@ -31,10 +31,11 @@ class logdump_action_step extends base_action_step { * * @var array */ - private static $stepfields = array( + private static $stepfields = [ 'vardump', - ); + ]; + #[\Override] public function form_definition_extra( $form, $mform, @@ -42,14 +43,17 @@ public function form_definition_extra( $mform->addElement('html', self::get_step_desc()); } + #[\Override] public static function get_step_desc() { return get_string('step_action_logdump_desc', 'tool_trigger'); } + #[\Override] public static function get_step_name() { return get_string('step_action_logdump_name', 'tool_trigger'); } + #[\Override] public function execute($step, $trigger, $event, $stepresults) { mtrace('logdump step "' . $step->name); ob_start(); @@ -72,5 +76,4 @@ public static function get_fields() { return self::$stepfields; } - } diff --git a/classes/steps/actions/role_assign_action_step.php b/classes/steps/actions/role_assign_action_step.php index 8df3caa..bf9e812 100644 --- a/classes/steps/actions/role_assign_action_step.php +++ b/classes/steps/actions/role_assign_action_step.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger\steps\actions; + /** * Role assignment action step class. * @@ -21,9 +23,6 @@ * @copyright Dmitrii Metelkin * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger\steps\actions; - class role_assign_action_step extends base_action_step { use \tool_trigger\helper\datafield_manager; @@ -70,18 +69,14 @@ public static function get_step_desc() { return get_string('roleassignactionstepdesc', 'tool_trigger'); } - /** - * @inheritdoc - */ + #[\Override] protected function init() { $this->useridfield = $this->data['useridfield']; $this->roleidfield = $this->data['roleidfield']; $this->contextidfield = $this->data['contextidfield']; } - /** - * @inheritdoc - */ + #[\Override] public function execute($step, $trigger, $event, $stepresults) { $datafields = $this->get_datafields($event, $stepresults); @@ -128,10 +123,7 @@ public function execute($step, $trigger, $event, $stepresults) { return [true, $stepresults]; } - /** - * {@inheritDoc} - * @see \tool_trigger\steps\base\base_step::add_extra_form_fields() - */ + #[\Override] public function form_definition_extra($form, $mform, $customdata) { $mform->addElement('text', 'useridfield', get_string('step_action_role_assign_useridfield', 'tool_trigger')); $mform->setType('useridfield', PARAM_ALPHANUMEXT); diff --git a/classes/steps/actions/role_unassign_action_step.php b/classes/steps/actions/role_unassign_action_step.php index 7d18110..dbc91c4 100644 --- a/classes/steps/actions/role_unassign_action_step.php +++ b/classes/steps/actions/role_unassign_action_step.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger\steps\actions; + /** * Role unassignment action step class. * @@ -22,9 +24,6 @@ * @author Nicholas Hoobin * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger\steps\actions; - class role_unassign_action_step extends base_action_step { use \tool_trigger\helper\datafield_manager; @@ -72,7 +71,7 @@ public static function get_step_desc() { } /** - * @inheritdoc + * Init the step. */ protected function init() { $this->useridfield = $this->data['useridfield']; @@ -80,9 +79,7 @@ protected function init() { $this->contextidfield = $this->data['contextidfield']; } - /** - * @inheritdoc - */ + #[\Override] public function execute($step, $trigger, $event, $stepresults) { $datafields = $this->get_datafields($event, $stepresults); @@ -125,10 +122,7 @@ public function execute($step, $trigger, $event, $stepresults) { return [true, $stepresults]; } - /** - * {@inheritDoc} - * @see \tool_trigger\steps\base\base_step::add_extra_form_fields() - */ + #[\Override] public function form_definition_extra($form, $mform, $customdata) { $mform->addElement('text', 'useridfield', get_string('step_action_role_unassign_useridfield', 'tool_trigger')); $mform->setType('useridfield', PARAM_ALPHANUMEXT); diff --git a/classes/steps/actions/roles_unassign_action_step.php b/classes/steps/actions/roles_unassign_action_step.php index 0c17d2a..d4341ce 100644 --- a/classes/steps/actions/roles_unassign_action_step.php +++ b/classes/steps/actions/roles_unassign_action_step.php @@ -14,18 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Roles unassign action step class. - * - * @package tool_trigger - * @copyright Ilya Tregubov - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\steps\actions; /** - * HTTP Post action step class. + * Roles unassign action step class. * * @package tool_trigger * @copyright Ilya Tregubov @@ -40,16 +32,25 @@ class roles_unassign_action_step extends base_action_step { * * @var array */ - private static $stepfields = array(); + private static $stepfields = []; /** * The prefix to put before the new fields added to the workflow data. * - * @var string + * @var ?string */ private $inputprefixuser = null; + + /** + * The prefix to put before the new fields added to the workflow data. + * + * @var ?string + */ private $inputprefixrole = null; + /** + * Init the step. + */ protected function init() { if (!is_null($this->data['inputprefixuser'])) { $this->inputprefixuser = $this->data['inputprefixuser']; @@ -82,6 +83,8 @@ public static function get_step_desc() { } /** + * Execute the step. + * * @param $step * @param $trigger * @param $event @@ -93,21 +96,18 @@ public function execute($step, $trigger, $event, $stepresults) { if ($stepresults['user_suspended'] == 1) { foreach ($stepresults[$this->inputprefixrole . 'roles'] as $key => $value) { - role_unassign_all(array( + role_unassign_all([ 'userid' => $stepresults[$this->inputprefixrole . 'id'], 'contextid' => $value['contextid'], 'component' => $value['component'], - 'itemid' => $value['itemid'])); + 'itemid' => $value['itemid']]); } } - return array(true, $stepresults); + return [true, $stepresults]; } - /** - * {@inheritDoc} - * @see \tool_trigger\steps\base\base_step::add_extra_form_fields() - */ + #[\Override] public function form_definition_extra($form, $mform, $customdata) { $mform->addElement('text', 'inputprefixuser', get_string('inputprefixuser', 'tool_trigger')); $mform->setType('inputprefixuser', PARAM_ALPHANUMEXT); diff --git a/classes/steps/actions/webservice_action_step.php b/classes/steps/actions/webservice_action_step.php index f937316..938a8c2 100644 --- a/classes/steps/actions/webservice_action_step.php +++ b/classes/steps/actions/webservice_action_step.php @@ -50,6 +50,9 @@ class webservice_action_step extends base_action_step { 'exception', ]; + /** + * Step init. + */ protected function init() { $this->functionname = $this->data['functionname']; $this->username = $this->data['username']; diff --git a/classes/steps/base/base_form.php b/classes/steps/base/base_form.php index 95dcf19..d588656 100644 --- a/classes/steps/base/base_form.php +++ b/classes/steps/base/base_form.php @@ -92,9 +92,9 @@ private function is_first_step($stepclass, $existingsteps) { * @return array $explodedfields The formatted fields. */ private function explode_fields($stepfields, $outputprefix) { - $explodedfields = array(); + $explodedfields = []; foreach ($stepfields as $field) { - $explodedfields[] = array('field' => $outputprefix.$field); + $explodedfields[] = ['field' => $outputprefix.$field]; } return $explodedfields; @@ -110,14 +110,14 @@ private function explode_fields($stepfields, $outputprefix) { */ public function get_trigger_fields($eventname, $stepclass, $existingsteps, $steporder) { // Get all fields for this workflows event. - $fields = array(); + $fields = []; $learnprocess = new \tool_trigger\learn_process(); $fields['fields'] = $learnprocess->get_event_fields_with_type($eventname); - $fields['steps'] = array(); + $fields['steps'] = []; // Add notification for no event fields. if (empty($fields['fields'])) { - $fields['fields'] = array('nofields' => true); + $fields['fields'] = ['nofields' => true]; } $isfirst = $this->is_first_step($stepclass, $existingsteps); @@ -132,10 +132,10 @@ public function get_trigger_fields($eventname, $stepclass, $existingsteps, $step $stepfields = $step['stepclass']::get_fields(); if ($stepfields) { $stepfieldarray = $this->explode_fields($stepfields, $step['outputprefix']); - $steparray = array( + $steparray = [ 'stepname' => $step['stepdesc'], - 'fields' => $stepfieldarray - ); + 'fields' => $stepfieldarray, + ]; $fields['steps'][] = $steparray; } } @@ -161,13 +161,13 @@ public function definition() { $mform->setDefault('steporder', -1); // Step type. - $steptype = array( + $steptype = [ '' => get_string('choosedots'), 'lookups' => get_string('lookup', 'tool_trigger'), 'filters' => get_string('filter', 'tool_trigger'), 'actions' => get_string('action', 'tool_trigger'), 'debounce' => get_string('debounce', 'tool_trigger'), - ); + ]; $mform->addElement('select', 'type', get_string('steptype', 'tool_trigger'), $steptype); $mform->addHelpButton('type', 'steptype', 'tool_trigger'); $mform->addRule('type', get_string('required'), 'required'); @@ -176,9 +176,9 @@ public function definition() { } // Step. - $steps = array( + $steps = [ '' => get_string('choosedots'), - ); + ]; if (isset($this->_customdata['stepclass'])) { $steps[$this->_customdata['stepclass']] = $this->_customdata['steptext']; } @@ -196,14 +196,14 @@ public function definition() { // If a step class has already been instantiated, add more step details. if ($this->step) { // Name. - $attributes = array('size' => '50'); + $attributes = ['size' => '50']; $mform->addElement('text', 'name', get_string ('stepname', 'tool_trigger'), $attributes); $mform->setType('name', PARAM_ALPHAEXT); $mform->addRule('name', get_string('required'), 'required'); $mform->addHelpButton('name', 'stepname', 'tool_trigger'); // Description. - $attributes = array('cols' => '50', 'rows' => '2'); + $attributes = ['cols' => '50', 'rows' => '2']; $mform->addElement('textarea', 'description', get_string ('stepdescription', 'tool_trigger'), $attributes); $mform->setType('description', PARAM_ALPHAEXT); $mform->addRule('description', get_string('required'), 'required'); diff --git a/classes/steps/base/base_step.php b/classes/steps/base/base_step.php index d5d5b16..7744614 100644 --- a/classes/steps/base/base_step.php +++ b/classes/steps/base/base_step.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Base step class. - * - * @package tool_trigger - * @copyright Matt Porritt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\steps\base; /** @@ -33,10 +25,22 @@ */ abstract class base_step { + /** + * @var array Data storage array, typically holding parsed configuration or input values. + */ protected $data = []; - private $stepfields = array(); + /** + * @var array List of fields used in a specific processing step. + */ + private $stepfields = []; + /** + * Constructor. + * + * @param string|null $jsondata Optional JSON-encoded string to initialize the object with. + * If provided, it will be decoded into $data and init() will be called. + */ public function __construct($jsondata = null) { if ($jsondata) { $this->data = json_decode($jsondata, true); diff --git a/classes/steps/debounce/debounce_form.php b/classes/steps/debounce/debounce_form.php index 66cc7db..4c09237 100644 --- a/classes/steps/debounce/debounce_form.php +++ b/classes/steps/debounce/debounce_form.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Debounce step form class. - * - * @package tool_trigger - * @copyright Peter Burnett - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\steps\debounce; defined('MOODLE_INTERNAL') || die; @@ -37,6 +29,9 @@ */ class debounce_form extends \tool_trigger\steps\base\base_form { + /** + * Form definition. + */ public function definition() { parent::definition(); diff --git a/classes/steps/debounce/debounce_step.php b/classes/steps/debounce/debounce_step.php index dbca148..74e2687 100644 --- a/classes/steps/debounce/debounce_step.php +++ b/classes/steps/debounce/debounce_step.php @@ -258,7 +258,7 @@ public static function get_fields() { * {@inheritDoc} * @see \tool_trigger\steps\base\base_step::form_definition_extra() */ - public function form_definition_extra ($form, $mform, $customdata) { + public function form_definition_extra($form, $mform, $customdata) { return; } } diff --git a/classes/steps/filters/numcompare_filter_step.php b/classes/steps/filters/numcompare_filter_step.php index 17675e3..b0e5eb9 100644 --- a/classes/steps/filters/numcompare_filter_step.php +++ b/classes/steps/filters/numcompare_filter_step.php @@ -14,17 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Base filter step class. - * - * A filter is a workflow step that applies a test to the workflow instance's - * data, and halts execution of further steps if the test does not pass. - * - * @package tool_trigger - * @copyright Matt Porritt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger\steps\filters; /** @@ -37,17 +26,50 @@ class numcompare_filter_step extends base_filter_step { use \tool_trigger\helper\datafield_manager; + /** + * Comparison operator for equality. + */ const OPERATOR_EQUAL = '=='; + + /** + * Comparison operator for inequality. + */ const OPERATOR_NOTEQUAL = '!='; + + /** + * Comparison operator for less than. + */ const OPERATOR_LT = '<'; + + /** + * Comparison operator for less than or equal to. + */ const OPERATOR_LTE = '<='; + + /** + * Comparison operator for greater than or equal to. + */ const OPERATOR_GTE = '>='; + + /** + * Comparison operator for greater than. + */ const OPERATOR_GT = '>'; + /** + * @var mixed The first field or value to be compared. + */ protected $field1; + + /** + * @var mixed The second field or value to be compared. + */ protected $field2; - protected $operator; + /** + * @var string The comparison operator, one of the OPERATOR_* constants. + */ + protected $operator; /** * {@inheritDoc} @@ -94,6 +116,13 @@ public function execute($step, $trigger, $event, $stepresults) { return [$result, $stepresults]; } + /** + * Gets the field value from form value. + * + * @param mixed $formval + * + * @return float|int|string + */ private function get_field_value($formval) { $formval = trim($formval); @@ -157,7 +186,7 @@ public function form_definition_extra($form, $mform, $customdata) { self::OPERATOR_LTE => '<', self::OPERATOR_LT => '<=', self::OPERATOR_GT => '>', - self::OPERATOR_GTE => '>=' + self::OPERATOR_GTE => '>=', ]); // TODO: lang string! diff --git a/classes/steps/filters/stringcompare_filter_step.php b/classes/steps/filters/stringcompare_filter_step.php index 79b9986..e573615 100644 --- a/classes/steps/filters/stringcompare_filter_step.php +++ b/classes/steps/filters/stringcompare_filter_step.php @@ -209,7 +209,7 @@ public function form_definition_extra($form, $mform, $customdata) { $fields[] = $mform->createElement('select', 'wantmatch', 'Reverse match?', [ 1 => 'does', - 0 => 'does not' + 0 => 'does not', ]); // TODO: lang strings! @@ -218,7 +218,7 @@ public function form_definition_extra($form, $mform, $customdata) { self::OPERATOR_CONTAINS => 'contain', self::OPERATOR_STARTS_WITH => 'start with', self::OPERATOR_ENDS_WITH => 'end with', - self::OPERATOR_REGEX => 'match regex' + self::OPERATOR_REGEX => 'match regex', ]); // TODO: lang string! @@ -230,7 +230,7 @@ public function form_definition_extra($form, $mform, $customdata) { // Error instead of failure. $mform->addElement('advcheckbox', 'erroronfail', get_string ('erroronfail', 'tool_trigger'), - 'Enable', array(), array(0, 1)); + 'Enable', [], [0, 1]); $mform->setType('erroronfail', PARAM_INT); $mform->addHelpButton('erroronfail', 'erroronfail', 'tool_trigger'); $mform->setDefault('erroronfail', 0); diff --git a/classes/steps/lookups/cohort_lookup_step.php b/classes/steps/lookups/cohort_lookup_step.php index d5bcd1c..3be5372 100644 --- a/classes/steps/lookups/cohort_lookup_step.php +++ b/classes/steps/lookups/cohort_lookup_step.php @@ -56,10 +56,13 @@ class cohort_lookup_step extends base_lookup_step { * * @var array */ - private static $stepfields = array( - 'id_[cohortid]' - ); + private static $stepfields = [ + 'id_[cohortid]', + ]; + /** + * Init the step. + */ protected function init() { $this->useridfield = $this->data['useridfield']; $this->outputprefix = $this->data['outputprefix']; diff --git a/classes/steps/lookups/course_cat_lookup_step.php b/classes/steps/lookups/course_cat_lookup_step.php index a50cab0..571803a 100644 --- a/classes/steps/lookups/course_cat_lookup_step.php +++ b/classes/steps/lookups/course_cat_lookup_step.php @@ -61,9 +61,12 @@ class course_cat_lookup_step extends base_lookup_step { 'depth', 'path', 'theme', - 'contextid' + 'contextid', ]; + /** + * Init the step. + */ protected function init() { $this->categoryidfield = $this->data['categoryidfield']; $this->outputprefix = $this->data['outputprefix']; diff --git a/classes/steps/lookups/course_lookup_step.php b/classes/steps/lookups/course_lookup_step.php index 1b3f324..094e42b 100644 --- a/classes/steps/lookups/course_lookup_step.php +++ b/classes/steps/lookups/course_lookup_step.php @@ -47,7 +47,7 @@ class course_lookup_step extends base_lookup_step { * * @var array */ - private static $stepfields = array( + private static $stepfields = [ 'id', 'category', 'sortorder', @@ -80,8 +80,11 @@ class course_lookup_step extends base_lookup_step { 'completionnotify', 'cacherev', 'contextid', - ); + ]; + /** + * Init the step. + */ protected function init() { $this->courseidfield = $this->data['courseidfield']; $this->outputprefix = $this->data['outputprefix']; diff --git a/classes/steps/lookups/roles_lookup_step.php b/classes/steps/lookups/roles_lookup_step.php index 2db19c2..69e6de5 100644 --- a/classes/steps/lookups/roles_lookup_step.php +++ b/classes/steps/lookups/roles_lookup_step.php @@ -47,8 +47,11 @@ class roles_lookup_step extends base_lookup_step { * * @var array */ - private static $stepfields = array('roles'); + private static $stepfields = ['roles']; + /** + * Init the step. + */ protected function init() { $this->useridfield = $this->data['useridfield']; $this->outputprefix = $this->data['outputprefix']; @@ -69,7 +72,7 @@ public function execute($step, $trigger, $event, $stepresults) { } $sql = 'SELECT id, roleid, contextid, component, itemid FROM {role_assignments} WHERE userid = :userid'; - $params = array('userid' => $datafields[$this->useridfield]); + $params = ['userid' => $datafields[$this->useridfield]]; $userroles = $DB->get_records_sql($sql, $params); foreach ($userroles as $role) { foreach ($role as $key => $value) { diff --git a/classes/steps/lookups/user_lookup_step.php b/classes/steps/lookups/user_lookup_step.php index 9f14e85..24c6a69 100644 --- a/classes/steps/lookups/user_lookup_step.php +++ b/classes/steps/lookups/user_lookup_step.php @@ -52,7 +52,7 @@ class user_lookup_step extends base_lookup_step { * * @var array */ - private static $stepfields = array( + private static $stepfields = [ 'id', 'auth', 'confirmed', @@ -98,7 +98,7 @@ class user_lookup_step extends base_lookup_step { 'firstnamephonetic', 'middlename', 'alternatename', - 'moodlenetprofile'); + 'moodlenetprofile']; /** * Whether to halt execution of the workflow, if the user has been marked "deleted". @@ -107,6 +107,9 @@ class user_lookup_step extends base_lookup_step { */ private $nodeleted; + /** + * Init the step. + */ protected function init() { $this->useridfield = $this->data['useridfield']; $this->outputprefix = $this->data['outputprefix']; diff --git a/classes/task/cleanup.php b/classes/task/cleanup.php index 6de5e12..a1e4da9 100644 --- a/classes/task/cleanup.php +++ b/classes/task/cleanup.php @@ -64,7 +64,7 @@ public function execute() { AND timecreated < :timetocleanup"; $DB->execute($sql, [ 'statusready' => \tool_trigger\task\process_workflows::STATUS_READY_TO_RUN, - 'timetocleanup' => $timetocleanup + 'timetocleanup' => $timetocleanup, ]); // Now delete processed queue items. @@ -74,7 +74,7 @@ public function execute() { AND timemodified < :timetocleanup"; $DB->execute($sql, [ 'statusready' => \tool_trigger\task\process_workflows::STATUS_READY_TO_RUN, - 'timetocleanup' => $timetocleanup + 'timetocleanup' => $timetocleanup, ]); } } diff --git a/classes/task/process_workflows.php b/classes/task/process_workflows.php index 1809383..9082fe1 100644 --- a/classes/task/process_workflows.php +++ b/classes/task/process_workflows.php @@ -14,6 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger\task; + +use tool_trigger\helper\processor_helper; + /** * Process queued workflows. * @@ -21,14 +25,6 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger\task; - -use tool_trigger\helper\processor_helper; - -/** - * Simple task to rocess queued workflows. - */ class process_workflows extends \core\task\scheduled_task { use processor_helper; @@ -91,7 +87,7 @@ public function execute() { */ private function create_trigger_queue($now) { global $DB; - $triggerqueue = array(); + $triggerqueue = []; // Get list of events to process that are not already in the queue for not real time workflows. $sql = "SELECT e.*, w.id as workflowid @@ -116,7 +112,12 @@ private function create_trigger_queue($now) { $this->insert_queue_records($triggerqueue); } - private function process_queue($starttime) { + /** + * Process queue. + * + * @param int $starttime Start time. + */ + private function process_queue(int $starttime) { global $DB; // Now process queue including real time workflows that dumped records in the queue as couldn't process realtime. @@ -130,7 +131,7 @@ private function process_queue($starttime) { ORDER BY q.timecreated"; $params = [ 'time' => time(), - 'autorerunmaxtries' => get_config('tool_trigger', 'autorerunmaxtries') + 'autorerunmaxtries' => get_config('tool_trigger', 'autorerunmaxtries'), ]; $queue = $DB->get_recordset_sql($sql, $params, 0, get_config('tool_trigger', 'queuelimit')); @@ -146,7 +147,12 @@ private function process_queue($starttime) { $queue->close(); } - private function process_item($item) { + /** + * Process a given item + * + * @param \stdClass $item Item to process. + */ + private function process_item(\stdClass $item) { global $DB; // Check if this queue item has been cancelled in this run. diff --git a/classes/workflow.php b/classes/workflow.php index 6dfdbfe..6f5d6a4 100644 --- a/classes/workflow.php +++ b/classes/workflow.php @@ -120,7 +120,7 @@ public function __construct($workflow) { * @return \string */ public function get_name($context) { - return format_text($this->workflow->name, FORMAT_HTML, array('context' => $context)); + return format_text($this->workflow->name, FORMAT_HTML, ['context' => $context]); } /** @@ -130,6 +130,6 @@ public function get_name($context) { * @return \string */ public function get_description($context) { - return format_text($this->descriptiontext, $this->descriptionformat, array('context' => $context)); + return format_text($this->descriptiontext, $this->descriptionformat, ['context' => $context]); } } diff --git a/classes/workflow_manager.php b/classes/workflow_manager.php index 69dd2fb..97de147 100644 --- a/classes/workflow_manager.php +++ b/classes/workflow_manager.php @@ -36,7 +36,7 @@ class workflow_manager { /** * @var string[] The categories of steps available. */ - const STEPTYPES = array('lookups', 'actions', 'filters', 'debounce'); + const STEPTYPES = ['lookups', 'actions', 'filters', 'debounce']; /** * Helper method to convert db records to workflow objects. @@ -45,7 +45,7 @@ class workflow_manager { * @return array of worklfow objects. */ protected static function get_instances($records) { - $workflows = array(); + $workflows = []; foreach ($records as $key => $record) { $workflows[$key] = new workflow($record); } @@ -223,8 +223,8 @@ public function get_step_class_names($steptype = null) { $steptypes = [$steptype]; } - $matchedsteps = array(); - $matches = array(); + $matchedsteps = []; + $matches = []; foreach ($steptypes as $steptype) { $stepdir = __DIR__ . '/steps/' . $steptype; @@ -250,7 +250,7 @@ public function get_step_class_names($steptype = null) { * @return string[] An array with the classes as the keys, and the name strings as the values. */ public function lookup_step_names($stepclasses) { - $stepnames = array(); + $stepnames = []; foreach ($stepclasses as $stepclass) { if ($this->validate_step_class($stepclass)) { diff --git a/classes/workflow_process.php b/classes/workflow_process.php index 66228c0..c89c41f 100644 --- a/classes/workflow_process.php +++ b/classes/workflow_process.php @@ -41,14 +41,14 @@ class workflow_process { /** * @var array Array of fields to filter from step JSON. */ - protected $stepfields = array( + protected $stepfields = [ 'id', 'type', 'stepclass', 'name', 'description', - 'steporder' - ); + 'steporder', + ]; /** * Class constructor. @@ -75,14 +75,14 @@ public function to_form_defaults($workflowid) { 'workflowname' => $workflow->workflow->name, 'workflowdescription' => [ 'text' => $workflow->descriptiontext, - 'format' => $workflow->descriptionformat + 'format' => $workflow->descriptionformat, ], 'eventtomonitor' => $workflow->event, 'draftmode' => $workflow->draft, 'workflowactive' => $workflow->active, 'workflowrealtime' => $workflow->realtime, 'workflowdebug' => $workflow->debug, - 'stepjson' => $this->encode_steps_to_json_for_form($workflow) + 'stepjson' => $this->encode_steps_to_json_for_form($workflow), ]; } @@ -271,7 +271,7 @@ public static function import_prep($filejson) { $data->workflowdebug = isset($content['debug']) ? $content['debug'] : 0; // Format and flatten step data. - $cleansteps = array(); + $cleansteps = []; foreach ($content['steps'] as $step) { $stepdata = json_decode($step['data']); foreach ($stepdata as $key => $value) { diff --git a/cli/export_fields.php b/cli/export_fields.php index 8a7e4f8..5d5f1b9 100644 --- a/cli/export_fields.php +++ b/cli/export_fields.php @@ -28,7 +28,7 @@ require_once($CFG->libdir.'/clilib.php'); // Get cli options. -list($options, $unrecognized) = cli_get_params(array('help' => false), array('h' => 'help')); +list($options, $unrecognized) = cli_get_params(['help' => false], ['h' => 'help']); if ($unrecognized) { $unrecognized = implode("\n ", $unrecognized); @@ -58,7 +58,7 @@ // Get the events we have stored fields for. $learnprocess = new \tool_trigger\learn_process(); $eventnames = $learnprocess->get_event_fields_events(); -$results = array(); +$results = []; $count = 0; // Iterrate through each event getting fields. diff --git a/cli/import_csv_records.php b/cli/import_csv_records.php index 6f3c15e..6b0a334 100644 --- a/cli/import_csv_records.php +++ b/cli/import_csv_records.php @@ -32,13 +32,13 @@ // Get cli options. list($options, $unrecognized) = cli_get_params( - array( + [ 'source' => '', - 'help' => false - ), - array( - 'h' => 'help' - ) + 'help' => false, + ], + [ + 'h' => 'help', + ] ); if ($unrecognized) { @@ -73,8 +73,8 @@ if ($fp) { // Go through CSV file line by line extracting data and inserting into database. while (($data = fgetcsv($fp)) !== false) { - $parametermatches = array(); - $valuesmatches = array(); + $parametermatches = []; + $valuesmatches = []; // Only get the 2 fields from the CSV that contain the data we need. $gotparameters = preg_match ('/\((.*?)\)/', $data[13], $parametermatches); diff --git a/db/access.php b/db/access.php index e29f522..50ab7d1 100644 --- a/db/access.php +++ b/db/access.php @@ -26,30 +26,30 @@ defined('MOODLE_INTERNAL') || die(); -$capabilities = array( +$capabilities = [ - 'tool/trigger:manageworkflows' => array( + 'tool/trigger:manageworkflows' => [ 'riskbitmask' => RISK_CONFIG | RISK_PERSONAL | RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, - 'archetypes' => array( - 'manager' => CAP_ALLOW - ), - ), - 'tool/trigger:exportworkflowhistory' => array( + 'archetypes' => [ + 'manager' => CAP_ALLOW, + ], + ], + 'tool/trigger:exportworkflowhistory' => [ 'riskbitmask' => RISK_CONFIG | RISK_PERSONAL | RISK_SPAM, 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, - 'archetypes' => array( - 'manager' => CAP_ALLOW - ), - ), - 'tool/trigger:exportrundetails' => array( + 'archetypes' => [ + 'manager' => CAP_ALLOW, + ], + ], + 'tool/trigger:exportrundetails' => [ 'riskbitmask' => RISK_CONFIG | RISK_PERSONAL | RISK_SPAM, 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, - 'archetypes' => array( - 'manager' => CAP_ALLOW - ), - ), -); + 'archetypes' => [ + 'manager' => CAP_ALLOW, + ], + ], +]; diff --git a/db/caches.php b/db/caches.php index 31b9afd..a5dc9d6 100644 --- a/db/caches.php +++ b/db/caches.php @@ -25,12 +25,12 @@ defined('MOODLE_INTERNAL') || die; -$definitions = array( - 'eventsubscriptions' => array( +$definitions = [ + 'eventsubscriptions' => [ 'mode' => cache_store::MODE_APPLICATION, 'simplekeys' => true, 'simpledata' => true, 'staticacceleration' => true, - 'staticaccelerationsize' => 30 - ) -); + 'staticaccelerationsize' => 30, + ], +]; diff --git a/db/events.php b/db/events.php index 29c1224..ab7904c 100644 --- a/db/events.php +++ b/db/events.php @@ -25,9 +25,9 @@ defined('MOODLE_INTERNAL') || die(); // List of observers. -$observers = array( - array( +$observers = [ + [ 'eventname' => '*', 'callback' => '\tool_trigger\event_processor::process_event', - ), -); + ], +]; diff --git a/db/messages.php b/db/messages.php index 9f69b78..aa7e2a7 100644 --- a/db/messages.php +++ b/db/messages.php @@ -13,16 +13,18 @@ // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . + /** * Defines message providers (types of message sent) for the Re-engagement activity. * * @package tool_trigger * @author Dan Marsden + * @copyright Catalyst IT * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -$messageproviders = array( - 'tool_trigger' => array(), -); +$messageproviders = [ + 'tool_trigger' => [], +]; diff --git a/db/services.php b/db/services.php index 41a35c0..35ae963 100644 --- a/db/services.php +++ b/db/services.php @@ -25,32 +25,32 @@ defined('MOODLE_INTERNAL') || die(); // Define the web service functions to install. -$functions = array( - 'tool_trigger_step_by_type' => array( +$functions = [ + 'tool_trigger_step_by_type' => [ 'classname' => 'tool_trigger_external', 'methodname' => 'step_by_type', 'classpath' => 'admin/tool/trigger/externallib.php', 'description' => 'Returns all steps matching supplied type', 'type' => 'read', 'capabilities' => 'tool/trigger:manageworkflows', - 'ajax' => true - ), - 'tool_trigger_validate_form' => array( + 'ajax' => true, + ], + 'tool_trigger_validate_form' => [ 'classname' => 'tool_trigger_external', 'methodname' => 'validate_form', 'classpath' => 'admin/tool/trigger/externallib.php', 'description' => 'Checks to see if a form contains valid data', 'type' => 'read', 'capabilities' => 'tool/trigger:manageworkflows', - 'ajax' => true - ), - 'tool_trigger_process_import_form' => array( + 'ajax' => true, + ], + 'tool_trigger_process_import_form' => [ 'classname' => 'tool_trigger_external', 'methodname' => 'process_import_form', 'classpath' => 'admin/tool/trigger/externallib.php', 'description' => 'Creates a new workflow.', 'type' => 'write', 'capabilities' => 'tool/trigger:manageworkflows', - 'ajax' => true - ), -); + 'ajax' => true, + ], +]; diff --git a/db/tasks.php b/db/tasks.php index 374e724..fbb9232 100644 --- a/db/tasks.php +++ b/db/tasks.php @@ -17,7 +17,7 @@ /** * This file defines tasks performed by the tool. * - * @package tool_monitor + * @package tool_trigger * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -25,41 +25,41 @@ defined('MOODLE_INTERNAL') || die(); // List of tasks. -$tasks = array( - array( +$tasks = [ + [ 'classname' => 'tool_trigger\task\process_workflows', 'blocking' => 0, 'minute' => '*', 'hour' => '*', 'day' => '*', 'dayofweek' => '*', - 'month' => '*' - ), - array( + 'month' => '*', + ], + [ 'classname' => 'tool_trigger\task\cleanup', 'blocking' => 0, 'minute' => 'R', 'hour' => '*', 'day' => '*', 'dayofweek' => '*', - 'month' => '*' - ), - array( + 'month' => '*', + ], + [ 'classname' => 'tool_trigger\task\learn', 'blocking' => 0, 'minute' => 'R', 'hour' => 'R', 'day' => '*', 'dayofweek' => '*', - 'month' => '*' - ), - array( + 'month' => '*', + ], + [ 'classname' => 'tool_trigger\task\cleanup_history', 'blocking' => 0, 'minute' => 'R', 'hour' => '0', 'day' => '*', 'dayofweek' => '*', - 'month' => '*' - ) -); + 'month' => '*', + ], +]; diff --git a/db/upgrade.php b/db/upgrade.php index 3f9f688..f15c9e0 100644 --- a/db/upgrade.php +++ b/db/upgrade.php @@ -49,7 +49,7 @@ function xmldb_tool_trigger_upgrade($oldversion) { $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); // Adding keys to table tool_trigger_events. - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); // Conditionally launch create table for tool_trigger_events. if (!$dbman->table_exists($table)) { @@ -86,7 +86,7 @@ function xmldb_tool_trigger_upgrade($oldversion) { // Add new index to table tool_trigger_events. $table = new xmldb_table('tool_trigger_events'); - $table->add_index('eventname', XMLDB_INDEX_NOTUNIQUE, array('eventname')); + $table->add_index('eventname', XMLDB_INDEX_NOTUNIQUE, ['eventname']); // Conditionally launch create table for tool_trigger_events. if (!$dbman->table_exists($table)) { @@ -119,11 +119,11 @@ function xmldb_tool_trigger_upgrade($oldversion) { $table->add_field('ip', XMLDB_TYPE_CHAR, '45', null, null, null, null); $table->add_field('realuserid', XMLDB_TYPE_INTEGER, '10', null, null, null, null); - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id')); + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + $table->add_key('contextid', XMLDB_KEY_FOREIGN, ['contextid'], 'context', ['id']); - $table->add_index('timecreated', XMLDB_INDEX_NOTUNIQUE, array('timecreated')); - $table->add_index('eventname', XMLDB_INDEX_NOTUNIQUE, array('eventname')); + $table->add_index('timecreated', XMLDB_INDEX_NOTUNIQUE, ['timecreated']); + $table->add_index('eventname', XMLDB_INDEX_NOTUNIQUE, ['eventname']); // Conditionally launch create table for tool_trigger_events. if (!$dbman->table_exists($table)) { @@ -173,7 +173,7 @@ function xmldb_tool_trigger_upgrade($oldversion) { // Convert all old email text fields to new Atto fields. $sql = 'SELECT * FROM {tool_trigger_steps} WHERE stepclass = \'\tool_trigger\steps\actions\email_action_step\''; - $rs = $DB->get_recordset_sql($sql, array()); + $rs = $DB->get_recordset_sql($sql, []); foreach ($rs as $record) { $data = json_decode($record->data, true); $data['emailcontent_editor[text]'] = $data['emailcontent']; @@ -217,8 +217,8 @@ function xmldb_tool_trigger_upgrade($oldversion) { $table->add_field('failedstep', XMLDB_TYPE_INTEGER, '10', null, null, null, null); // Adding keys to table tool_trigger_workflow_hist. - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('eventid', XMLDB_KEY_FOREIGN, array('eventid'), 'tool_trigger_events', array('id')); + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + $table->add_key('eventid', XMLDB_KEY_FOREIGN, ['eventid'], 'tool_trigger_events', ['id']); // Conditionally launch create table for tool_trigger_workflow_hist. if (!$dbman->table_exists($table)) { @@ -247,12 +247,12 @@ function xmldb_tool_trigger_upgrade($oldversion) { $table->add_field('stepconfigid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); // Adding keys to table tool_trigger_run_hist. - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('workflowid', XMLDB_KEY_FOREIGN, array('workflowid'), 'tool_trigger_workflows', array('id')); - $table->add_key('run', XMLDB_KEY_FOREIGN, array('runid'), 'tool_trigger_workflow_hist', array('id')); + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + $table->add_key('workflowid', XMLDB_KEY_FOREIGN, ['workflowid'], 'tool_trigger_workflows', ['id']); + $table->add_key('run', XMLDB_KEY_FOREIGN, ['runid'], 'tool_trigger_workflow_hist', ['id']); // Adding indexes to table tool_trigger_run_hist. - $table->add_index('class', XMLDB_INDEX_NOTUNIQUE, array('stepclass')); + $table->add_index('class', XMLDB_INDEX_NOTUNIQUE, ['stepclass']); // Conditionally launch create table for tool_trigger_run_hist. if (!$dbman->table_exists($table)) { diff --git a/edit.php b/edit.php index 92d8c04..cbacfa1 100644 --- a/edit.php +++ b/edit.php @@ -31,7 +31,7 @@ require_login(); -$url = new moodle_url("/admin/tool/trigger/edit.php", array('workflowid' => $workflowid)); +$url = new moodle_url("/admin/tool/trigger/edit.php", ['workflowid' => $workflowid]); $context = context_system::instance(); // Check for caps. @@ -52,7 +52,7 @@ if ($node = $PAGE->settingsnav->find('root', \navigation_node::TYPE_SITE_ADMIN)) { $PAGE->navbar->add($node->get_content(), $node->action()); } -foreach (array('tools', 'tool_trigger', 'tool_trigger_worfklowsettings') as $label) { +foreach (['tools', 'tool_trigger', 'tool_trigger_worfklowsettings'] as $label) { if ($node = $PAGE->settingsnav->find($label, \navigation_node::TYPE_SETTING)) { $PAGE->navbar->add($node->get_content(), $node->action()); } @@ -60,7 +60,7 @@ $PAGE->navbar->add($pagetitlestr); // Load the javascript. -$PAGE->requires->js_call_amd('tool_trigger/step_select', 'init', array($context->id)); +$PAGE->requires->js_call_amd('tool_trigger/step_select', 'init', [$context->id]); $eventlist = \tool_monitor\eventlist::get_all_eventlist(); diff --git a/externallib.php b/externallib.php index 8aa839e..0f5e8ee 100644 --- a/externallib.php +++ b/externallib.php @@ -40,9 +40,9 @@ class tool_trigger_external extends external_api { */ public static function step_by_type_parameters() { return new external_function_parameters( - array( + [ 'steptype' => new external_value(PARAM_ALPHA, 'The type of step to get.'), - ) + ] ); } @@ -80,7 +80,7 @@ public static function step_by_type($steptype) { foreach ($steps as $class => $namestr) { $output[] = [ 'class' => $class, - 'name' => $namestr + 'name' => $namestr, ]; } return $output; @@ -93,10 +93,10 @@ public static function step_by_type($steptype) { public static function step_by_type_returns() { return new external_multiple_structure( new external_single_structure( - array( + [ 'class' => new external_value(PARAM_TEXT, 'Event identifier'), 'name' => new external_value(PARAM_TEXT, 'Event Name'), - ) + ] ) ); } @@ -107,10 +107,10 @@ public static function step_by_type_returns() { */ public static function validate_form_parameters() { return new external_function_parameters( - array( + [ 'stepclass' => new external_value(PARAM_RAW, 'The step class being validated'), - 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the create group form, encoded as a json array') - ) + 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the create group form, encoded as a json array'), + ] ); } @@ -136,14 +136,14 @@ public static function validate_form($stepclass, $jsonformdata) { $workflowmanager = new \tool_trigger\workflow_manager(); $step = $workflowmanager->validate_and_make_step($stepclass); - $data = array(); + $data = []; if (!empty($params['jsonformdata'])) { $serialiseddata = json_decode($params['jsonformdata']); parse_str($serialiseddata, $data); } // Create the form and trigger validation. - $mform = $step->make_form(array(), $data); + $mform = $step->make_form([], $data); if (!$mform->is_validated()) { // Generate a warning. @@ -168,9 +168,9 @@ public static function validate_form_returns() { */ public static function process_import_form_parameters() { return new external_function_parameters( - array( - 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the create group form, encoded as a json array') - ) + [ + 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the create group form, encoded as a json array'), + ] ); } @@ -192,7 +192,7 @@ public static function process_import_form($jsonformdata) { $params = self::validate_parameters(self::process_import_form_parameters(), ['jsonformdata' => $jsonformdata]); - $data = array(); + $data = []; if (!empty($params['jsonformdata'])) { $serialiseddata = json_decode($params['jsonformdata']); parse_str($serialiseddata, $data); @@ -221,7 +221,7 @@ public static function process_import_form($jsonformdata) { $cache = \cache::make('tool_trigger', 'eventsubscriptions'); $cache->purge(); - $returnmsg->message = array('success' => get_string('workflowimported', 'tool_trigger')); + $returnmsg->message = ['success' => get_string('workflowimported', 'tool_trigger')]; $returnmsg->errorcode = 'success'; } else { // Processing failure. diff --git a/history.php b/history.php index 451c8d1..dc5c240 100644 --- a/history.php +++ b/history.php @@ -25,7 +25,7 @@ require_once(__DIR__ . '/../../../config.php'); require_once($CFG->libdir . '/adminlib.php'); -admin_externalpage_setup('tool_trigger_worfklowsettings', '', null, '', array('pagelayout' => 'report')); +admin_externalpage_setup('tool_trigger_worfklowsettings', '', null, '', ['pagelayout' => 'report']); $context = context_system::instance(); @@ -188,7 +188,7 @@ } else { $confirmurl = new moodle_url('/admin/tool/trigger/history.php'); $confirmurl->params(['confirm' => 1, 'action' => $action, 'id' => $actionid, - 'workflow' => $workflowid, 'id' => $actionid]); + 'workflow' => $workflowid]); $cancelurl = new moodle_url('/admin/tool/trigger/history.php', ['workflow' => $workflowid, 'run' => $runid]); $string = get_string('rerunallcurrconfirm', 'tool_trigger'); } @@ -200,7 +200,7 @@ } else { $confirmurl = new moodle_url('/admin/tool/trigger/history.php'); $confirmurl->params(['confirm' => 1, 'action' => $action, 'id' => $actionid, - 'workflow' => $workflowid, 'id' => $actionid]); + 'workflow' => $workflowid]); $cancelurl = new moodle_url('/admin/tool/trigger/history.php', ['workflow' => $workflowid, 'run' => $runid]); $string = get_string('rerunallhistconfirm', 'tool_trigger'); } diff --git a/lang/en/tool_trigger.php b/lang/en/tool_trigger.php index e689ae9..52924fd 100644 --- a/lang/en/tool_trigger.php +++ b/lang/en/tool_trigger.php @@ -25,9 +25,6 @@ defined('MOODLE_INTERNAL') || die(); -$string['pluginname'] = 'Event Trigger'; -$string['pluginname_help'] = 'Event Triggering for Moodle'; - $string['action'] = 'Action'; $string['actionscurrent'] = 'Current configuration'; $string['actionshistoric'] = 'Historic configuration'; @@ -35,8 +32,8 @@ $string['addworkflow'] = 'Add new trigger workflow'; $string['areatomonitor'] = 'Area to monitor'; $string['areatomonitor_help'] = 'The Moodle area that contains the event to trigger workflow on.'; -$string['assigncohortactionstepname'] = 'Assign cohort'; $string['assigncohortactionstepdesc'] = 'A step that allows for assigning a user to a cohort'; +$string['assigncohortactionstepname'] = 'Assign cohort'; $string['autorerun'] = 'Enable auto re-run'; $string['autorerun_help'] = ''; $string['autorerunduration'] = 'Minimum duration before re-run attempted'; @@ -46,9 +43,11 @@ $string['autorerunsettings'] = 'Auto re-run'; $string['autorerunsettingsdesc'] = ''; $string['availablefields'] = 'Available fields'; -$string['badsteptype'] = 'Incorrect step type'; $string['badstepclass'] = 'Incorrect step class name'; +$string['badsteptype'] = 'Incorrect step type'; $string['cachedef_eventsubscriptions'] = 'Tool Trigger event subscription cache'; +$string['categoryidfield'] = 'Category id data field'; +$string['categoryidfield_help'] = 'You can use category id as a number or as a filed name from the workflow data'; $string['cleanupsettings'] = 'Clean up settings'; $string['cleanupsettingsdesc'] = 'The following settings control the cleanup tasks for this plugin.'; $string['cli_extractfields'] = 'Extracting fields for learnt events from database...'; @@ -56,7 +55,11 @@ $string['cli_filesummary'] = 'File written to: {$a}'; $string['cli_writingfile'] = 'Writing {$a} event field definitions to file...'; $string['cohortidfield'] = 'Cohort ID'; +$string['contextidfield'] = 'Context id data field'; +$string['contextidfield_help'] = 'You can use context id as a number or as a filed name from the workflow data'; $string['core'] = 'Core'; +$string['courseidfield'] = 'Course id data field'; +$string['courseidfield_help'] = 'You can use course id as a number or as a filed name from the workflow data'; $string['debounce'] = 'Debounce'; $string['debounce_desc'] = 'The debounce step is a special step that queues up the workflow to be run after a certain period of time, using only the latest instance of the workflow to occur in the period, with a period reset occuring at each new workflow instance trigger.'; $string['debouncecontext'] = 'Debounce match fields'; @@ -67,38 +70,38 @@ $string['deletestep'] = 'Delete step'; $string['description'] = 'Description'; $string['downloadrule'] = 'Download rule'; -$string['downloadworkflow'] = 'Download workflow history'; $string['downloadrundetails'] = 'Download run details'; +$string['downloadworkflow'] = 'Download workflow history'; $string['draft'] = 'Draft'; $string['draftmode'] = 'Draft mode'; $string['draftmode_help'] = 'Use draft mode to test workflow with firing triggers.'; -$string['duplicaterule'] = 'Duplicate rule'; $string['duplicatedworkflowname'] = '{$a} (copy)'; +$string['duplicaterule'] = 'Duplicate rule'; $string['editrule'] = 'Edit rule'; $string['editsettings'] = 'Workflow settings'; $string['editstep'] = 'Edit step'; $string['editworkflow'] = 'Edit trigger workflow'; +$string['emailactionstepdesc'] = 'A step to allow an e-mail to be sent'; +$string['emailactionstepname'] = 'Email'; +$string['emailcontent'] = 'Content'; +$string['emailcontent_help'] = 'The content to use in the email'; $string['emailsubject'] = 'Subject'; $string['emailsubject_help'] = 'The text to use in the subject of the e-mail'; $string['emailto'] = 'To'; $string['emailto_help'] = 'Who to send the email to'; -$string['emailcontent'] = 'Content'; -$string['emailcontent_help'] = 'The content to use in the email'; -$string['emailactionstepname'] = 'Email'; -$string['emailactionstepdesc'] = 'A step to allow an e-mail to be sent'; +$string['erroreditstep'] = 'Something went wrong while attempting to save the workflow step. Please try again.'; +$string['errorimportworkflow'] = 'Something went wrong while importing the workflow. Please try again.'; $string['erroronfail'] = 'Error on failure'; $string['erroronfail_help'] = 'Set the step to error instead of fail'; +$string['errorsavingworkflow'] = 'Something went wrong while attempting to save the workflow. Please try again.'; +$string['errorstep'] = 'Errored step {$a}'; +$string['errorstepretrypending'] = '(Pending retry {$a})'; $string['event'] = 'Event'; $string['eventdescription'] = 'Event description'; $string['eventfields'] = 'Event fields'; $string['eventid'] = 'Event ID'; $string['eventtomonitor'] = 'Event to monitor'; $string['eventtomonitor_help'] = 'The Moodle event to trigger workflow on.'; -$string['erroreditstep'] = 'Something went wrong while attempting to save the workflow step. Please try again.'; -$string['errorimportworkflow'] = 'Something went wrong while importing the workflow. Please try again.'; -$string['errorsavingworkflow'] = 'Something went wrong while attempting to save the workflow. Please try again.'; -$string['errorstep'] = 'Errored step {$a}'; -$string['errorstepretrypending'] = '(Pending retry {$a})'; $string['executenext'] = 'Execute following step'; $string['executenextconfirm'] = 'Are you sure you wish to execute following step? It will execute based on the data from this step.'; $string['expectedresponse'] = 'Expected response code'; @@ -109,29 +112,29 @@ $string['filterdeferred'] = 'Deferred'; $string['filtererrored'] = 'Errored'; $string['filterfailed'] = 'Failed'; -$string['filterpassed'] = 'Passed'; $string['filterlabelrunstatus'] = 'Filter by run status'; $string['filterlabeluser'] = 'Filter by user name OR user ID'; +$string['filterpassed'] = 'Passed'; $string['filterreset'] = 'Reset'; $string['filtersubmit'] = 'Filter'; $string['historyduration'] = 'Duration to store trigger instances'; $string['historydurationdesc'] = 'This is the duration to store detailed trigger instances. After this period, it is no longer possible to rerun steps of the instance, or view step data.'; $string['historysettings'] = 'Workflow history settings'; $string['historysettingsdesc'] = 'These settings provide control over how the history of a workflow is stored.'; -$string['httpostactionurl'] = 'URL'; -$string['httpostactionurl_help'] = 'The URL to post the data to.'; -$string['httpostmethod'] = 'HTTP method'; -$string['httpostmethod_help'] = 'HTTP method for the given request.'; $string['httpostactionheaders'] = 'Headers'; $string['httpostactionheaders_help'] = 'The requests headers to send.'; $string['httpostactionparams'] = 'Parameters'; $string['httpostactionparams_help'] = 'The parameters to send with the request.'; -$string['httppostactionstepname'] = 'HTTP request'; +$string['httpostactionurl'] = 'URL'; +$string['httpostactionurl_help'] = 'The URL to post the data to.'; +$string['httpostmethod'] = 'HTTP method'; +$string['httpostmethod_help'] = 'HTTP method for the given request.'; $string['httppostactionstepdesc'] = 'A step to allow Moodle workflows to send data to a HTTP/S endpoint.'; +$string['httppostactionstepname'] = 'HTTP request'; $string['importmodaltitle'] = 'Import workflow from file'; $string['importworkflow'] = 'Import a workflow'; -$string['inputprefixuser'] = 'Prefix used for user lookup'; $string['inputprefixrole'] = 'Prefix used for role lookup'; +$string['inputprefixuser'] = 'Prefix used for user lookup'; $string['invalidjson'] = 'The workflow import file contains invalid JSON and could not be imported'; $string['invalidversion'] = 'The workflow import file is not valid with this version of the plugin'; $string['jsonencode'] = 'JSON encode parameters'; @@ -150,17 +153,19 @@ $string['manageworkflow'] = 'Manage workflow'; $string['messageprovider:tool_trigger'] = 'Event trigger notifications'; $string['modaltitle'] = 'Add workflow step.'; -$string['movestepup'] = 'Move step towards start'; $string['movestepdown'] = 'Move step towards end'; +$string['movestepup'] = 'Move step towards start'; $string['name'] = 'Name'; $string['newrunfailed'] = 'Run {$a->prev} was rerun as run {$a->new} and errored.'; $string['noavailablefields'] = 'No fields available, consider turning on learning mode.'; $string['noworkflowfile'] = 'No workflow file found'; $string['numsteps'] = 'Steps'; $string['outputprefix'] = 'Prefix for added fields'; +$string['pluginname'] = 'Event Trigger'; +$string['pluginname_help'] = 'Event Triggering for Moodle'; + $string['pluginsettings'] = 'Plugin Settings'; $string['prevstep'] = 'Previous step ID'; -$string['privacy:path:events'] = ''; $string['privacy:metadata:events'] = 'Data from monitored Moodle events'; $string['privacy:metadata:events:anonymous'] = 'Whether the event was flagged as anonymous'; $string['privacy:metadata:events:eventname'] = 'The event name'; @@ -171,7 +176,6 @@ $string['privacy:metadata:events:relateduserid'] = 'The ID of a user related to this event'; $string['privacy:metadata:events:timecreated'] = 'The time at which the event occurred'; $string['privacy:metadata:events:userid'] = 'The ID of the user who triggered this event'; -$string['privacy:path:learnevents'] = ''; $string['privacy:metadata:learnevents'] = 'Data from monitored Moodle learn events'; $string['privacy:metadata:learnevents:anonymous'] = 'Whether the learn event was flagged as anonymous'; $string['privacy:metadata:learnevents:eventname'] = 'The learn event name'; @@ -188,6 +192,8 @@ $string['privacy:metadata:workflowhistory'] = 'This table stores historical data of trigger runs, in order to allow for replaying trigger runs.'; $string['privacy:metadata:workflowhistory:event'] = 'An encoded event entry that triggered the trigger run.'; $string['privacy:metadata:workflowhistory:timecreated'] = 'The time that the trigger run was executed.'; +$string['privacy:path:events'] = ''; +$string['privacy:path:learnevents'] = ''; $string['queuelimit'] = 'Queue limit'; $string['queuelimitdesc'] = 'Max number of tasks to try and process in a queue.'; $string['queuesettings'] = 'Workflow queue settings'; @@ -197,6 +203,7 @@ $string['rerunallcurrconfirm'] = 'Are you sure you wish to re-run all errored runs using the current workflow configuration?'; $string['rerunallhist'] = 'Rerun all errored runs with historic configuration'; $string['rerunallhistconfirm'] = 'Are you sure you wish to re-run all errored runs using a historic workflow configuration?'; +$string['rerunerrors'] = 'All error runs have been rerun.'; $string['rerunstep'] = 'Re-run step'; $string['rerunstepandfinish'] = 'Re-run step and finish run'; $string['rerunstepandfinishconfirm'] = 'Are you sure you wish to re-run this step, and perform all steps until completing the run?'; @@ -205,104 +212,100 @@ $string['rerunstepconfirm'] = 'Are you sure you wish to re-run step? This will perform all actions from the step.'; $string['rerunworkflow'] = 'Re-run workflow'; $string['rerunworkflowconfirm'] = 'Are you sure you wish to re-run workflow with current workflow configuration? This will execute all steps based on the original event.'; -$string['roleassignactionstepname'] = 'Role assignment'; $string['roleassignactionstepdesc'] = 'Assign a role to a user in the given context'; +$string['roleassignactionstepname'] = 'Role assignment'; +$string['roleidfield'] = 'Role id data field'; +$string['roleidfield_help'] = 'You can use role id as a number or as a filed name from the workflow data'; +$string['rolesunassignactionstepdesc'] = 'A step to unassign all user role assignments.'; +$string['rolesunassignactionstepname'] = 'Roles unassignment'; +$string['roleunassignactionstepdesc'] = 'Unassign a role from a user in the given context'; $string['roleunassignactionstepname'] = 'Role unassignment'; -$string['roleunassignactionstepdesc'] = 'Unassign a role to a user in the given context'; +$string['runid'] = 'Run ID'; +$string['runpassed'] = 'Passed step {$a}'; +$string['runpassednonum'] = 'Passed'; +$string['runstatus'] = 'Run status'; +$string['step_action_email:privacy:desc'] = 'This plugin may be configured to send emails containing data from Moodle.'; +$string['step_action_httppost:privacy:desc'] = 'This plugin may be configured to send HTTP requests to external addresses, containing data from Moodle.'; +$string['step_action_logdump_desc'] = 'This step prints the event and workflow steps data to the cron log. (Mostly useful for testing.)'; +$string['step_action_logdump_name'] = 'Cron log'; +$string['step_action_role_assign_contextidfield'] = 'Context id data field'; +$string['step_action_role_assign_roleidfield'] = 'Role id data field'; +$string['step_action_role_assign_useridfield'] = 'User id data field'; +$string['step_action_role_unassign_contextidfield'] = 'Context id data field'; +$string['step_action_role_unassign_roleidfield'] = 'Role id data field'; +$string['step_action_role_unassign_useridfield'] = 'User id data field'; +$string['step_action_webservice:privacy:desc'] = 'This plugin may be configured to call webservice functions directly and so may handle data from Moodle depending on the function called.'; +$string['step_filter_fail_desc'] = 'A step that always fails. (Mostly useful for testing.)'; +$string['step_filter_fail_name'] = 'Fail'; +$string['step_lookup_category_categoryidfield'] = 'Category id data field'; +$string['step_lookup_category_desc'] = 'This step looks up data about a category.'; +$string['step_lookup_category_name'] = 'Category lookup'; +$string['step_lookup_cohort_desc'] = 'This step looks up cohort data for a user.'; +$string['step_lookup_cohort_name'] = 'Cohort lookup'; +$string['step_lookup_course:privacy:categorydata_desc'] = 'Data about course categories, including name, description etc.'; +$string['step_lookup_course:privacy:coursedata_desc'] = 'Data about courses, including id, course name, start and end dates, etc.'; +$string['step_lookup_course_courseidfield'] = 'Course id data field'; +$string['step_lookup_course_desc'] = 'This step looks up data about a course.'; +$string['step_lookup_course_name'] = 'Course lookup'; +$string['step_lookup_roles:privacy:userdata_desc'] = 'Data about user roles in various contexts.'; +$string['step_lookup_roles_desc'] = 'This step looks up user roles.'; +$string['step_lookup_roles_name'] = 'User roles lookup'; +$string['step_lookup_user:privacy:userdata_desc'] = 'Personal data about users, such as usernames, names, email addresses, etc.'; +$string['step_lookup_user_desc'] = 'This step looks up data about a user.'; +$string['step_lookup_user_name'] = 'User lookup'; +$string['step_lookup_user_nodeleted'] = 'Exit if user has been deleted?'; +$string['step_lookup_user_useridfield'] = 'User id data field'; $string['stepclass'] = 'Step'; $string['stepclass_help'] = 'Choose the step to apply.'; $string['stepdescription'] = 'Step description'; $string['stepdescription_help'] = 'A meaningful description for this step.'; $string['stepid'] = 'Step ID'; -$string['sttepidembed'] = 'Step ID: {$a}'; $string['stepmodalbutton'] = 'Add workflow step'; $string['stepname'] = 'Step name'; $string['stepname_help'] = 'The name of this step.'; +$string['stepnotfound'] = 'Step not found'; +$string['stepnumber'] = 'Step Number'; $string['steprequired'] = 'The workflow must have at least one step.'; $string['stepresults'] = 'Step results:'; $string['steptype'] = 'Step type'; $string['steptype_help'] = 'The type of step to apply.'; -$string['step_filter_fail_desc'] = 'A step that always fails. (Mostly useful for testing.)'; -$string['step_filter_fail_name'] = 'Fail'; -$string['step_lookup_cohort_desc'] = 'This step looks up cohort data for a user.'; -$string['step_lookup_cohort_name'] = 'Cohort lookup'; -$string['step_lookup_course:privacy:coursedata_desc'] = 'Data about courses, including id, course name, start and end dates, etc.'; -$string['step_lookup_course:privacy:categorydata_desc'] = 'Data about course categories, including name, description etc.'; -$string['step_lookup_course_desc'] = 'This step looks up data about a course.'; -$string['step_lookup_course_name'] = 'Course lookup'; -$string['step_lookup_course_courseidfield'] = 'Course id data field'; -$string['courseidfield'] = 'Course id data field'; -$string['courseidfield_help'] = 'You can use course id as a number or as a filed name from the workflow data'; -$string['step_lookup_category_desc'] = 'This step looks up data about a category.'; -$string['step_lookup_category_name'] = 'Category lookup'; -$string['step_lookup_category_categoryidfield'] = 'Category id data field'; -$string['categoryidfield'] = 'Category id data field'; -$string['categoryidfield_help'] = 'You can use category id as a number or as a filed name from the workflow data'; -$string['step_lookup_user:privacy:userdata_desc'] = 'Personal data about users, such as usernames, names, email addresses, etc.'; -$string['step_lookup_user_desc'] = 'This step looks up data about a user.'; -$string['step_lookup_user_nodeleted'] = 'Exit if user has been deleted?'; -$string['step_lookup_user_name'] = 'User lookup'; -$string['step_lookup_user_useridfield'] = 'User id data field'; +$string['sttepidembed'] = 'Step ID: {$a}'; -$string['step_lookup_roles:privacy:userdata_desc'] = 'Data about user roles in various contexts.'; -$string['step_lookup_roles_desc'] = 'This step looks up user roles.'; -$string['step_lookup_roles_name'] = 'User roles lookup'; -$string['step_action_email:privacy:desc'] = 'This plugin may be configured to send emails containing data from Moodle.'; -$string['step_action_httppost:privacy:desc'] = 'This plugin may be configured to send HTTP requests to external addresses, containing data from Moodle.'; -$string['step_action_logdump_desc'] = 'This step prints the event and workflow steps data to the cron log. (Mostly useful for testing.)'; -$string['step_action_logdump_name'] = 'Cron log'; -$string['step_action_role_assign_useridfield'] = 'User id data field'; -$string['step_action_role_unassign_useridfield'] = 'User id data field'; -$string['step_action_webservice:privacy:desc'] = 'This plugin may be configured to call webservice functions directly and so may handle data from Moodle depending on the function called.'; -$string['useridfield'] = 'User id data field'; -$string['useridfield_help'] = 'You can use user id as a number or as a filed name from the workflow data'; -$string['step_action_role_assign_roleidfield'] = 'Role id data field'; -$string['step_action_role_unassign_roleidfield'] = 'Role id data field'; -$string['rerunerrors'] = 'All error runs have been rerun.'; -$string['roleidfield'] = 'Role id data field'; -$string['roleidfield_help'] = 'You can use role id as a number or as a filed name from the workflow data'; -$string['runid'] = 'Run ID'; -$string['runpassed'] = 'Passed step {$a}'; -$string['runpassednonum'] = 'Passed'; -$string['runstatus'] = 'Run status'; -$string['step_action_role_assign_contextidfield'] = 'Context id data field'; -$string['step_action_role_unassign_contextidfield'] = 'Context id data field'; -$string['stepnotfound'] = 'Step not found'; -$string['stepnumber'] = 'Step Number'; -$string['contextidfield'] = 'Context id data field'; -$string['contextidfield_help'] = 'You can use context id as a number or as a filed name from the workflow data'; $string['taskcleanup'] = 'Delete old processed events'; $string['taskcleanuphistory'] = 'Delete historical trigger data'; $string['taskemptyhistoryconfig'] = 'Error: missing configuration for history duration. Exiting...'; $string['tasklearn'] = 'Learn about the fields in stored events.'; $string['tasklearnstart'] = 'Starting event field extraction processing...'; $string['taskprocessworkflows'] = 'Process workflows scheduled task.'; -$string['triggerhistory'] = 'History'; -$string['triggernumber'] = 'Trigger Number'; -$string['triggernumberembed'] = 'Trigger Number: {$a}'; -$string['trigger:exportrundetails'] = 'Download exported event-triggered run step history'; -$string['trigger:exportworkflowhistory'] = 'Download exported event-triggered workflow history'; -$string['trigger:manageworkflows'] = 'Create and configure automatic event-triggered workflows'; $string['timeexecuted'] = 'Time executed'; $string['timetocleanup'] = 'Time to cleanup old events'; $string['timetocleanup_help'] = 'This setting sets the time sucessfully executed workflows remain in the Moodle database prior to being removed.'; +$string['trigger:exportrundetails'] = 'Download exported event-triggered run step history'; +$string['trigger:exportworkflowhistory'] = 'Download exported event-triggered workflow history'; +$string['trigger:manageworkflows'] = 'Create and configure automatic event-triggered workflows'; +$string['triggerhistory'] = 'History'; +$string['triggernumber'] = 'Trigger Number'; +$string['triggernumberembed'] = 'Trigger Number: {$a}'; $string['update_trigger_helper_task'] = 'Adhoc task to offload upgrade processing work.'; +$string['useridfield'] = 'User id data field'; +$string['useridfield_help'] = 'You can use user id as a number or as a filed name from the workflow data'; +$string['viewdetailedrun'] = 'View run details'; +$string['viewstepinfo'] = 'View step information'; +$string['viewtriggerrun'] = 'View run'; $string['warningdebugging'] = 'Debug mode is disabled for the current workflow. To be able to record the history, you should enable debugging for the workflow.'; $string['webserviceactionfunctionname'] = 'Function'; $string['webserviceactionfunctionname_help'] = 'The webservice function to be called. See the API Documentation'; -$string['webserviceactionusername'] = 'Who'; -$string['webserviceactionusername_help'] = 'The user (username) who this step will be performed in the context of. This defaults to the main admin user if not explicitly set'; $string['webserviceactionparams'] = 'Parameters'; $string['webserviceactionparams_help'] = 'The function parameters - currently with support for JSON.'; -$string['webserviceactionstepname'] = 'Webservice Function'; $string['webserviceactionstepdesc'] = 'A step allowing the workflow to trigger web service functions.'; +$string['webserviceactionstepname'] = 'Webservice Function'; +$string['webserviceactionusername'] = 'Who'; +$string['webserviceactionusername_help'] = 'The user (username) who this step will be performed in the context of. This defaults to the main admin user if not explicitly set'; $string['workflowactive'] = 'Workflow active'; $string['workflowactive_help'] = 'Only active workflows will be processed when an event is triggered.'; -$string['workflowrealtime'] = 'Real time processing'; -$string['workflowrealtime_help'] = 'When enabled this workflow will be triggered synchronously as part of the event. Use caution when enabling as long running workflows will block the user interface.'; $string['workflowcopysuccess'] = 'Workflow successfully duplicated'; $string['workflowdebug'] = 'Debug mode'; $string['workflowdebug_help'] = 'Debug mode stores historical data about this workflow, for use in refining the workflow.'; @@ -310,18 +313,12 @@ $string['workflowdeletesuccess'] = 'Workflow successfully deleted'; $string['workflowdescription'] = 'Description'; $string['workflowdescription_help'] = 'A short description of this workflows purpose.'; +$string['workflowfile'] = 'Workflow file'; $string['workflowid'] = 'Workflow ID: {$a}'; $string['workflowimported'] = 'Workflow successfully imported'; -$string['workflowfile'] = 'Workflow file'; $string['workflowname'] = 'Name'; $string['workflowname_help'] = 'The human readable name for this workflow.'; $string['workflowoverview'] = 'Workflow overview'; +$string['workflowrealtime'] = 'Real time processing'; +$string['workflowrealtime_help'] = 'When enabled this workflow will be triggered synchronously as part of the event. Use caution when enabling as long running workflows will block the user interface.'; $string['workflowviewhistory'] = 'View workflow history'; -$string['viewtriggerrun'] = 'View run'; -$string['viewdetailedrun'] = 'View run details'; -$string['viewstepinfo'] = 'View step information'; - -$string['roleunassignactionstepname'] = 'Role unassignment'; -$string['roleunassignactionstepdesc'] = 'A step to unassign a specific user role assignment.'; -$string['rolesunassignactionstepname'] = 'Roles unassignment'; -$string['rolesunassignactionstepdesc'] = 'A step to unassign all user role assignments.'; diff --git a/lib.php b/lib.php index 5724fea..b5e612b 100644 --- a/lib.php +++ b/lib.php @@ -72,17 +72,17 @@ function tool_trigger_output_fragment_new_step_form($args) { $workflowmanager = new \tool_trigger\workflow_manager(); $stepclassobj = $workflowmanager->validate_and_make_step($stepclass); - $customdata = array( + $customdata = [ 'type' => $steptype, 'stepclass' => $stepclass, 'steptext' => $stepclass::get_step_name(), 'steps' => $workflowmanager->get_steps_by_type($steptype), 'event' => $event, 'existingsteps' => $existingsteps, - 'steporder' => $steporder - ); + 'steporder' => $steporder, + ]; - $ajaxformdata = array(); + $ajaxformdata = []; if (!empty($args['ajaxformdata'])) { // Don't need to clean/validate these, because formslib will do that. parse_str($args['ajaxformdata'], $ajaxformdata); diff --git a/manage.php b/manage.php index 3457298..b08adcc 100644 --- a/manage.php +++ b/manage.php @@ -29,7 +29,7 @@ require_login(); -admin_externalpage_setup('tool_trigger_worfklowsettings', '', null, '', array('pagelayout' => 'report')); +admin_externalpage_setup('tool_trigger_worfklowsettings', '', null, '', ['pagelayout' => 'report']); $context = context_system::instance(); @@ -37,7 +37,7 @@ require_capability('tool/trigger:manageworkflows', $context); // Load the javascript. -$PAGE->requires->js_call_amd('tool_trigger/import_workflow', 'init', array($context->id)); +$PAGE->requires->js_call_amd('tool_trigger/import_workflow', 'init', [$context->id]); // Build the page output. echo $OUTPUT->header(); diff --git a/manageworkflow.php b/manageworkflow.php index cb2c7b5..2db9f56 100644 --- a/manageworkflow.php +++ b/manageworkflow.php @@ -89,7 +89,7 @@ 'workflowid' => $workflowid, 'action' => 'delete', 'confirm' => true, - 'sesskey' => sesskey() + 'sesskey' => sesskey(), ] ); $cancelurl = new moodle_url($CFG->wwwroot. '/admin/tool/trigger/manage.php'); diff --git a/stepdetails.php b/stepdetails.php index 1392f33..9a3b82f 100644 --- a/stepdetails.php +++ b/stepdetails.php @@ -24,7 +24,7 @@ require_once(__DIR__ . '/../../../config.php'); require_once($CFG->libdir . '/adminlib.php'); -admin_externalpage_setup('tool_trigger_worfklowsettings', '', null, '', array('pagelayout' => 'report')); +admin_externalpage_setup('tool_trigger_worfklowsettings', '', null, '', ['pagelayout' => 'report']); $context = context_system::instance(); $PAGE->set_url(new moodle_url('/admin/tool/trigger/stepdetails.php')); diff --git a/tests/course_cat_lookup_step_test.php b/tests/course_cat_lookup_step_test.php index 3b06455..763ab2f 100644 --- a/tests/course_cat_lookup_step_test.php +++ b/tests/course_cat_lookup_step_test.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + /** * Course category look up tests. * @@ -22,33 +24,30 @@ * @copyright 2019 Catalyst IT * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -class course_cat_lookup_step_test extends \advanced_testcase { +final class course_cat_lookup_step_test extends \advanced_testcase { /** * Test user. - * @var + * @var \stdClass */ protected $user; /** * Test category. - * @var + * @var \stdClass */ protected $category; /** * Test event. - * @var + * @var \core\event\course_category_created */ protected $event; /** * Initial set up. */ - public function setUp():void { + public function setUp(): void { parent::setUp(); $this->resetAfterTest(true); @@ -69,7 +68,7 @@ public function setUp():void { /** * Test fields list. */ - public function test_get_fields() { + public function test_get_fields(): void { $expected = [ 'id', 'name', @@ -94,11 +93,11 @@ public function test_get_fields() { * Find the category identified at "objectid", and add their data with the * prefix "category_". */ - public function test_execute_basic() { + public function test_execute_basic(): void { $step = new \tool_trigger\steps\lookups\course_cat_lookup_step( json_encode([ 'categoryidfield' => 'objectid', - 'outputprefix' => 'category_' + 'outputprefix' => 'category_', ]) ); @@ -114,11 +113,11 @@ public function test_execute_basic() { /** * Test for exception if an invalid field name is entered. */ - public function test_execute_nosuchfield() { + public function test_execute_nosuchfield(): void { $step = new \tool_trigger\steps\lookups\course_cat_lookup_step( json_encode([ 'categoryidfield' => 'nosuchfield', - 'outputprefix' => 'category_' + 'outputprefix' => 'category_', ]) ); @@ -129,7 +128,7 @@ public function test_execute_nosuchfield() { /** * Test for failure if a category is no longer present in the database. */ - public function test_execute_no_such_category() { + public function test_execute_no_such_category(): void { global $DB; $DB->delete_records('course_categories', ['id' => $this->category->id]); @@ -137,7 +136,7 @@ public function test_execute_no_such_category() { $step = new \tool_trigger\steps\lookups\course_cat_lookup_step( json_encode([ 'categoryidfield' => 'objectid', - 'outputprefix' => 'category_' + 'outputprefix' => 'category_', ]) ); @@ -149,7 +148,7 @@ public function test_execute_no_such_category() { * Data provided to test hardcoded category id. * @return array */ - public function hardcoded_category_id_data_provider() { + public function hardcoded_category_id_data_provider(): array { return [ 'Non-existing category id.' => [ @@ -180,11 +179,11 @@ public function hardcoded_category_id_data_provider() { * * @dataProvider hardcoded_category_id_data_provider */ - public function test_execute_category_id($categoryid, $status, $exception) { + public function test_execute_category_id($categoryid, $status, $exception): void { $step = new \tool_trigger\steps\lookups\course_cat_lookup_step( json_encode([ 'categoryidfield' => $categoryid, - 'outputprefix' => 'category_' + 'outputprefix' => 'category_', ]) ); @@ -209,11 +208,11 @@ public function test_execute_category_id($categoryid, $status, $exception) { /** * Test dynamic category id as int. */ - public function test_execute_category_id_integer() { + public function test_execute_category_id_integer(): void { $step = new \tool_trigger\steps\lookups\course_cat_lookup_step( json_encode([ 'categoryidfield' => $this->category->id, - 'outputprefix' => 'category_' + 'outputprefix' => 'category_', ]) ); @@ -229,11 +228,11 @@ public function test_execute_category_id_integer() { /** * Test dynamic category id as string. */ - public function test_execute_category_id_string() { + public function test_execute_category_id_string(): void { $step = new \tool_trigger\steps\lookups\course_cat_lookup_step( json_encode([ 'categoryidfield' => (string) $this->category->id, - 'outputprefix' => 'category_' + 'outputprefix' => 'category_', ]) ); diff --git a/tests/course_lookup_step_test.php b/tests/course_lookup_step_test.php index ac21c1c..c898e35 100644 --- a/tests/course_lookup_step_test.php +++ b/tests/course_lookup_step_test.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + /** * "Fail" filter step's unit tests. * @@ -22,20 +24,17 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -class course_lookup_step_test extends \advanced_testcase { +final class course_lookup_step_test extends \advanced_testcase { /** * Test user. - * @var + * @var \stdClass */ protected $user; /** - * Test user. - * @var + * Test course. + * @var \stdClass */ protected $course; @@ -49,7 +48,7 @@ class course_lookup_step_test extends \advanced_testcase { * Create a "user_profile_viewed" event, of user1 viewing user2's * profile. And then run everything else as the cron user. */ - public function setup():void { + public function setup(): void { $this->resetAfterTest(true); $this->user = \core_user::get_user_by_username('admin'); $this->course = $this->getDataGenerator()->create_course(); @@ -61,8 +60,8 @@ public function setup():void { 'context' => \context_course::instance($this->course->id), 'other' => [ 'shortname' => $this->course->shortname, - 'fullname' => $this->course->fullname - ] + 'fullname' => $this->course->fullname, + ], ]); // Run as the cron user . @@ -73,11 +72,11 @@ public function setup():void { * Find the course identified at "objectid", and add their data with the * prefix "course_". */ - public function test_execute_basic() { + public function test_execute_basic(): void { $step = new \tool_trigger\steps\lookups\course_lookup_step( json_encode([ 'courseidfield' => 'objectid', - 'outputprefix' => 'course_' + 'outputprefix' => 'course_', ]) ); @@ -93,11 +92,11 @@ public function test_execute_basic() { /** * Test for exception if an invalid field name is entered. */ - public function test_execute_nosuchfield() { + public function test_execute_nosuchfield(): void { $step = new \tool_trigger\steps\lookups\course_lookup_step( json_encode([ 'courseidfield' => 'nosuchfield', - 'outputprefix' => 'course_' + 'outputprefix' => 'course_', ]) ); @@ -108,13 +107,13 @@ public function test_execute_nosuchfield() { /** * Test for failure if a course is no longer present in the database. */ - public function test_execute_nosuchcourse() { + public function test_execute_nosuchcourse(): void { delete_course($this->course, false); $step = new \tool_trigger\steps\lookups\course_lookup_step( json_encode([ 'courseidfield' => 'objectid', - 'outputprefix' => 'course_' + 'outputprefix' => 'course_', ]) ); @@ -126,7 +125,7 @@ public function test_execute_nosuchcourse() { * Data provided to test hardcoded category id. * @return array */ - public function hardcoded_course_id_data_provider() { + public function hardcoded_course_id_data_provider(): array { return [ 'Non-existing Course id.' => [ @@ -157,11 +156,11 @@ public function hardcoded_course_id_data_provider() { * * @dataProvider hardcoded_course_id_data_provider */ - public function test_execute_course_id($courseid, $status, $exception) { + public function test_execute_course_id($courseid, $status, $exception): void { $step = new \tool_trigger\steps\lookups\course_lookup_step( json_encode([ 'courseidfield' => $courseid, - 'outputprefix' => 'course_' + 'outputprefix' => 'course_', ]) ); @@ -186,11 +185,11 @@ public function test_execute_course_id($courseid, $status, $exception) { /** * Test for exception if course id entered directly with dynamic id as integer. */ - public function test_execute_course_id_integer() { + public function test_execute_course_id_integer(): void { $step = new \tool_trigger\steps\lookups\course_lookup_step( json_encode([ 'courseidfield' => $this->course->id, - 'outputprefix' => 'course_' + 'outputprefix' => 'course_', ]) ); @@ -206,11 +205,11 @@ public function test_execute_course_id_integer() { /** * Test for exception if course id entered directly with dynamic id as string. */ - public function test_execute_course_id_string() { + public function test_execute_course_id_string(): void { $step = new \tool_trigger\steps\lookups\course_lookup_step( json_encode([ 'courseidfield' => (string)$this->course->id, - 'outputprefix' => 'course_' + 'outputprefix' => 'course_', ]) ); diff --git a/tests/datafield_manager_test.php b/tests/datafield_manager_test.php index f16f917..ccaad91 100644 --- a/tests/datafield_manager_test.php +++ b/tests/datafield_manager_test.php @@ -14,6 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once(__DIR__.'/fixtures/user_event_fixture.php'); + /** * Test of the datafield_manager trait * @@ -22,15 +29,7 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -defined('MOODLE_INTERNAL') || die(); - -global $CFG; -require_once(__DIR__.'/fixtures/user_event_fixture.php'); - -class datafield_manager_test extends \advanced_testcase { +final class datafield_manager_test extends \advanced_testcase { use \tool_trigger_user_event_fixture; /** @@ -44,7 +43,7 @@ public function setup(): void { /** * Test that all the datafields are correctly generated. */ - public function test_get_datafields() { + public function test_get_datafields(): void { $stepdata = ['foo' => 'bar']; // Tell PHPUnit to create a generic object that uses this trait. Handy! @@ -97,7 +96,7 @@ public function test_get_datafields() { * - multiple instances of the same tag, in the template * - some non-existent tags in the template (which should be left in place) */ - public function test_render_datafields() { + public function test_render_datafields(): void { $stepdata = [ 'tagnotused' => 'valuenotused', 'tagexists' => 'tagvalue', @@ -145,7 +144,7 @@ public function test_render_datafields() { public function test_render_datafields_transformcallback() { $stepdata = [ 'tagnotused' => 'valuenotused', - 'tagexists' => 'tagvalue' + 'tagexists' => 'tagvalue', ]; $templatestring = 'Tag: {tagexists}'; diff --git a/tests/debounce_step_test.php b/tests/debounce_step_test.php index 9ef4ba9..f86ea2a 100644 --- a/tests/debounce_step_test.php +++ b/tests/debounce_step_test.php @@ -14,6 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once("$CFG->libdir/gradelib.php"); + /** * Debounce filter step's unit test * @@ -22,15 +29,7 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -defined('MOODLE_INTERNAL') || die(); - -global $CFG; -require_once("$CFG->libdir/gradelib.php"); - -class debounce_step_test extends \advanced_testcase { +final class debounce_step_test extends \advanced_testcase { /** * The step to execute. * @@ -40,6 +39,8 @@ class debounce_step_test extends \advanced_testcase { /** * EventID to keep track of. + * + * @var int */ private $eventid; @@ -53,7 +54,7 @@ class debounce_step_test extends \advanced_testcase { * Create a "user_profile_viewed" event, of user1 viewing user2's * profile. And then run everything else as the cron user. */ - public function setup():void { + public function setup(): void { global $DB; $this->resetAfterTest(true); @@ -68,7 +69,7 @@ public function setup():void { $gradeitem->update_final_grade($user->id, 10, 'gradebook'); - $gradegrade = new \grade_grade(array('userid' => $user->id, 'itemid' => $gradeitem->id), true); + $gradegrade = new \grade_grade(['userid' => $user->id, 'itemid' => $gradeitem->id], true); $gradegrade->grade_item = $gradeitem; $this->event = \core\event\user_graded::create_from_grade($gradegrade); @@ -100,13 +101,13 @@ private function get_mock_queue_item() { 'tries' => 0, 'laststep' => 1, 'timecreated' => time(), - 'timemodified' => time() + 'timemodified' => time(), ], true); return $DB->get_record('tool_trigger_queue', ['id' => $id]); } - public function test_event_queue() { + public function test_event_queue(): void { global $DB; // Scenario 1: No existing event queue. @@ -153,7 +154,7 @@ public function test_event_queue() { $this->assertTrue($end->executiontime >= time()); } - public function test_event_cancellation() { + public function test_event_cancellation(): void { global $DB; // Scenario 1: 2 event, run lower diff --git a/tests/email_action_step_test.php b/tests/email_action_step_test.php index 6747ac5..caa8a30 100644 --- a/tests/email_action_step_test.php +++ b/tests/email_action_step_test.php @@ -14,6 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once(__DIR__.'/fixtures/user_event_fixture.php'); + /** * Test of the email action * @@ -22,15 +29,7 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -defined('MOODLE_INTERNAL') || die(); - -global $CFG; -require_once(__DIR__.'/fixtures/user_event_fixture.php'); - -class email_action_step_test extends \advanced_testcase { +final class email_action_step_test extends \advanced_testcase { use \tool_trigger_user_event_fixture; /** @@ -43,7 +42,7 @@ class email_action_step_test extends \advanced_testcase { * Create a "user_profile_viewed" event, of user1 viewing user2's * profile. And then run everything else as the cron user. */ - public function setup():void { + public function setup(): void { $this->setup_user_event(); // Set up the email sync. @@ -51,12 +50,12 @@ public function setup():void { $this->sink = $this->redirectMessages(); } - public function test_execute_basic() { + public function test_execute_basic(): void { $settings = [ 'emailto' => $this->user1->email, 'emailsubject' => 'Subject of the email', 'emailcontent_editor[text]' => 'Content of the email', - 'emailcontent_editor[format]' => 0 + 'emailcontent_editor[format]' => 0, ]; $step = new \tool_trigger\steps\actions\email_action_step(json_encode($settings)); @@ -88,12 +87,12 @@ public function test_execute_basic() { ); } - public function test_execute_external_email_address() { + public function test_execute_external_email_address(): void { $settings = [ 'emailto' => 'testusernotinmoodle@example.com', 'emailsubject' => 'Subject of the email', 'emailcontent_editor[text]' => 'Content of the email', - 'emailcontent_editor[format]' => 0 + 'emailcontent_editor[format]' => 0, ]; $step = new \tool_trigger\steps\actions\email_action_step(json_encode($settings)); @@ -119,7 +118,7 @@ public function test_execute_external_email_address() { ); } - public function test_execute_with_datafields() { + public function test_execute_with_datafields(): void { $settings = [ 'emailto' => '{user_email}', 'emailsubject' => 'User {userid} looked at your profile', @@ -131,7 +130,7 @@ public function test_execute_with_datafields() { $prevstepresults = [ // In practice, this value would have been added by a previous user_lookup step. - 'user_email' => $this->user2->email + 'user_email' => $this->user2->email, ]; // Run the step. diff --git a/tests/event_processor_test.php b/tests/event_processor_test.php index d9af662..441016f 100644 --- a/tests/event_processor_test.php +++ b/tests/event_processor_test.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Event processor unit tests. - * - * @package tool_trigger - * @copyright Matt Porritt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; defined('MOODLE_INTERNAL') || die(); @@ -37,35 +29,34 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -class event_processor_test extends \tool_trigger_testcase { +final class event_processor_test extends \tool_trigger_testcase { /** * Event array. - * @var + * @var array */ protected $eventarr; /** * Test user. - * @var + * @var \stdClass */ protected $user; /** * Test context. - * @var + * @var \context */ protected $context; - public function setup():void { + public function setup(): void { $this->resetAfterTest(true); // Create an event. This _is_ easier to do via direct DB insertions. $user = $this->getDataGenerator()->create_user(); $context = \context_system::instance(); - $eventarr = array( + $eventarr = [ 'objectid' => $user->id, 'contextid' => $context->id, 'userid' => $user->id, @@ -74,7 +65,7 @@ public function setup():void { 'anonymous' => 0, 'other' => ['username' => $user->username], - ); + ]; $this->eventarr = $eventarr; $this->user = $user; @@ -84,7 +75,7 @@ public function setup():void { \core\cron::setup_user(); } - public function tearDown():void { + public function tearDown(): void { global $DB; // Manually clear all related DB tables. Avoids voodoo failing tests. $DB->delete_records('tool_trigger_run_hist', []); @@ -94,13 +85,14 @@ public function tearDown():void { // Purge caches that may cause issues with events being ignored. \cache_helper::purge_by_definition('tool_trigger', 'eventsubscriptions'); + parent::tearDown(); } /** * Test is event ignored. * Test event with no associated workflow is ignored. */ - public function test_is_event_ignored() { + public function test_is_event_ignored(): void { $event = \core\event\user_loggedin::create($this->eventarr); @@ -116,7 +108,7 @@ public function test_is_event_ignored() { * Test is event ignored. * Test event with no associated workflow is NOT ignored. */ - public function test_is_event_ignored_false() { + public function test_is_event_ignored_false(): void { $this->create_workflow(); // Add a workflow to the database. $event = \core\event\user_loggedin::create($this->eventarr); @@ -132,7 +124,7 @@ public function test_is_event_ignored_false() { /** * Test is prepare event data when learning mode is false. */ - public function test_prepare_event() { + public function test_prepare_event(): void { $event = \core\event\user_loggedin::create($this->eventarr); // We're testing a protected method, so we need to setup reflector magic. @@ -148,7 +140,7 @@ public function test_prepare_event() { * Test processing event. * Ensure details for a non ignored event end up in database. */ - public function test_process_event_add_event_to_db() { + public function test_process_event_add_event_to_db(): void { global $DB; $this->create_workflow(); @@ -164,7 +156,7 @@ public function test_process_event_add_event_to_db() { * Test processing real time event. * Ensure realtime event processed and timetriggered updated in DB. */ - public function test_process_realtime_workflow() { + public function test_process_realtime_workflow(): void { global $DB; $now = time(); @@ -187,7 +179,7 @@ public function test_process_realtime_workflow() { /** * Test processing real time event with an error will add a message to a queue to process later. */ - public function test_process_realtime_workflow_save_to_queue_if_failed() { + public function test_process_realtime_workflow_save_to_queue_if_failed(): void { global $DB; $now = time(); @@ -200,7 +192,7 @@ public function test_process_realtime_workflow_save_to_queue_if_failed() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'broken_field', // This should trigger exception on look up step. - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], ]; @@ -220,7 +212,7 @@ public function test_process_realtime_workflow_save_to_queue_if_failed() { $this->assertGreaterThanOrEqual($now, $timetriggered); } - public function test_record_workflow_trigger() { + public function test_record_workflow_trigger(): void { // Perform basic workflow setup, with debug mode disabled. global $DB; $workflowid = $this->create_workflow(1); @@ -260,7 +252,7 @@ public function test_record_workflow_trigger() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'broken_field', // This should trigger exception on look up step. - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], ]; // Now create a new indentical WF, and check that only 1 set of events is logged. @@ -277,7 +269,7 @@ public function test_record_workflow_trigger() { $this->assertEquals(1, $histrecord2->number); } - public function test_record_step_trigger() { + public function test_record_step_trigger(): void { // Perform basic workflow setup, with debug mode disabled. global $DB; $this->create_workflow(1); @@ -299,7 +291,7 @@ public function test_record_step_trigger() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -309,8 +301,8 @@ public function test_record_step_trigger() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; // Now create a workflow with debug mode enabled. @@ -351,7 +343,7 @@ public function test_record_step_trigger() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -361,8 +353,8 @@ public function test_record_step_trigger() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'broken_field', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $brokensteps, 1); @@ -374,7 +366,7 @@ public function test_record_step_trigger() { $this->assertEquals(2, $countrunhist3); } - public function test_execute_current_step() { + public function test_execute_current_step(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -386,7 +378,7 @@ public function test_execute_current_step() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -396,8 +388,8 @@ public function test_execute_current_step() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $steps, 1); @@ -439,7 +431,7 @@ public function test_execute_current_step() { $this->assertNotEquals($secondstep->description, $newstep->description); } - public function test_execute_historic_step() { + public function test_execute_historic_step(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -451,7 +443,7 @@ public function test_execute_historic_step() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -461,8 +453,8 @@ public function test_execute_historic_step() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $steps, 1); @@ -497,7 +489,7 @@ public function test_execute_historic_step() { $this->assertEquals($secondstep->prevstepid, $newstep->prevstepid); } - public function test_execute_next_step_current() { + public function test_execute_next_step_current(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -509,7 +501,7 @@ public function test_execute_next_step_current() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -519,8 +511,8 @@ public function test_execute_next_step_current() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $steps, 1); @@ -554,7 +546,7 @@ public function test_execute_next_step_current() { $this->assertNotEquals($secondstep->description, $thirdstep->description); } - public function test_execute_next_step_historic() { + public function test_execute_next_step_historic(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -566,7 +558,7 @@ public function test_execute_next_step_historic() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 0, @@ -576,8 +568,8 @@ public function test_execute_next_step_historic() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $steps, 1); @@ -606,7 +598,7 @@ public function test_execute_next_step_historic() { $this->assertEquals($secondstep->prevstepid, $thirdstep->prevstepid); } - public function test_execute_step_and_continue_current() { + public function test_execute_step_and_continue_current(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -618,7 +610,7 @@ public function test_execute_step_and_continue_current() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -630,8 +622,8 @@ public function test_execute_step_and_continue_current() { 'emailto' => 'testusernotinmoodle@example.com', 'emailsubject' => 'Subject of the email', 'emailcontent_editor[text]' => 'Content of the email', - 'emailcontent_editor[format]' => 0 - ] + 'emailcontent_editor[format]' => 0, + ], ]; $this->create_workflow(1, $steps, 1); @@ -697,7 +689,7 @@ public function test_execute_step_and_continue_current() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -709,7 +701,7 @@ public function test_execute_step_and_continue_current() { 'emailto' => 'testusernotinmoodle@example.com', 'emailsubject' => 'Subject of the email', 'emailcontent_editor[text]' => 'Content of the email', - 'emailcontent_editor[format]' => 0 + 'emailcontent_editor[format]' => 0, ], [ 'id' => 2, @@ -721,7 +713,7 @@ public function test_execute_step_and_continue_current() { 'emailto' => 'testusernotinmoodle@example.com', 'emailsubject' => 'Subject of the email', 'emailcontent_editor[text]' => 'Content of the email', - 'emailcontent_editor[format]' => 0 + 'emailcontent_editor[format]' => 0, ], [ 'id' => 3, @@ -733,8 +725,8 @@ public function test_execute_step_and_continue_current() { 'emailto' => 'testusernotinmoodle@example.com', 'emailsubject' => 'Subject of the email', 'emailcontent_editor[text]' => 'Content of the email', - 'emailcontent_editor[format]' => 0 - ] + 'emailcontent_editor[format]' => 0, + ], ]; $this->create_workflow(1, $longsteps, 1); \tool_trigger\event_processor::process_event($event); @@ -765,7 +757,7 @@ public function test_execute_step_and_continue_current() { $this->assertEquals(8, count($fouthrecords)); } - public function test_execute_step_and_continue_historic() { + public function test_execute_step_and_continue_historic(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -777,7 +769,7 @@ public function test_execute_step_and_continue_historic() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -787,8 +779,8 @@ public function test_execute_step_and_continue_historic() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $steps, 1); @@ -845,7 +837,7 @@ public function test_execute_step_and_continue_historic() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -855,7 +847,7 @@ public function test_execute_step_and_continue_historic() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' + 'outputprefix' => 'user2_', ], [ 'id' => 2, @@ -865,7 +857,7 @@ public function test_execute_step_and_continue_historic() { 'name' => 'Get user data3', 'description' => 'Get user data3', 'useridfield' => 'userid', - 'outputprefix' => 'user3_' + 'outputprefix' => 'user3_', ], [ 'id' => 3, @@ -875,8 +867,8 @@ public function test_execute_step_and_continue_historic() { 'name' => 'Get user data4', 'description' => 'Get user data4', 'useridfield' => 'userid', - 'outputprefix' => 'user4_' - ] + 'outputprefix' => 'user4_', + ], ]; $this->create_workflow(1, $longsteps, 1); \tool_trigger\event_processor::process_event($event); @@ -904,7 +896,7 @@ public function test_execute_step_and_continue_historic() { $this->assertEquals(8, count($fouthrecords)); } - public function test_execute_workflow_from_event_current() { + public function test_execute_workflow_from_event_current(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -916,7 +908,7 @@ public function test_execute_workflow_from_event_current() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -926,8 +918,8 @@ public function test_execute_workflow_from_event_current() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $steps, 1); @@ -967,7 +959,7 @@ public function test_execute_workflow_from_event_current() { $this->assertEquals('New description', $secondstep->description); } - public function test_execute_workflow_from_event_historic() { + public function test_execute_workflow_from_event_historic(): void { // Perform basic workflow setup, with debug mode enabled. global $DB; $steps = [ @@ -979,7 +971,7 @@ public function test_execute_workflow_from_event_historic() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -989,8 +981,8 @@ public function test_execute_workflow_from_event_historic() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $this->create_workflow(1, $steps, 1); @@ -1018,7 +1010,7 @@ public function test_execute_workflow_from_event_historic() { $this->assertEquals($firstruncount, $secondruncount); } - public function test_rerun_all_error_runs() { + public function test_rerun_all_error_runs(): void { global $DB; set_config('historyduration', 14 * DAYSECS, 'tool_trigger'); @@ -1033,7 +1025,7 @@ public function test_rerun_all_error_runs() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 1, @@ -1043,8 +1035,8 @@ public function test_rerun_all_error_runs() { 'name' => 'Get user data2', 'description' => 'Get user data2', 'useridfield' => 'userid', - 'outputprefix' => 'user2_' - ] + 'outputprefix' => 'user2_', + ], ]; $wfid = $this->create_workflow(1, $goodsteps, 1); @@ -1079,7 +1071,7 @@ public function test_rerun_all_error_runs() { 'field1' => 123, 'operator' => '==', 'field2' => 456, - ] + ], ]; // New workflow with these steps. @@ -1115,7 +1107,7 @@ public function test_rerun_all_error_runs() { 'field1' => 123, 'operator' => 'invalid operator', 'field2' => 456, - ] + ], ]; // New workflow with these steps. @@ -1159,7 +1151,7 @@ public function test_rerun_all_error_runs() { $this->assertEquals($insertedid, $third->id); } - public function test_cleanup_history() { + public function test_cleanup_history(): void { global $DB; $this->resetAfterTest(); diff --git a/tests/fail_filter_step_test.php b/tests/fail_filter_step_test.php index 16b9384..c4c0bd0 100644 --- a/tests/fail_filter_step_test.php +++ b/tests/fail_filter_step_test.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + /** * "Fail" filter step's unit tests. * @@ -22,11 +24,8 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -class fail_filter_step_test extends \basic_testcase { - public function test_execute() { +final class fail_filter_step_test extends \basic_testcase { + public function test_execute(): void { $step = new \tool_trigger\steps\filters\fail_filter_step(); list($status) = $step->execute(null, null, null, null); $this->assertFalse($status); diff --git a/tests/fixtures/user_event_fixture.php b/tests/fixtures/user_event_fixture.php index 4aa0931..f0a03a6 100644 --- a/tests/fixtures/user_event_fixture.php +++ b/tests/fixtures/user_event_fixture.php @@ -14,6 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +defined('MOODLE_INTERNAL') || die(); + +global $CFG; + /** * A lot of our tests need to go through a similar set of steps to * create an event. This is a trait that does so. @@ -23,15 +27,29 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -defined('MOODLE_INTERNAL') || die(); - -global $CFG; - trait tool_trigger_user_event_fixture { + /** + * User 1. + * @var ?\stdClass + */ public $user1 = null; + + /** + * User 2. + * @var ?\stdClass + */ public $user2 = null; + + /** + * Course. + * @var ?\stdClass + */ public $course = null; + + /** + * Event. + * @var mixed + */ public $event = null; /** @@ -47,7 +65,7 @@ public function setup_user_event() { 'descriptionformat' => FORMAT_HTML, 'url' => 'https://www.example.com', 'picture' => 1, - 'password' => 'af98y4hqkfhacvaHKHDFSs' + 'password' => 'af98y4hqkfhacvaHKHDFSs', ]; $this->user1 = $this->getDataGenerator()->create_user($extrauserdata); @@ -65,7 +83,7 @@ public function setup_user_event() { 'courseshortname' => $this->course->shortname, 'coursefullname' => $this->course->fullname, 'eventid' => 1, - ] + ], ]); $this->event->trigger(); diff --git a/tests/http_post_action_step_test.php b/tests/http_post_action_step_test.php index 35f1876..a9cf779 100644 --- a/tests/http_post_action_step_test.php +++ b/tests/http_post_action_step_test.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + /** * Test of the HTTP POST action step. * @@ -22,30 +24,27 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -class http_post_action_step_test extends \advanced_testcase { +final class http_post_action_step_test extends \advanced_testcase { /** * Test user. - * @var + * @var \stdClass */ protected $user; /** * A list of sent requests. - * @var + * @var array */ protected $requestssent; /** * Test event. - * @var + * @var \core\event\user_profile_viewed */ protected $event; - public function setup():void { + public function setup(): void { $this->resetAfterTest(true); $this->requestssent = []; @@ -57,8 +56,8 @@ public function setup():void { 'other' => [ 'courseid' => 1, 'courseshortname' => 'short name', - 'coursefullname' => 'full name' - ] + 'coursefullname' => 'full name', + ], ]); // Run as the cron user . @@ -80,7 +79,7 @@ private function make_mock_http_handler($response) { /** * Test supported HTTP methods. */ - public function test_supported_http_methods() { + public function test_supported_http_methods(): void { $expected = [ 'POST' => 'POST', 'GET' => 'GET', @@ -95,12 +94,12 @@ public function test_supported_http_methods() { * Test that POST method is set as default if no httpmethod set for the step class. * This is to make sure that steps created before httpmethod was introduced will get it by default. */ - public function test_if_httpmethod_is_not_set_post_method_set_as_default() { + public function test_if_httpmethod_is_not_set_post_method_set_as_default(): void { $stepsettings = [ 'url' => 'http://http_post_action_step.example.com', 'httpheaders' => 'My-Special-Header: {headervalue}', 'httpparams' => '', - 'jsonencode' => '0' + 'jsonencode' => '0', ]; $step = new \tool_trigger\steps\actions\http_post_action_step(json_encode($stepsettings)); @@ -132,13 +131,13 @@ public function http_methods_data_provider(): array { * @dataProvider http_methods_data_provider * @param string $httpmethod */ - public function test_execute_200(string $httpmethod) { + public function test_execute_200(string $httpmethod): void { $stepsettings = [ 'url' => 'http://http_post_action_step.example.com', 'httpmethod' => $httpmethod, 'httpheaders' => 'My-Special-Header: {headervalue}', 'httpparams' => '', - 'jsonencode' => '0' + 'jsonencode' => '0', ]; $step = new \tool_trigger\steps\actions\http_post_action_step(json_encode($stepsettings)); @@ -161,14 +160,14 @@ public function test_execute_200(string $httpmethod) { * @dataProvider http_methods_data_provider * @param string $httpmethod */ - public function test_execute_404(string $httpmethod) { + public function test_execute_404(string $httpmethod): void { $stepsettings = [ 'url' => 'http://http_post_action_step.example.com/badurl', 'httpmethod' => $httpmethod, 'httpheaders' => 'My-Special-Header: {headervalue}', 'httpparams' => '', 'jsonencode' => '0', - 'expectedresponse' => 404 + 'expectedresponse' => 404, ]; $step = new \tool_trigger\steps\actions\http_post_action_step(json_encode($stepsettings)); @@ -189,12 +188,12 @@ public function test_execute_404(string $httpmethod) { * Placeholders in the "http headers" setting can go in as-is, but placeholders * in the url and http params need to be urlencoded. */ - public function test_execute_with_datafields() { + public function test_execute_with_datafields(): void { $stepsettings = [ 'url' => 'http://api.example.com/?returnurl={returnurl}&lang=en', 'httpheaders' => 'My-Special-Header: {headervalue}', 'httpparams' => 'a={a}&b={b}&c={c}&d=1&e={e}', - 'jsonencode' => '0' + 'jsonencode' => '0', ]; $step = new \tool_trigger\steps\actions\http_post_action_step(json_encode($stepsettings)); @@ -210,7 +209,7 @@ public function test_execute_with_datafields() { 'a' => '1005', 'b' => '?.&=;', 'c' => 'c', - 'e' => null + 'e' => null, ]; list($status) = $step->execute(null, null, $this->event, $prevstepresults); @@ -247,12 +246,12 @@ public function test_execute_with_datafields() { * Placeholders in the "http headers" setting can go in as-is, but placeholders * in the url and http params need to be urlencoded. */ - public function test_execute_with_datafields_json() { + public function test_execute_with_datafields_json(): void { $stepsettings = [ 'url' => 'http://api.example.com/?returnurl={returnurl}&lang=en', 'httpheaders' => 'My-Special-Header: {headervalue}', 'httpparams' => 'a={a}&b={b}&c={c}&d=1&e={e}', - 'jsonencode' => '1' + 'jsonencode' => '1', ]; $step = new \tool_trigger\steps\actions\http_post_action_step(json_encode($stepsettings)); @@ -268,7 +267,7 @@ public function test_execute_with_datafields_json() { 'a' => '1005', 'b' => '?.&=;', 'c' => 'c', - 'e' => null + 'e' => null, ]; list($status) = $step->execute(null, null, $this->event, $prevstepresults); diff --git a/tests/json_export_test.php b/tests/json_export_test.php index 411cfe4..b3317b8 100644 --- a/tests/json_export_test.php +++ b/tests/json_export_test.php @@ -31,22 +31,22 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class json_export_test extends \advanced_testcase { +final class json_export_test extends \advanced_testcase { - public function setup():void { + public function setup(): void { $this->resetAfterTest(true); } /** * Test filename creations */ - public function test_set_filename() { + public function test_set_filename(): void { $workflowobj = new \stdClass(); // Create workflow object. $workflowobj->name = '__testworkflow__'; $workflowobj->description = 'test workflow description'; $workflowobj->event = '\mod_scorm\event\user_report_viewed'; - $workflowobj->steps = array ( - 358000 => array( + $workflowobj->steps = [ + 358000 => [ 'id' => 358000, 'name' => 'a', 'description' => 's', @@ -55,18 +55,18 @@ public function test_set_filename() { 'data' => '{"useridfield":"userid","outputprefix":"user_","nodeleted":"1",' .'"stepdesc":"User lookup","typedesc":"Lookup"}', 'steporder' => 0, - ), - 358001 => array( + ], + 358001 => [ 'id' => 358001, 'name' => 's', 'description' => 's', 'type' => 'lookups', 'stepclass' => '/tool_trigger/steps/lookups/course_lookup_step', 'data' => '{"courseidfield":"courseid","outputprefix":"course_","stepdesc":"Course lookup","typedesc":"Lookup"}', - 'steporder' => 1 - ) + 'steporder' => 1, + ], - ); + ]; $workflowobj->moodleversion = 2018080300; $workflowobj->pluginversion = 2018080500; diff --git a/tests/learn_process_test.php b/tests/learn_process_test.php index d47b957..023efdd 100644 --- a/tests/learn_process_test.php +++ b/tests/learn_process_test.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Learn processor unit tests. - * - * @package tool_trigger - * @copyright Matt Porritt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; /** @@ -31,10 +23,9 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ +final class learn_process_test extends \advanced_testcase { -class learn_process_test extends \advanced_testcase { - - public function setup():void { + public function setup(): void { $this->resetAfterTest(true); } @@ -76,7 +67,7 @@ public function create_learnt_event_object() { * @return array $fields The event fields. */ public function get_event_fields() { - $fields = array( + $fields = [ 'eventname' => 'string', 'component' => 'string', 'action' => 'string', @@ -96,8 +87,8 @@ public function get_event_fields() { 'timecreated' => 'integer', 'origin' => 'string', 'ip' => 'string', - 'realuserid' => 'string' - ); + 'realuserid' => 'string', + ]; return $fields; } @@ -105,7 +96,7 @@ public function get_event_fields() { /** * Test learnt events names are retrieved from database. */ - public function test_get_learnt_events() { + public function test_get_learnt_events(): void { global $DB; // Add event records to database. @@ -114,9 +105,9 @@ public function test_get_learnt_events() { $learntevent2->eventname = '\core\event\user_loggedout'; $learntevent2->action = 'loggedout'; - $DB->insert_records('tool_trigger_learn_events', array($learntevent, $learntevent2)); + $DB->insert_records('tool_trigger_learn_events', [$learntevent, $learntevent2]); - $expected = array('\core\event\fake_event', '\core\event\user_loggedout'); // Expected result. + $expected = ['\core\event\fake_event', '\core\event\user_loggedout']; // Expected result. // We're testing a private method, so we need to setup reflector magic. $method = new \ReflectionMethod('tool_trigger\learn_process', 'get_learnt_events'); @@ -129,17 +120,17 @@ public function test_get_learnt_events() { /** * Test learnt event records are retrieved from database. */ - public function test_get_learnt_records() { + public function test_get_learnt_records(): void { global $DB; $count = 0; - $eventnames = array(); + $eventnames = []; // Add event records to database. $learntevent = $this->create_learnt_event_object(); - $DB->insert_records('tool_trigger_learn_events', array($learntevent, $learntevent)); + $DB->insert_records('tool_trigger_learn_events', [$learntevent, $learntevent]); - $expected = array('\core\event\fake_event', '\core\event\fake_event'); // Expected result. + $expected = ['\core\event\fake_event', '\core\event\fake_event']; // Expected result. // We're testing a private method, so we need to setup reflector magic. $method = new \ReflectionMethod('tool_trigger\learn_process', 'get_learnt_records'); @@ -161,7 +152,7 @@ public function test_get_learnt_records() { /** * Test learnt event records are retrieved from database. */ - public function test_convert_record_type() { + public function test_convert_record_type(): void { $learntevent = $this->create_learnt_event_object(); @@ -179,12 +170,12 @@ public function test_convert_record_type() { /** * Test processed records are merged successfully. */ - public function test_merge_records() { + public function test_merge_records(): void { $processedrecord = $this->get_event_fields(); $processedrecord2 = $processedrecord; $processedrecord2['oher_foo'] = 'string'; - $processedrecords = array($processedrecord, $processedrecord2); + $processedrecords = [$processedrecord, $processedrecord2]; $expected = $processedrecord; $expected['oher_foo'] = 'string'; @@ -201,7 +192,7 @@ public function test_merge_records() { /** * Test db record is merged successfully before updating. */ - public function test_merge_db_record() { + public function test_merge_db_record(): void { // Simulate learnt event. $processedrecord = $this->get_event_fields(); @@ -238,7 +229,7 @@ public function test_merge_db_record() { /** * Test learnt fields are correctly inserted in the database. */ - public function test_store_json_fields_insert() { + public function test_store_json_fields_insert(): void { global $DB; // Simulate learnt event. @@ -251,7 +242,7 @@ public function test_store_json_fields_insert() { $learnprocess->store_json_fields($learntevent, $jsonfields); // Get record form DB. - $result = $DB->get_record('tool_trigger_event_fields', array('eventname' => $learntevent)); + $result = $DB->get_record('tool_trigger_event_fields', ['eventname' => $learntevent]); $this->assertEquals($result->eventname, $learntevent); $this->assertEquals($result->jsonfields, $jsonfields); @@ -261,7 +252,7 @@ public function test_store_json_fields_insert() { /** * Test learnt fields are correctly updated in the database. */ - public function test_store_json_fields_update() { + public function test_store_json_fields_update(): void { global $DB; // Simulate learnt event. @@ -280,7 +271,7 @@ public function test_store_json_fields_update() { $learnprocess->store_json_fields($learntevent, $jsonfields); // Get record form DB. - $result = $DB->get_record('tool_trigger_event_fields', array('eventname' => $learntevent)); + $result = $DB->get_record('tool_trigger_event_fields', ['eventname' => $learntevent]); $this->assertEquals($result->eventname, $learntevent); $this->assertEquals($result->jsonfields, $jsonfields); @@ -290,7 +281,7 @@ public function test_store_json_fields_update() { /** * Test learnt fields are correctly retrieved from database for step form. */ - public function test_get_event_fields_with_type() { + public function test_get_event_fields_with_type(): void { global $DB; // Simulate learnt event. @@ -309,118 +300,118 @@ public function test_get_event_fields_with_type() { $learnprocess = new \tool_trigger\learn_process(); $eventfields = $learnprocess->get_event_fields_with_type($eventname); - $expected = array ( + $expected = [ 0 => - array ( + [ 'field' => 'eventname', 'type' => 'string', - ), + ], 1 => - array ( + [ 'field' => 'component', 'type' => 'string', - ), + ], 2 => - array ( + [ 'field' => 'action', 'type' => 'string', - ), + ], 3 => - array ( + [ 'field' => 'target', 'type' => 'string', - ), + ], 4 => - array ( + [ 'field' => 'objecttable', 'type' => 'string', - ), + ], 5 => - array ( + [ 'field' => 'objectid', 'type' => 'integer', - ), + ], 6 => - array ( + [ 'field' => 'crud', 'type' => 'string', - ), + ], 7 => - array ( + [ 'field' => 'edulevel', 'type' => 'integer', - ), + ], 8 => - array ( + [ 'field' => 'contextid', 'type' => 'integer', - ), + ], 9 => - array ( + [ 'field' => 'contextlevel', 'type' => 'integer', - ), + ], 10 => - array ( + [ 'field' => 'contextinstanceid', 'type' => 'integer', - ), + ], 11 => - array ( + [ 'field' => 'userid', 'type' => 'integer', - ), + ], 12 => - array ( + [ 'field' => 'courseid', 'type' => 'integer', - ), + ], 13 => - array ( + [ 'field' => 'relateduserid', 'type' => 'string', - ), + ], 14 => - array ( + [ 'field' => 'anonymous', 'type' => 'integer', - ), + ], 15 => - array ( + [ 'field' => 'other_username', 'type' => 'string', - ), + ], 16 => - array ( + [ 'field' => 'timecreated', 'type' => 'integer', - ), + ], 17 => - array ( + [ 'field' => 'origin', 'type' => 'string', - ), + ], 18 => - array ( + [ 'field' => 'ip', 'type' => 'string', - ), + ], 19 => - array ( + [ 'field' => 'realuserid', 'type' => 'string', - ), + ], 20 => - array ( + [ 'field' => 'wwwroot', - 'type' => 'string' - ), + 'type' => 'string', + ], 21 => - array ( + [ 'field' => 'wwwroot_domain', - 'type' => 'string' - ), - ); + 'type' => 'string', + ], + ]; $this->assertEquals($eventfields, $expected); @@ -429,7 +420,7 @@ public function test_get_event_fields_with_type() { /** * Test retrieve all the event names we have stored fields for. */ - public function test_get_event_fields_events() { + public function test_get_event_fields_events(): void { global $DB; // Simulate learnt event. @@ -454,7 +445,7 @@ public function test_get_event_fields_events() { /** * Test get the stored JSON fields for that event. */ - public function test_get_event_fields_json() { + public function test_get_event_fields_json(): void { global $DB; // Simulate learnt event. @@ -479,7 +470,7 @@ public function test_get_event_fields_json() { /** * Test procesing of JSON fixture file. */ - public function test_process_fixtures() { + public function test_process_fixtures(): void { $learnprocess = new \tool_trigger\learn_process(); $learnprocess->process_fixtures(); diff --git a/tests/logdump_action_step_test.php b/tests/logdump_action_step_test.php index 4df1092..1e72c86 100644 --- a/tests/logdump_action_step_test.php +++ b/tests/logdump_action_step_test.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + /** * Unit tests for logdump_action_step * @@ -22,11 +24,8 @@ * @copyright Catalyst IT 2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -namespace tool_trigger; - -class logdump_action_step_test extends \basic_testcase { - public function test_execute() { +final class logdump_action_step_test extends \basic_testcase { + public function test_execute(): void { // Don't overload var_dump by xdebug to solve the unit test when we run it with xdebug. ini_set('xdebug.overload_var_dump', 0); @@ -40,13 +39,13 @@ public function test_execute() { 'other' => [ 'courseid' => 1, 'courseshortname' => 'short name', - 'coursefullname' => 'full name' - ] + 'coursefullname' => 'full name', + ], ]); $prevstepresults = [ 'foo' => 'bar', - 'baz' => 'bax' + 'baz' => 'bax', ]; // Just check for a portion of the var_dump of the event, because it's looong! diff --git a/tests/numcompare_filter_step_test.php b/tests/numcompare_filter_step_test.php index 80eff6d..2e05599 100644 --- a/tests/numcompare_filter_step_test.php +++ b/tests/numcompare_filter_step_test.php @@ -14,15 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Numeric comparison filter step's unit test - * - * @package tool_trigger - * @author Aaron Wells - * @copyright Catalyst IT 2018 - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; use tool_trigger\steps\filters\numcompare_filter_step; @@ -32,7 +23,15 @@ global $CFG; require_once("$CFG->libdir/gradelib.php"); -class numcompare_filter_step_test extends \advanced_testcase { +/** + * Numeric comparison filter step's unit test + * + * @package tool_trigger + * @author Aaron Wells + * @copyright Catalyst IT 2018 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +final class numcompare_filter_step_test extends \advanced_testcase { /** * Event for testing. @@ -44,7 +43,7 @@ class numcompare_filter_step_test extends \advanced_testcase { * Create a "user_profile_viewed" event, of user1 viewing user2's * profile. And then run everything else as the cron user. */ - public function setup():void { + public function setup(): void { $this->resetAfterTest(true); // Grade event generation, copied from lib/tests/event_user_graded.php! @@ -58,7 +57,7 @@ public function setup():void { $gradeitem->update_final_grade($user->id, 10, 'gradebook'); - $gradegrade = new \grade_grade(array('userid' => $user->id, 'itemid' => $gradeitem->id), true); + $gradegrade = new \grade_grade(['userid' => $user->id, 'itemid' => $gradeitem->id], true); $gradegrade->grade_item = $gradeitem; $this->event = \core\event\user_graded::create_from_grade($gradegrade); @@ -72,12 +71,12 @@ public function setup():void { * * @dataProvider operator_permutations */ - public function test_all_operators($operator, $comparator, $expectedresult) { + public function test_all_operators($operator, $comparator, $expectedresult): void { $step = new \tool_trigger\steps\filters\numcompare_filter_step( json_encode([ 'field1' => $comparator, 'operator' => $operator, - 'field2' => '0' + 'field2' => '0', ]) ); @@ -95,7 +94,7 @@ public function test_all_operators($operator, $comparator, $expectedresult) { * * @return string[][]|boolean[][] */ - public function operator_permutations() { + public function operator_permutations(): array { return [ [ numcompare_filter_step::OPERATOR_EQUAL, '-100', false ], [ numcompare_filter_step::OPERATOR_EQUAL, '0', true ], @@ -114,18 +113,18 @@ public function operator_permutations() { [ numcompare_filter_step::OPERATOR_GT, '100', true ], [ numcompare_filter_step::OPERATOR_GT, '-100', false ], [ numcompare_filter_step::OPERATOR_GT, '0', false ], - [ numcompare_filter_step::OPERATOR_GT, '100', true ] + [ numcompare_filter_step::OPERATOR_GT, '100', true ], ]; } - public function test_datafield() { + public function test_datafield(): void { $step = new numcompare_filter_step( json_encode([ // Should work if the datafield name is provided on its own... 'field1' => 'other_finalgrade', 'operator' => numcompare_filter_step::OPERATOR_EQUAL, // ... or if the datafield name is in {brackets}. - 'field2' => '{target_grade}' + 'field2' => '{target_grade}', ]) ); @@ -134,12 +133,12 @@ public function test_datafield() { $this->assertTrue($status); } - public function test_nosuch_datafield() { + public function test_nosuch_datafield(): void { $step = new numcompare_filter_step( json_encode([ 'field1' => 'nosuchfield', 'operator' => numcompare_filter_step::OPERATOR_NOTEQUAL, - 'field2' => '10' + 'field2' => '10', ]) ); @@ -147,12 +146,12 @@ public function test_nosuch_datafield() { $this->assertTrue($status); } - public function test_not_numeric() { + public function test_not_numeric(): void { $step = new numcompare_filter_step( json_encode([ 'field1' => 'stringfield', 'operator' => numcompare_filter_step::OPERATOR_EQUAL, - 'field2' => '100' + 'field2' => '100', ]) ); diff --git a/tests/privacy_test.php b/tests/privacy_test.php index 4681fc2..c1c1f16 100644 --- a/tests/privacy_test.php +++ b/tests/privacy_test.php @@ -36,19 +36,20 @@ * @copyright 2019 Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class privacy_test extends \advanced_testcase { +final class privacy_test extends \advanced_testcase { /** * Set up method. */ - public function setUp():void { + public function setUp(): void { + parent::setUp(); $this->resetAfterTest(); } /** * Check that the correct userlist is returned if there is any user data for this context. */ - public function test_get_users_in_context() { + public function test_get_users_in_context(): void { global $DB; $component = 'tool_trigger'; @@ -99,7 +100,7 @@ public function test_get_users_in_context() { /** * Test deleting user data for an approved userlist in a context. */ - public function test_delete_data_for_users() { + public function test_delete_data_for_users(): void { global $DB; $component = 'tool_trigger'; diff --git a/tests/process_workflows_test.php b/tests/process_workflows_test.php index d645fe9..2eb6d07 100644 --- a/tests/process_workflows_test.php +++ b/tests/process_workflows_test.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Workflow form processing unit tests. - * - * @package tool_trigger - * @copyright Matt Porritt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; /** @@ -31,36 +23,29 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -class process_workflows_test extends \advanced_testcase { +final class process_workflows_test extends \advanced_testcase { /** * Test user. - * @var + * @var \stdClass */ protected $user; /** * Test context. - * @var + * @var \context */ protected $context; - /** - * Test event. - * @var - */ - protected $event; - /** * Test event object. - * @var + * @var \stdClass */ protected $eventobj; - public function setup():void { + public function setup(): void { global $DB; $this->resetAfterTest(true); @@ -107,7 +92,7 @@ public function setup():void { * * TODO: test a workflow that throws an execption */ - public function test_process_workflow() { + public function test_process_workflow(): void { $mdata = new \stdClass(); $mdata->workflowid = 0; $mdata->workflowname = 'Email me about login'; @@ -127,7 +112,7 @@ public function test_process_workflow() { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], [ 'id' => 0, @@ -139,8 +124,8 @@ public function test_process_workflow() { 'emailto' => \core_user::get_user_by_username('admin')->email, 'emailsubject' => '{user_firstname} {user_lastname} logged in', 'emailcontent_editor[text]' => '{user_email} logged in.', - 'emailcontent_editor[format]' => 0 - ] + 'emailcontent_editor[format]' => 0, + ], ]); // Insert it into the database. (It seems like it'll be more robust to do this diff --git a/tests/processor_helper_test.php b/tests/processor_helper_test.php index 515130b..61dfb7c 100644 --- a/tests/processor_helper_test.php +++ b/tests/processor_helper_test.php @@ -14,14 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Test for processor helper trait. - * - * @package tool_trigger - * @copyright Dmitrii Metelkin - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; defined('MOODLE_INTERNAL') || die(); @@ -30,18 +22,25 @@ require_once('tool_trigger_testcase.php'); -class processor_helper_test extends \tool_trigger_testcase { +/** + * Test for processor helper trait. + * + * @package tool_trigger + * @copyright Dmitrii Metelkin + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +final class processor_helper_test extends \tool_trigger_testcase { /** * Anonymous class for testing. - * @var + * @var mixed */ protected $testclass; /** * Set up. */ - public function setup():void { + public function setup(): void { $this->resetAfterTest(true); // Create anonymous class for testing trait. @@ -53,7 +52,7 @@ public function setup():void { /** * Test can restore event from the DB record. */ - public function test_restore_event() { + public function test_restore_event(): void { $data = (object) [ 'id' => 1, 'eventname' => '\\core\\event\\user_loggedin', @@ -94,7 +93,7 @@ public function test_restore_event() { $expectedevent = \core\event\user_loggedin::create([ 'userid' => '113000', 'objectid' => '113000', - 'other' => array('username' => 'username1'), + 'other' => ['username' => 'username1'], ]); $this->assertTrue($actual->is_restored()); $this->assertEquals($expectedevent->eventname, $actual->eventname); @@ -108,7 +107,7 @@ public function test_restore_event() { /** * Test can execute step. */ - public function test_execute_step() { + public function test_execute_step(): void { global $DB; $user = $this->getDataGenerator()->create_user(); @@ -116,7 +115,7 @@ public function test_execute_step() { $event = \core\event\user_loggedin::create([ 'userid' => $user->id, 'objectid' => $user->id, - 'other' => array('username' => $user->username), + 'other' => ['username' => $user->username], ]); $workflowid = $this->create_workflow(); @@ -135,7 +134,7 @@ public function test_execute_step() { /** * Test can get workflow steps. */ - public function test_get_workflow_steps() { + public function test_get_workflow_steps(): void { // Non-existing. $this->assertEmpty($this->testclass->get_workflow_steps(777777)); @@ -153,7 +152,7 @@ public function test_get_workflow_steps() { /** * Test can get workflow record. */ - public function test_update_workflow_record() { + public function test_update_workflow_record(): void { global $DB; $workflowid = $this->create_workflow(); @@ -186,7 +185,7 @@ public function test_update_workflow_record() { /** * Test can save a list of records to a trigger queue. */ - public function test_insert_queue_records() { + public function test_insert_queue_records(): void { global $DB; $this->assertEquals(0, $DB->count_records('tool_trigger_queue')); @@ -207,13 +206,13 @@ public function test_insert_queue_records() { /** * Test can get event record. */ - public function test_get_event_record() { + public function test_get_event_record(): void { global $DB; $event = \core\event\user_loggedin::create([ 'userid' => '113000', 'objectid' => '113000', - 'other' => array('username' => 'username1'), + 'other' => ['username' => 'username1'], ]); $data = (object)$event->get_data(); diff --git a/tests/role_assign_action_step_test.php b/tests/role_assign_action_step_test.php index dccffa6..ed05ef1 100644 --- a/tests/role_assign_action_step_test.php +++ b/tests/role_assign_action_step_test.php @@ -24,42 +24,42 @@ * @copyright 2019 Catalyst IT * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class role_assign_action_step_test extends \advanced_testcase { +final class role_assign_action_step_test extends \advanced_testcase { /** * Test user. - * @var + * @var \stdClass */ protected $user; /** * Test category. - * @var + * @var \stdClass */ protected $course; /** * Test event. - * @var + * @var \core\event\role_assigned */ protected $event; /** * Test role id. - * @var + * @var int */ protected $roleid; /** * Test context. - * @var + * @var \context */ protected $context; /** * Initial set up. */ - public function setUp():void { + public function setUp(): void { parent::setUp(); $this->resetAfterTest(true); @@ -78,7 +78,7 @@ public function setUp():void { 'other' => [ 'id' => 'not important', 'component' => 'not important', - 'itemid' => 'not important' + 'itemid' => 'not important', ], ]); @@ -89,7 +89,7 @@ public function setUp():void { /** * Test fields list. */ - public function test_get_fields() { + public function test_get_fields(): void { $expected = [ 'role_assign_result', 'role_assign_record_id', @@ -100,7 +100,7 @@ public function test_get_fields() { /** * Test can use hardcoded values. */ - public function test_execute_basic() { + public function test_execute_basic(): void { $this->assertFalse(user_has_role_assignment($this->user->id, $this->roleid, $this->context->id)); $step = new \tool_trigger\steps\actions\role_assign_action_step( @@ -121,7 +121,7 @@ public function test_execute_basic() { /** * Test can use placeholders. */ - public function test_execute_placeholder() { + public function test_execute_placeholder(): void { $this->assertFalse(user_has_role_assignment($this->user->id, $this->roleid, $this->context->id)); $step = new \tool_trigger\steps\actions\role_assign_action_step( @@ -142,7 +142,7 @@ public function test_execute_placeholder() { /** * Test for exception if an invalid field name is entered. */ - public function test_execute_nosuchfield() { + public function test_execute_nosuchfield(): void { $step = new \tool_trigger\steps\actions\role_assign_action_step( json_encode([ 'useridfield' => 'nosuchfield', diff --git a/tests/role_unassign_action_step_test.php b/tests/role_unassign_action_step_test.php index 5c289a3..6567f75 100644 --- a/tests/role_unassign_action_step_test.php +++ b/tests/role_unassign_action_step_test.php @@ -24,42 +24,42 @@ * @author Nicholas Hoobin * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class role_unassign_action_step_test extends \advanced_testcase { +final class role_unassign_action_step_test extends \advanced_testcase { /** * Test user. - * @var + * @var \stdClass */ protected $user; /** * Test category. - * @var + * @var \stdClass */ protected $course; /** * Test event. - * @var + * @var \core\event\role_assigned */ protected $event; /** * Test role id. - * @var + * @var int */ protected $roleid; /** * Test context. - * @var + * @var \context */ protected $context; /** * Initial set up. */ - public function setUp():void { + public function setUp(): void { parent::setUp(); $this->resetAfterTest(true); @@ -78,7 +78,7 @@ public function setUp():void { 'other' => [ 'id' => 'not important', 'component' => 'not important', - 'itemid' => 'not important' + 'itemid' => 'not important', ], ]); @@ -91,7 +91,7 @@ public function setUp():void { /** * Test fields list. */ - public function test_get_fields() { + public function test_get_fields(): void { $expected = [ 'role_unassign_result', 'role_unassign_role_id', @@ -102,7 +102,7 @@ public function test_get_fields() { /** * Test can use hardcoded values. */ - public function test_execute_basic() { + public function test_execute_basic(): void { $this->assertTrue(user_has_role_assignment($this->user->id, $this->roleid, $this->context->id)); @@ -124,7 +124,7 @@ public function test_execute_basic() { /** * Test can use placeholders. */ - public function test_execute_placeholder() { + public function test_execute_placeholder(): void { $this->assertTrue(user_has_role_assignment($this->user->id, $this->roleid, $this->context->id)); $step = new \tool_trigger\steps\actions\role_unassign_action_step( @@ -145,7 +145,7 @@ public function test_execute_placeholder() { /** * Test for exception if an invalid field name is entered. */ - public function test_execute_nosuchfield() { + public function test_execute_nosuchfield(): void { $step = new \tool_trigger\steps\actions\role_unassign_action_step( json_encode([ 'useridfield' => 'nosuchfield', diff --git a/tests/steps_form_test.php b/tests/steps_form_test.php index 21d6cbf..03171fd 100644 --- a/tests/steps_form_test.php +++ b/tests/steps_form_test.php @@ -14,6 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace tool_trigger; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once($CFG->dirroot . '/admin/tool/trigger/lib.php'); + /** * Test for the rendering of the forms of all the step classes. * @@ -21,22 +28,18 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ +final class steps_form_test extends \advanced_testcase { -defined('MOODLE_INTERNAL') || die(); - -global $CFG; -require_once($CFG->dirroot . '/admin/tool/trigger/lib.php'); - -class tool_trigger_steps_form_testcase extends advanced_testcase { - - public function setUp():void { + public function setUp(): void { + parent::setUp(); // Run as admin user. $this->setAdminUser(); } - public function tearDown():void { + public function tearDown(): void { // Reset user for tests. $this->setUser(); + parent::tearDown(); } /** @@ -45,7 +48,7 @@ public function tearDown():void { * @return array $fields The event fields. */ public function get_event_fields() { - $fields = array( + $fields = [ 'eventname' => 'string', 'component' => 'string', 'action' => 'string', @@ -65,8 +68,8 @@ public function get_event_fields() { 'timecreated' => 'integer', 'origin' => 'string', 'ip' => 'string', - 'realuserid' => 'string' - ); + 'realuserid' => 'string', + ]; return $fields; } @@ -74,10 +77,10 @@ public function get_event_fields() { /** * Test the display of the starting form (with just the "type" and "step" menus). */ - public function test_base_form() { + public function test_base_form(): void { // This lib function simply prints out the base form. $html = tool_trigger_output_fragment_new_base_form([ - 'context' => \context_system::instance() + 'context' => \context_system::instance(), ]); // Check that it has these form fields. @@ -100,7 +103,7 @@ public function test_base_form() { * @dataProvider provide_steps * @runInSeparateProcess */ - public function test_step_form($steptype, $stepclass) { + public function test_step_form($steptype, $stepclass): void { global $PAGE; $PAGE->set_url('/'); @@ -111,7 +114,7 @@ public function test_step_form($steptype, $stepclass) { 'stepclass' => $stepclass, 'event' => '\core\event\user_loggedin', 'existingsteps' => '[]', - 'steporder' => 0 + 'steporder' => 0, ]); // We mostly want to test that it renders with no errors thrown. @@ -124,7 +127,7 @@ public function test_step_form($steptype, $stepclass) { /** * Test getting the available fields from database. */ - public function test_get_trigger_fields() { + public function test_get_trigger_fields(): void { $this->resetAfterTest(); global $DB; @@ -141,142 +144,142 @@ public function test_get_trigger_fields() { $DB->insert_record('tool_trigger_event_fields', $record); // We're testing a private method, so we need to setup reflector magic. - $method = new ReflectionMethod('tool_trigger\steps\base\base_form', 'get_trigger_fields'); + $method = new \ReflectionMethod('tool_trigger\steps\base\base_form', 'get_trigger_fields'); $method->setAccessible(true); // Allow accessing of private method. $proxy = $method->invoke( new \tool_trigger\steps\base\base_form, '\core\event\user_login_failed', '\tool_trigger\steps\lookups\course_lookup_step', - array(), + [], -1 ); // Get result of invoked method. - $expected = array ( + $expected = [ 'fields' => - array ( + [ 0 => - array ( + [ 'field' => 'id', 'type' => 'string', - ), + ], 1 => - array ( + [ 'field' => 'eventname', 'type' => 'string', - ), + ], 2 => - array ( + [ 'field' => 'component', 'type' => 'string', - ), + ], 3 => - array ( + [ 'field' => 'action', 'type' => 'string', - ), + ], 4 => - array ( + [ 'field' => 'target', 'type' => 'string', - ), + ], 5 => - array ( + [ 'field' => 'objecttable', 'type' => 'string', - ), + ], 6 => - array ( + [ 'field' => 'objectid', 'type' => 'string', - ), + ], 7 => - array ( + [ 'field' => 'crud', 'type' => 'string', - ), + ], 8 => - array ( + [ 'field' => 'edulevel', 'type' => 'string', - ), + ], 9 => - array ( + [ 'field' => 'contextid', 'type' => 'string', - ), + ], 10 => - array ( + [ 'field' => 'contextlevel', 'type' => 'string', - ), + ], 11 => - array ( + [ 'field' => 'contextinstanceid', 'type' => 'string', - ), + ], 12 => - array ( + [ 'field' => 'userid', 'type' => 'string', - ), + ], 13 => - array ( + [ 'field' => 'courseid', 'type' => 'string', - ), + ], 14 => - array ( + [ 'field' => 'relateduserid', 'type' => 'string', - ), + ], 15 => - array ( + [ 'field' => 'anonymous', 'type' => 'string', - ), + ], 16 => - array ( + [ 'field' => 'other_username', 'type' => 'string', - ), + ], 17 => - array ( + [ 'field' => 'other_reason', 'type' => 'integer', - ), + ], 18 => - array ( + [ 'field' => 'timecreated', 'type' => 'string', - ), + ], 19 => - array ( + [ 'field' => 'origin', 'type' => 'string', - ), + ], 20 => - array ( + [ 'field' => 'ip', 'type' => 'string', - ), + ], 21 => - array ( + [ 'field' => 'realuserid', 'type' => 'string', - ), + ], 22 => - array( + [ 'field' => 'wwwroot', - 'type' => 'string' - ), + 'type' => 'string', + ], 23 => - array( + [ 'field' => 'wwwroot_domain', - 'type' => 'string' - ), - ), - 'steps' => array() - ); + 'type' => 'string', + ], + ], + 'steps' => [], + ]; $this->assertEquals($proxy, $expected); @@ -287,7 +290,7 @@ public function test_get_trigger_fields() { * * @return array */ - public function provide_steps() { + public function provide_steps(): array { $data = []; $wfm = new \tool_trigger\workflow_manager(); diff --git a/tests/stringcompare_filter_step_test.php b/tests/stringcompare_filter_step_test.php index b84fb46..17e7488 100644 --- a/tests/stringcompare_filter_step_test.php +++ b/tests/stringcompare_filter_step_test.php @@ -14,15 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * Numeric comparison filter step's unit test - * - * @package tool_trigger - * @author Aaron Wells - * @copyright Catalyst IT 2018 - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; use tool_trigger\steps\filters\stringcompare_filter_step; @@ -32,8 +23,15 @@ global $CFG; require_once(__DIR__.'/fixtures/user_event_fixture.php'); - -class stringcompare_filter_step_test extends \advanced_testcase { +/** + * Numeric comparison filter step's unit test + * + * @package tool_trigger + * @author Aaron Wells + * @copyright Catalyst IT 2018 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +final class stringcompare_filter_step_test extends \advanced_testcase { use \tool_trigger_user_event_fixture; @@ -41,7 +39,7 @@ class stringcompare_filter_step_test extends \advanced_testcase { * Create a "user_profile_viewed" event, of user1 viewing user2's * profile. And then run everything else as the cron user. */ - public function setup():void { + public function setup(): void { $this->setup_user_event(); } @@ -55,12 +53,12 @@ public function setup():void { * * @dataProvider operator_permutations */ - public function test_all_operators($operator, $comparator, $expectedresult) { + public function test_all_operators($operator, $comparator, $expectedresult): void { $stepconfig = [ 'field1' => 'Aaron Wells', 'operator' => $operator, 'field2' => $comparator, - 'wantmatch' => true + 'wantmatch' => true, ]; $step = new \tool_trigger\steps\filters\stringcompare_filter_step( json_encode($stepconfig) @@ -87,7 +85,7 @@ public function test_all_operators($operator, $comparator, $expectedresult) { * * @return array */ - public function operator_permutations() { + public function operator_permutations(): array { return [ [stringcompare_filter_step::OPERATOR_EQUAL, 'Aaron Wells', true], [stringcompare_filter_step::OPERATOR_EQUAL, 'Aaron Burr', false], @@ -102,14 +100,14 @@ public function operator_permutations() { // a problem, because datafields have an alphabetic component, and // regexes only accept integers and commas inside of {}. [stringcompare_filter_step::OPERATOR_REGEX, '^[A-Z][a-z]{4} ', true], - [stringcompare_filter_step::OPERATOR_REGEX, '[0-9]', false] + [stringcompare_filter_step::OPERATOR_REGEX, '[0-9]', false], ]; } /** * Test that datafield substitution works correctly. */ - public function test_datafield() { + public function test_datafield(): void { $step = new stringcompare_filter_step( json_encode([ // Put a datafield placeholder in field1. @@ -117,7 +115,7 @@ public function test_datafield() { 'operator' => stringcompare_filter_step::OPERATOR_STARTS_WITH, // The course we created during the event setup. 'field2' => $this->course->fullname, - 'wantmatch' => true + 'wantmatch' => true, ]) ); @@ -126,13 +124,13 @@ public function test_datafield() { $this->assertTrue($status); } - public function test_invalidregex() { + public function test_invalidregex(): void { $step = new stringcompare_filter_step( json_encode([ 'field1' => 'foo', 'operator' => stringcompare_filter_step::OPERATOR_REGEX, 'field2' => '***[', - 'wantmatch' => true + 'wantmatch' => true, ]) ); diff --git a/tests/tool_trigger_testcase.php b/tests/tool_trigger_testcase.php index 218235b..40e49ac 100644 --- a/tests/tool_trigger_testcase.php +++ b/tests/tool_trigger_testcase.php @@ -33,7 +33,6 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - abstract class tool_trigger_testcase extends advanced_testcase { /** @@ -54,7 +53,7 @@ public function create_workflow($realtime = 0, $steps = [], $debug = 0) { 'name' => 'Get user data', 'description' => 'Get user data', 'useridfield' => 'userid', - 'outputprefix' => 'user_' + 'outputprefix' => 'user_', ], ]; } diff --git a/tests/user_lookup_step_test.php b/tests/user_lookup_step_test.php index 83ed702..824272d 100644 --- a/tests/user_lookup_step_test.php +++ b/tests/user_lookup_step_test.php @@ -14,15 +14,6 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -/** - * "Fail" filter step's unit tests. - * - * @package tool_trigger - * @author Aaron Wells - * @copyright Catalyst IT 2018 - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - namespace tool_trigger; defined('MOODLE_INTERNAL') || die(); @@ -30,14 +21,22 @@ global $CFG; require_once(__DIR__.'/fixtures/user_event_fixture.php'); -class user_lookup_step_test extends \advanced_testcase { +/** + * User look up step's unit tests. + * + * @package tool_trigger + * @author Aaron Wells + * @copyright Catalyst IT 2018 + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +final class user_lookup_step_test extends \advanced_testcase { use \tool_trigger_user_event_fixture; /** * Create a "user_profile_viewed" event, of user1 viewing user2's * profile. And then run everything else as the cron user. */ - public function setup():void { + public function setup(): void { $this->setup_user_event(); } @@ -46,12 +45,12 @@ public function setup():void { * user identified at "userid", and add their data with the * prefix "user_". */ - public function test_execute_basic() { + public function test_execute_basic(): void { $step = new \tool_trigger\steps\lookups\user_lookup_step( json_encode([ 'useridfield' => 'userid', 'outputprefix' => 'user_', - 'nodeleted' => '1' + 'nodeleted' => '1', ]) ); @@ -65,7 +64,7 @@ public function test_execute_basic() { /** * Basic test, but this time with additional custom profile field. */ - public function test_execute_basic_with_custom_profile_fields() { + public function test_execute_basic_with_custom_profile_fields(): void { // Create user profile fields. $field1 = $this->add_user_custom_profile_field('testfield1', 'text'); $field2 = $this->add_user_custom_profile_field('testfield2', 'text'); @@ -79,7 +78,7 @@ public function test_execute_basic_with_custom_profile_fields() { json_encode([ 'useridfield' => 'userid', 'outputprefix' => 'user_', - 'nodeleted' => '1' + 'nodeleted' => '1', ]) ); @@ -97,12 +96,12 @@ public function test_execute_basic_with_custom_profile_fields() { * (an optional field, for events that involve one user interacting * with another), and use a different prefix. */ - public function test_execute_relateduser() { + public function test_execute_relateduser(): void { $step = new \tool_trigger\steps\lookups\user_lookup_step( json_encode([ 'useridfield' => 'relateduserid', 'outputprefix' => 'vieweduser_', - 'nodeleted' => '1' + 'nodeleted' => '1', ]) ); @@ -116,12 +115,12 @@ public function test_execute_relateduser() { /** * Test for exception if an invalid field name is entered. */ - public function test_execute_nosuchfield() { + public function test_execute_nosuchfield(): void { $step = new \tool_trigger\steps\lookups\user_lookup_step( json_encode([ 'useridfield' => 'nosuchfield', 'outputprefix' => 'user_', - 'nodeleted' => '1' + 'nodeleted' => '1', ]) ); @@ -132,7 +131,7 @@ public function test_execute_nosuchfield() { /** * Test for failure if a user is no longer present in the database. */ - public function test_execute_deleted_user() { + public function test_execute_deleted_user(): void { // Delete one of our users. delete_user($this->user1); @@ -142,7 +141,7 @@ public function test_execute_deleted_user() { json_encode([ 'useridfield' => 'userid', 'outputprefix' => 'user_', - 'nodeleted' => '1' + 'nodeleted' => '1', ]) ); @@ -155,7 +154,7 @@ public function test_execute_deleted_user() { json_encode([ 'useridfield' => 'userid', 'outputprefix' => 'user_', - 'nodeleted' => '0' + 'nodeleted' => '0', ]) ); list($status2, $stepresults2) = $step2->execute(null, null, $this->event, []); diff --git a/tests/webservice_action_step_test.php b/tests/webservice_action_step_test.php index 1dc0cda..4f2f6b8 100644 --- a/tests/webservice_action_step_test.php +++ b/tests/webservice_action_step_test.php @@ -29,7 +29,7 @@ * @copyright Catalyst IT, 2022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class webservice_action_step_test extends \advanced_testcase { +final class webservice_action_step_test extends \advanced_testcase { use \tool_trigger_user_event_fixture; /** @@ -44,7 +44,7 @@ public function setup(): void { * Simple test, with a successful result. * @runInSeparateProcess */ - public function test_with_valid_call_to_enrol_user() { + public function test_with_valid_call_to_enrol_user(): void { global $DB; $adminuser = get_admin(); @@ -86,7 +86,7 @@ public function test_with_valid_call_to_enrol_user() { * Test when the username is not valid, so the step fails with an exception. * @runInSeparateProcess */ - public function test_with_invalid_username() { + public function test_with_invalid_username(): void { $stepsettings = [ 'username' => 'tool_trigger_invalid_username', 'functionname' => 'enrol_manual_enrol_users', @@ -102,7 +102,7 @@ public function test_with_invalid_username() { * Test with non_existent function * @runInSeparateProcess */ - public function test_with_non_existent_function() { + public function test_with_non_existent_function(): void { $adminuser = get_admin(); $stepsettings = [ 'username' => $adminuser->username, @@ -122,7 +122,7 @@ public function test_with_non_existent_function() { * Test with invalid function parameters * @runInSeparateProcess */ - public function test_with_invalid_function_parameters() { + public function test_with_invalid_function_parameters(): void { $adminuser = get_admin(); $stepsettings = [ 'username' => $adminuser->username, diff --git a/tests/workflow_manager_test.php b/tests/workflow_manager_test.php index 491652a..be723a7 100644 --- a/tests/workflow_manager_test.php +++ b/tests/workflow_manager_test.php @@ -31,12 +31,12 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class workflow_manager_test extends \advanced_testcase { +final class workflow_manager_test extends \advanced_testcase { /** * Test getting step class names by step type. */ - public function test_get_step_class_names() { + public function test_get_step_class_names(): void { $steptype = 'actions'; $stepobj = new \tool_trigger\workflow_manager(); $steps = $stepobj->get_step_class_names($steptype); @@ -50,9 +50,9 @@ public function test_get_step_class_names() { /** * Test getting step human readable names by class name. */ - public function test_lookup_step_names() { + public function test_lookup_step_names(): void { - $stepclasses = array('\tool_trigger\steps\actions\http_post_action_step'); + $stepclasses = ['\tool_trigger\steps\actions\http_post_action_step']; $stepobj = new \tool_trigger\workflow_manager(); $steps = $stepobj->lookup_step_names($stepclasses); @@ -67,7 +67,7 @@ public function test_lookup_step_names() { * * @runInSeparateProcess */ - public function test_get_steps_by_type() { + public function test_get_steps_by_type(): void { $steptype = 'actions'; $stepobj = new \tool_trigger\workflow_manager(); @@ -85,7 +85,7 @@ public function test_get_steps_by_type() { * (This is an important security feature, because we take the step class names from form input. We have to make sure that * a user can't modify the form submission data and cause us to instantiate an arbitrary class.) */ - public function test_validate_step_class_good() { + public function test_validate_step_class_good(): void { $wfm = new \tool_trigger\workflow_manager(); $goodstepclassname = '\tool_trigger\steps\filters\fail_filter_step'; @@ -97,7 +97,7 @@ public function test_validate_step_class_good() { /** * Test that the validation code will reject a bad step class name, and throw an exception when asked to instantiate it. */ - public function test_validate_step_class_bad() { + public function test_validate_step_class_bad(): void { $wfm = new \tool_trigger\workflow_manager(); $badstepclassname = '\core\task\password_reset_cleanup_task'; @@ -110,7 +110,7 @@ public function test_validate_step_class_bad() { /** * Test getting workflow data object with step data included. */ - public function test_get_workflow_data_with_steps() { + public function test_get_workflow_data_with_steps(): void { $this->resetAfterTest(); global $DB; @@ -133,7 +133,7 @@ public function test_get_workflow_data_with_steps() { $workflowprocess = new \tool_trigger\workflow_process($mdata); $workflowprocess->processform(); - $workflow = $DB->get_record('tool_trigger_workflows', array('name' => '__testworkflow__'), '*', MUST_EXIST); + $workflow = $DB->get_record('tool_trigger_workflows', ['name' => '__testworkflow__'], '*', MUST_EXIST); $workflowid = $workflow->id; $workflowdata = \tool_trigger\workflow_manager::get_workflow_data_with_steps($workflowid); @@ -143,7 +143,7 @@ public function test_get_workflow_data_with_steps() { } - public function test_cleanup() { + public function test_cleanup(): void { $this->resetAfterTest(); // Run the task. This only tests that DB query does not throw exceptions. $task = new \tool_trigger\task\cleanup(); diff --git a/tests/workflow_process_test.php b/tests/workflow_process_test.php index f378b5b..28f034b 100644 --- a/tests/workflow_process_test.php +++ b/tests/workflow_process_test.php @@ -23,12 +23,12 @@ * @copyright Matt Porritt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class workflow_process_test extends \advanced_testcase { +final class workflow_process_test extends \advanced_testcase { /** * Test workflow process form data */ - public function test_processform() { + public function test_processform(): void { $this->resetAfterTest(); global $DB; @@ -49,8 +49,8 @@ public function test_processform() { $result = $workflowprocess->processform(); // Check that some values were actually written to db. - $workflowexists = $DB->record_exists('tool_trigger_workflows', array('name' => 'test workflow')); - $stepexists = $DB->record_exists('tool_trigger_steps', array('name' => 'test step')); + $workflowexists = $DB->record_exists('tool_trigger_workflows', ['name' => 'test workflow']); + $stepexists = $DB->record_exists('tool_trigger_steps', ['name' => 'test step']); $this->assertTrue($workflowexists); $this->assertTrue($stepexists); @@ -60,7 +60,7 @@ public function test_processform() { /** * Test workflow process step json data. */ - public function test_processjson() { + public function test_processjson(): void { $mdata = new \stdClass(); $json = '[{"id":"0","type":"action","stepclass":"/steps/action/log_step","steporder":"0"' . ',"name":"test step","description":"test step description"}]'; @@ -87,7 +87,7 @@ public function test_processjson() { /** * Test workflow process step json data with mulitple steps. */ - public function test_processjson_multiple_steps() { + public function test_processjson_multiple_steps(): void { $mdata = new \stdClass(); $json = '[' . '{"id":"0","type":"action","stepclass":"/steps/action/log_step",' @@ -128,7 +128,7 @@ public function test_processjson_multiple_steps() { $this->assertEquals ($expected2, $result[1]); } - public function test_import_prep () { + public function test_import_prep(): void { global $CFG; $filename = $CFG->dirroot . '/admin/tool/trigger/tests/fixtures/' . 'Test_login_failed_workflow_20180826_0058.json'; @@ -141,8 +141,8 @@ public function test_import_prep () { .'

It is triggered on a user login failed event

'; $expecteddescription->format = '1'; - $expectedsteps = array( - array( + $expectedsteps = [ + [ 'name' => 'Test fixture user lookup', 'description' => 'A user step that gets user profile imformation', 'type' => 'lookups', @@ -152,18 +152,18 @@ public function test_import_prep () { 'outputprefix' => 'user_', 'nodeleted' => '1', 'stepdesc' => 'User lookup', - 'typedesc' => 'Lookup' - ), - array( + 'typedesc' => 'Lookup', + ], + [ 'name' => 'Test fixture cron log', 'description' => 'A step that dumps workflow output to the cron log.', 'type' => 'actions', 'stepclass' => '\\tool_trigger\\steps\\actions\\logdump_action_step', 'steporder' => '1', 'stepdesc' => 'Cron log', - 'typedesc' => 'Action' - ) - ); + 'typedesc' => 'Action', + ], + ]; $expected = new \stdClass (); $expected->workflowid = 0;