From bc4df2af71d0afaa2b1705d1881cd13f1cd8e31a Mon Sep 17 00:00:00 2001 From: Matthew Hilton Date: Thu, 2 Nov 2023 10:59:06 +1000 Subject: [PATCH] MDL-67898 check: Get component if not set by manager --- lib/classes/check/check.php | 22 ++++++++++++++++++---- lib/tests/check_test.php | 17 ++++++++++++++++- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/lib/classes/check/check.php b/lib/classes/check/check.php index 7abdcafd206..6fdb79f4f92 100644 --- a/lib/classes/check/check.php +++ b/lib/classes/check/check.php @@ -24,7 +24,7 @@ */ namespace core\check; -defined('MOODLE_INTERNAL') || die(); +use coding_exception; /** * Base class for checks @@ -37,9 +37,10 @@ abstract class check { /** * @var string $component - The component / plugin this task belongs to. * - * This is autopopulated by the check manager. + * This can be autopopulated by the check manager. + * Otherwise, it is dynamically determined by get_component(). */ - protected $component = 'core'; + protected $component = ''; /** * Get the frankenstyle component name @@ -47,7 +48,20 @@ abstract class check { * @return string */ public function get_component(): string { - return $this->component; + // Return component if has been set by the manager. + if (!empty($this->component)) { + return $this->component; + } + + // Else work it out based on the classname. + // Because the first part of the classname is always the component. + $parts = explode("\\", get_called_class()); + + if (empty($parts)) { + throw new coding_exception("Unable to determine component for check"); + } + + return $parts[0]; } /** diff --git a/lib/tests/check_test.php b/lib/tests/check_test.php index 0acf752eed8..297c23ced83 100644 --- a/lib/tests/check_test.php +++ b/lib/tests/check_test.php @@ -26,6 +26,7 @@ use core\check\security\passwordpolicy; * @category check * @copyright 2020 Brendan Heywood * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @covers \core\check */ class check_test extends \advanced_testcase { @@ -36,7 +37,7 @@ class check_test extends \advanced_testcase { * instead of build time so many checks in real life such as testing * an API is connecting aren't viable to unit test. */ - public function test_passwordpolicy() { + public function test_passwordpolicy(): void { global $CFG; $prior = $CFG->passwordpolicy; @@ -52,5 +53,19 @@ class check_test extends \advanced_testcase { $CFG->passwordpolicy = $prior; } + + /** + * Tests that the component is correctly set. + */ + public function test_get_component(): void { + $check = new \tool_task\check\maxfaildelay(); + + // If no component is set, it should return the one based off the namespace. + $this->assertEquals('tool_task', $check->get_component()); + + // However if one is set, it should return that. + $check->set_component('test component'); + $this->assertEquals('test component', $check->get_component()); + } }