From c87a889434362f7f95312841db51d9145160f298 Mon Sep 17 00:00:00 2001 From: Maximilian Haye Date: Mon, 28 Oct 2024 15:25:53 +0100 Subject: [PATCH] style: have phpcbf replace string double-quotes with single-quotes --- classes/api/api.php | 4 +- classes/api/attempt_file.php | 2 +- classes/api/attempt_scored.php | 4 +- classes/api/attempt_started.php | 2 +- classes/api/attempt_ui.php | 12 +- classes/api/package_api.php | 18 +- classes/api/qpy_http_client.php | 6 +- classes/api/question_edit_form_response.php | 2 +- classes/api/question_response.php | 14 +- classes/api/scoring_code.php | 8 +- classes/api/status.php | 4 +- classes/api/usage.php | 4 +- classes/array_converter/array_converter.php | 28 +-- classes/constants.php | 4 +- classes/external/favourite_package.php | 2 +- classes/external/get_tags.php | 2 +- classes/external/load_packages.php | 2 +- classes/external/remove_packages.php | 2 +- classes/external/search_packages.php | 10 +- classes/form/conditions/condition.php | 12 +- classes/form/conditions/does_not_equal.php | 2 +- classes/form/conditions/equals.php | 2 +- classes/form/conditions/in.php | 2 +- classes/form/conditions/is_checked.php | 2 +- classes/form/conditions/is_not_checked.php | 2 +- classes/form/context/array_render_context.php | 2 +- classes/form/context/mform_render_context.php | 2 +- classes/form/context/render_context.php | 12 +- classes/form/dynamic_help_icon.php | 2 +- classes/form/elements/checkbox_element.php | 12 +- classes/form/elements/fallback_element.php | 6 +- classes/form/elements/form_element.php | 22 +- classes/form/elements/group_element.php | 2 +- classes/form/elements/hidden_element.php | 2 +- classes/form/elements/radio_group_element.php | 8 +- classes/form/elements/repetition_element.php | 26 +-- classes/form/elements/select_element.php | 4 +- classes/form/elements/static_text_element.php | 2 +- classes/form/elements/text_area_element.php | 2 +- classes/form/elements/text_input_element.php | 6 +- classes/form/form_conditions.php | 4 +- classes/form/form_section.php | 4 +- classes/last_used_service.php | 2 +- classes/package/package.php | 10 +- classes/package/package_base.php | 4 +- classes/package/package_info.php | 4 +- classes/package/package_raw.php | 4 +- classes/package/package_version.php | 4 +- .../package/package_version_specific_info.php | 4 +- classes/package_file_service.php | 6 +- classes/package_settings.php | 2 +- classes/question_service.php | 2 +- classes/question_ui_metadata_extractor.php | 18 +- classes/question_ui_renderer.php | 190 +++++++++--------- classes/static_file_service.php | 4 +- classes/utils.php | 4 +- lang/en/qtype_questionpy.php | 4 +- lib.php | 6 +- question.php | 8 +- renderer.php | 2 +- .../array_converter/array_converter_test.php | 54 ++--- .../test_classes/polymorphic.php | 4 +- .../test_classes/uses_element_class.php | 2 +- .../test_classes/uses_rename_and_alias.php | 8 +- .../array_converter/test_classes/variant1.php | 2 +- .../array_converter/test_classes/variant2.php | 2 +- tests/data_provider.php | 54 ++--- tests/external/search_packages_test.php | 14 +- tests/form/elements/element_html_test.php | 10 +- tests/form/elements/element_json_test.php | 6 +- tests/form/elements/test_moodleform.php | 6 +- tests/question_service_test.php | 170 ++++++++-------- tests/question_test.php | 2 +- tests/question_ui_metadata_extractor_test.php | 26 +-- tests/question_ui_renderer_test.php | 42 ++-- tests/static_file_service_test.php | 44 ++-- version.php | 2 +- 77 files changed, 498 insertions(+), 498 deletions(-) diff --git a/classes/api/api.php b/classes/api/api.php index 23c6dfff..e8d6d672 100644 --- a/classes/api/api.php +++ b/classes/api/api.php @@ -109,7 +109,7 @@ public static function extract_package_info(stored_file $file): package_raw { 'package' => curl_file_create($filepath), ]; - $response = $connector->post("/package-extract-info", $data); + $response = $connector->post('/package-extract-info', $data); $response->assert_2xx(); return array_converter::from_array(package_raw::class, $response->get_data()); } @@ -122,7 +122,7 @@ public static function extract_package_info(stored_file $file): package_raw { */ public static function get_server_status(): status { $connector = connector::default(); - $response = $connector->get("/status"); + $response = $connector->get('/status'); $response->assert_2xx(); return array_converter::from_array(status::class, $response->get_data()); } diff --git a/classes/api/attempt_file.php b/classes/api/attempt_file.php index 4f44ae4f..db092f1a 100644 --- a/classes/api/attempt_file.php +++ b/classes/api/attempt_file.php @@ -31,7 +31,7 @@ class attempt_file { public string $name; /** @var string|null */ - #[array_key("mime_type")] + #[array_key('mime_type')] public ?string $mimetype = null; /** @var string $data */ diff --git a/classes/api/attempt_scored.php b/classes/api/attempt_scored.php index c84d1cd6..b0e17273 100644 --- a/classes/api/attempt_scored.php +++ b/classes/api/attempt_scored.php @@ -28,11 +28,11 @@ */ class attempt_scored extends attempt { /** @var string|null */ - #[array_key("scoring_state")] + #[array_key('scoring_state')] public ?string $scoringstate; /** @var scoring_code */ - #[array_key("scoring_code")] + #[array_key('scoring_code')] public scoring_code $scoringcode; /** @var float|null */ diff --git a/classes/api/attempt_started.php b/classes/api/attempt_started.php index 67aec2f7..bed1932a 100644 --- a/classes/api/attempt_started.php +++ b/classes/api/attempt_started.php @@ -28,7 +28,7 @@ */ class attempt_started extends attempt { /** @var string */ - #[array_key("attempt_state")] + #[array_key('attempt_state')] public string $attemptstate; /** diff --git a/classes/api/attempt_ui.php b/classes/api/attempt_ui.php index a3d71163..bfa3343b 100644 --- a/classes/api/attempt_ui.php +++ b/classes/api/attempt_ui.php @@ -32,22 +32,22 @@ class attempt_ui { public string $formulation; /** @var string|null */ - #[array_key("general_feedback")] + #[array_key('general_feedback')] public ?string $generalfeedback = null; /** @var string|null */ - #[array_key("specific_feedback")] + #[array_key('specific_feedback')] public ?string $specificfeedback = null; /** @var string|null */ - #[array_key("right_answer")] + #[array_key('right_answer')] public ?string $rightanswer = null; /** @var array string to string mapping of placeholder names to the values (to be replaced in the content) */ public array $placeholders = []; /** @var string[]|null */ - #[array_key("css_files")] + #[array_key('css_files')] public ?array $cssfiles = null; /** @var array specifics TBD */ @@ -55,8 +55,8 @@ class attempt_ui { public array $files = []; /** @var string specifics TBD */ - #[array_key("cache_control")] - public string $cachecontrol = "PRIVATE_CACHE"; + #[array_key('cache_control')] + public string $cachecontrol = 'PRIVATE_CACHE'; /** * Initializes a new instance. diff --git a/classes/api/package_api.php b/classes/api/package_api.php index c5309953..c0727ecc 100644 --- a/classes/api/package_api.php +++ b/classes/api/package_api.php @@ -194,9 +194,9 @@ private function guzzle_post_and_maybe_retry(string $uri, array $options = [], b $fd = $this->file->get_content_file_handle(); try { - $options["multipart"][] = [ - "name" => "package", - "contents" => $fd, + $options['multipart'][] = [ + 'name' => 'package', + 'contents' => $fd, ]; return $this->guzzle_post_and_maybe_retry($uri, $options, allowretry: false); @@ -204,7 +204,7 @@ private function guzzle_post_and_maybe_retry(string $uri, array $options = [], b @fclose($fd); } } catch (GuzzleException $e) { - throw new coding_exception("Request to QPy server failed: " . $e->getMessage()); + throw new coding_exception('Request to QPy server failed: ' . $e->getMessage()); } } @@ -226,7 +226,7 @@ public function download_static_file(string $namespace, string $shortname, strin try { $res = $this->guzzle_post_and_maybe_retry( "/packages/$this->hash/file/$namespace/$shortname/$kind/$path", - ["sink" => $targetpath] + ['sink' => $targetpath] ); } catch (BadResponseException $e) { if ($e->getResponse()->getStatusCode() == 404) { @@ -239,11 +239,11 @@ public function download_static_file(string $namespace, string $shortname, strin ); } - if ($res->hasHeader("Content-Type")) { - return $res->getHeader("Content-Type")[0]; + if ($res->hasHeader('Content-Type')) { + return $res->getHeader('Content-Type')[0]; } else { - debugging("Server did not send Content-Type header, falling back to application/octet-stream"); - return "application/octet-stream"; + debugging('Server did not send Content-Type header, falling back to application/octet-stream'); + return 'application/octet-stream'; } } diff --git a/classes/api/qpy_http_client.php b/classes/api/qpy_http_client.php index b5ac28fc..7dc30fb1 100644 --- a/classes/api/qpy_http_client.php +++ b/classes/api/qpy_http_client.php @@ -37,8 +37,8 @@ class qpy_http_client extends http_client { * @throws dml_exception */ public function __construct(array $config = []) { - $config["base_uri"] = rtrim(get_config('qtype_questionpy', 'server_url'), "/") . "/"; - $config["timeout"] = get_config('qtype_questionpy', 'server_timeout'); + $config['base_uri'] = rtrim(get_config('qtype_questionpy', 'server_url'), '/') . '/'; + $config['timeout'] = get_config('qtype_questionpy', 'server_timeout'); parent::__construct($config); } @@ -53,7 +53,7 @@ protected function get_handlers(array $settings): HandlerStack { /* This checks requests against Moodle's curlsecurityblockedhosts, which we don't want, since admins would need to ensure their QPy server isn't in this list otherwise. There may be ways to granularly allow the server_url, but this will do for now. */ - $handlerstack->remove("moodle_check_initial_request"); + $handlerstack->remove('moodle_check_initial_request'); return $handlerstack; } } diff --git a/classes/api/question_edit_form_response.php b/classes/api/question_edit_form_response.php index 618b5ada..adfaf790 100644 --- a/classes/api/question_edit_form_response.php +++ b/classes/api/question_edit_form_response.php @@ -32,7 +32,7 @@ class question_edit_form_response { public qpy_form $definition; /** @var array */ - #[array_key("form_data")] + #[array_key('form_data')] public array $formdata; /** diff --git a/classes/api/question_response.php b/classes/api/question_response.php index fe827482..e893d248 100644 --- a/classes/api/question_response.php +++ b/classes/api/question_response.php @@ -28,34 +28,34 @@ */ class question_response { /** @var string */ - #[array_key("question_state")] + #[array_key('question_state')] public string $state; /** @var string */ - #[array_key("scoring_method")] + #[array_key('scoring_method')] public string $scoringmethod; /** @var float|int */ - #[array_key("score_min")] + #[array_key('score_min')] public float $scoremin = 0; /** @var float|int */ - #[array_key("score_max")] + #[array_key('score_max')] public float $scoremax = 1; /** @var float|null */ public ?float $penalty = null; /** @var float|null */ - #[array_key("random_guess_score")] + #[array_key('random_guess_score')] public ?float $randomguessscore = null; /** @var bool */ - #[array_key("render_every_view")] + #[array_key('render_every_view')] public bool $rendereveryview = false; /** @var string|null */ - #[array_key("general_feedback")] + #[array_key('general_feedback')] public ?string $generalfeedback = null; /** diff --git a/classes/api/scoring_code.php b/classes/api/scoring_code.php index a6d5d9b8..6de7bbc6 100644 --- a/classes/api/scoring_code.php +++ b/classes/api/scoring_code.php @@ -26,8 +26,8 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ enum scoring_code: string { - case automatically_scored = "AUTOMATICALLY_SCORED"; - case needs_manual_scoring = "NEEDS_MANUAL_SCORING"; - case response_not_scorable = "RESPONSE_NOT_SCORABLE"; - case invalid_response = "INVALID_RESPONSE"; + case automatically_scored = 'AUTOMATICALLY_SCORED'; + case needs_manual_scoring = 'NEEDS_MANUAL_SCORING'; + case response_not_scorable = 'RESPONSE_NOT_SCORABLE'; + case invalid_response = 'INVALID_RESPONSE'; } diff --git a/classes/api/status.php b/classes/api/status.php index c7731d60..53b68357 100644 --- a/classes/api/status.php +++ b/classes/api/status.php @@ -34,11 +34,11 @@ class status { public string $version; /** @var bool */ - #[array_key("allow_lms_packages")] + #[array_key('allow_lms_packages')] public bool $allowlmspackages = false; /** @var string */ - #[array_key("max_package_size")] + #[array_key('max_package_size')] public string $maxpackagesize; /** @var usage|null */ diff --git a/classes/api/usage.php b/classes/api/usage.php index d478e504..90486619 100644 --- a/classes/api/usage.php +++ b/classes/api/usage.php @@ -28,11 +28,11 @@ */ class usage { /** @var int */ - #[array_key("requests_in_process")] + #[array_key('requests_in_process')] public int $requestsinprocess; /** @var int */ - #[array_key("requests_in_queue")] + #[array_key('requests_in_queue')] public int $requestsinqueue; /** diff --git a/classes/array_converter/array_converter.php b/classes/array_converter/array_converter.php index 0d74ce94..4a9be112 100644 --- a/classes/array_converter/array_converter.php +++ b/classes/array_converter/array_converter.php @@ -65,8 +65,8 @@ public static function from_array(string $class, array $raw): object { if ($discriminator !== null && $discriminator !== $expected) { // If the wrong discriminator is given, it is an error. throw new moodle_exception( - "cannotgetdata", - "error", + 'cannotgetdata', + 'error', debuginfo: "Expected '$config->discriminator' value '$expected', but got '$discriminator'" ); } @@ -80,7 +80,7 @@ public static function from_array(string $class, array $raw): object { debugging($message . " Using fallback variant '$config->fallbackvariant'."); $class = $config->fallbackvariant; } else { - throw new moodle_exception("cannotgetdata", "error", debuginfo: $message); + throw new moodle_exception('cannotgetdata', 'error', debuginfo: $message); } } @@ -112,13 +112,13 @@ public static function to_array($instance) { return $instance->value; } if ($instance instanceof \UnitEnum) { - throw new coding_exception("Only backed enums are supported."); + throw new coding_exception('Only backed enums are supported.'); } if (is_scalar($instance) || $instance === null) { return $instance; } if (is_array($instance)) { - return array_map([self::class, "to_array"], $instance); + return array_map([self::class, 'to_array'], $instance); } if (!is_object($instance)) { return (array)$instance; @@ -184,8 +184,8 @@ private static function instantiate(ReflectionClass $reflect, converter_config $ $args[] = $parameter->getDefaultValue(); } else if (!$parameter->isVariadic()) { throw new moodle_exception( - "cannotgetdata", - "error", + 'cannotgetdata', + 'error', debuginfo: "No value provided for required field '$parameter->name' of '{$reflect->getName()}'" ); } @@ -282,14 +282,14 @@ private static function convert_to_required_type(?ReflectionNamedType $type, con if (enum_exists($typehint)) { $enum = new \ReflectionEnum($typehint); if (!$enum->isBacked()) { - throw new coding_exception("Only backed enums are supported."); + throw new coding_exception('Only backed enums are supported.'); } try { - return call_user_func([$typehint, "from"], $value); + return call_user_func([$typehint, 'from'], $value); } catch (\TypeError | \ValueError) { throw new moodle_exception( - "cannotgetdata", - "error", + 'cannotgetdata', + 'error', debuginfo: "The value is not a valid member of enum '$typehint'" ); } @@ -300,7 +300,7 @@ private static function convert_to_required_type(?ReflectionNamedType $type, con return $value; } - if ($typehint === "array") { + if ($typehint === 'array') { $elementclass = $config->elementclasses[$propname] ?? null; if ($elementclass) { // Convert each element to the required class. @@ -319,8 +319,8 @@ private static function convert_to_required_type(?ReflectionNamedType $type, con $actualtype = gettype($value); throw new moodle_exception( - "cannotgetdata", - "error", + 'cannotgetdata', + 'error', debuginfo: "Cannot convert value of type '$actualtype' to type '$typehint'" ); } diff --git a/classes/constants.php b/classes/constants.php index 117c5253..d7ac62a6 100644 --- a/classes/constants.php +++ b/classes/constants.php @@ -31,7 +31,7 @@ class constants { public const NAMESPACE_QPY = 'http://questionpy.org/ns/question'; /** @var string */ - public const QT_VAR_ATTEMPT_STATE = "_attemptstate"; + public const QT_VAR_ATTEMPT_STATE = '_attemptstate'; /** @var string */ - public const QT_VAR_SCORING_STATE = "_scoringstate"; + public const QT_VAR_SCORING_STATE = '_scoringstate'; } diff --git a/classes/external/favourite_package.php b/classes/external/favourite_package.php index b4d09f71..ec903a15 100644 --- a/classes/external/favourite_package.php +++ b/classes/external/favourite_package.php @@ -19,7 +19,7 @@ defined('MOODLE_INTERNAL') || die; global $CFG; -require_once($CFG->libdir . "/externallib.php"); +require_once($CFG->libdir . '/externallib.php'); use context; use context_system; diff --git a/classes/external/get_tags.php b/classes/external/get_tags.php index 5b3e7a34..17569f1b 100644 --- a/classes/external/get_tags.php +++ b/classes/external/get_tags.php @@ -19,7 +19,7 @@ defined('MOODLE_INTERNAL') || die; global $CFG; -require_once($CFG->libdir . "/externallib.php"); +require_once($CFG->libdir . '/externallib.php'); use context_system; use external_api; diff --git a/classes/external/load_packages.php b/classes/external/load_packages.php index fad97e8a..3783a927 100644 --- a/classes/external/load_packages.php +++ b/classes/external/load_packages.php @@ -19,7 +19,7 @@ defined('MOODLE_INTERNAL') || die; global $CFG; -require_once($CFG->libdir . "/externallib.php"); +require_once($CFG->libdir . '/externallib.php'); use core\di; use external_api; diff --git a/classes/external/remove_packages.php b/classes/external/remove_packages.php index c0fe9826..c7e3e282 100644 --- a/classes/external/remove_packages.php +++ b/classes/external/remove_packages.php @@ -19,7 +19,7 @@ defined('MOODLE_INTERNAL') || die; global $CFG; -require_once($CFG->libdir . "/externallib.php"); +require_once($CFG->libdir . '/externallib.php'); use external_api; use external_function_parameters; diff --git a/classes/external/search_packages.php b/classes/external/search_packages.php index a5268383..f750a47d 100644 --- a/classes/external/search_packages.php +++ b/classes/external/search_packages.php @@ -19,7 +19,7 @@ defined('MOODLE_INTERNAL') || die; global $CFG; -require_once($CFG->libdir . "/externallib.php"); +require_once($CFG->libdir . '/externallib.php'); use context; use context_system; @@ -92,10 +92,10 @@ private static function validate_parameter_values($params): void { throw new invalid_parameter_exception("Unknown order. Valid parameters are: $validparameters"); } if ($params['limit'] <= 0 || $params['limit'] > 100) { - throw new invalid_parameter_exception("The limit can only be a value from 1 to 100."); + throw new invalid_parameter_exception('The limit can only be a value from 1 to 100.'); } if ($params['page'] < 0) { - throw new invalid_parameter_exception("The page can not be negative."); + throw new invalid_parameter_exception('The page can not be negative.'); } } @@ -285,10 +285,10 @@ private static function create_best_language_sql(): array { */ private static function create_recently_used_sql(int $contextid): array { // Create relevant sql fragment. - $joinlastusedsql = " + $joinlastusedsql = ' JOIN {qtype_questionpy_lastused} lu ON lu.packageid = p.id AND lu.contextid = :contextid - "; + '; return [$joinlastusedsql, ['contextid' => $contextid]]; } diff --git a/classes/form/conditions/condition.php b/classes/form/conditions/condition.php index 1f155e09..ba56dac6 100644 --- a/classes/form/conditions/condition.php +++ b/classes/form/conditions/condition.php @@ -26,12 +26,12 @@ * @copyright 2022 TU Berlin, innoCampus {@link https://www.questionpy.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -#[array_polymorphic("kind", variants: [ - "is_checked" => is_checked::class, - "is_not_checked" => is_not_checked::class, - "equals" => equals::class, - "does_not_equal" => does_not_equal::class, - "in" => in::class, +#[array_polymorphic('kind', variants: [ + 'is_checked' => is_checked::class, + 'is_not_checked' => is_not_checked::class, + 'equals' => equals::class, + 'does_not_equal' => does_not_equal::class, + 'in' => in::class, ])] abstract class condition { /** @var string $name name of the target element */ diff --git a/classes/form/conditions/does_not_equal.php b/classes/form/conditions/does_not_equal.php index 035dc9f3..75b5eb8b 100644 --- a/classes/form/conditions/does_not_equal.php +++ b/classes/form/conditions/does_not_equal.php @@ -32,6 +32,6 @@ class does_not_equal extends condition_with_value { * @return string */ public static function mform_type(): string { - return "neq"; + return 'neq'; } } diff --git a/classes/form/conditions/equals.php b/classes/form/conditions/equals.php index 73c57c43..67131242 100644 --- a/classes/form/conditions/equals.php +++ b/classes/form/conditions/equals.php @@ -32,6 +32,6 @@ class equals extends condition_with_value { * @return string */ public static function mform_type(): string { - return "eq"; + return 'eq'; } } diff --git a/classes/form/conditions/in.php b/classes/form/conditions/in.php index 5ad5573c..ab3cf8a7 100644 --- a/classes/form/conditions/in.php +++ b/classes/form/conditions/in.php @@ -32,6 +32,6 @@ class in extends condition_with_value { * @return string */ public static function mform_type(): string { - return "in"; + return 'in'; } } diff --git a/classes/form/conditions/is_checked.php b/classes/form/conditions/is_checked.php index e20ea76a..36969021 100644 --- a/classes/form/conditions/is_checked.php +++ b/classes/form/conditions/is_checked.php @@ -32,6 +32,6 @@ class is_checked extends condition { * @return string */ public static function mform_type(): string { - return "checked"; + return 'checked'; } } diff --git a/classes/form/conditions/is_not_checked.php b/classes/form/conditions/is_not_checked.php index 17744bea..b654fed2 100644 --- a/classes/form/conditions/is_not_checked.php +++ b/classes/form/conditions/is_not_checked.php @@ -32,6 +32,6 @@ class is_not_checked extends condition { * @return string */ public static function mform_type(): string { - return "notchecked"; + return 'notchecked'; } } diff --git a/classes/form/context/array_render_context.php b/classes/form/context/array_render_context.php index 282669a4..7b2d2990 100644 --- a/classes/form/context/array_render_context.php +++ b/classes/form/context/array_render_context.php @@ -133,7 +133,7 @@ public function set_default(string $name, $default): void { * @see \MoodleQuickForm::addRule() */ public function add_rule(string $name, ?string $message, string $type, ?string $format = null, - ?string $validation = "server", bool $reset = false, bool $force = false): void { + ?string $validation = 'server', bool $reset = false, bool $force = false): void { utils::ensure_exists( $this->rules, $this->mangle_name($name) diff --git a/classes/form/context/mform_render_context.php b/classes/form/context/mform_render_context.php index c59d9837..d15552e0 100644 --- a/classes/form/context/mform_render_context.php +++ b/classes/form/context/mform_render_context.php @@ -83,7 +83,7 @@ public function set_default(string $name, $default): void { * @see \MoodleQuickForm::addRule() */ public function add_rule(string $name, ?string $message, string $type, ?string $format = null, - ?string $validation = "server", bool $reset = false, bool $force = false): void { + ?string $validation = 'server', bool $reset = false, bool $force = false): void { $this->mform->addRule($this->mangle_name($name), $message, $type, $format, $validation, $reset, $force); } diff --git a/classes/form/context/render_context.php b/classes/form/context/render_context.php index a5bbf22a..8fc6f827 100644 --- a/classes/form/context/render_context.php +++ b/classes/form/context/render_context.php @@ -115,7 +115,7 @@ abstract public function set_default(string $name, $default): void; * @see MoodleQuickForm::addRule */ abstract public function add_rule(string $name, ?string $message, string $type, ?string $format = null, - ?string $validation = "server", bool $reset = false, bool $force = false): void; + ?string $validation = 'server', bool $reset = false, bool $force = false): void; /** * Adds a condition which will disable the named element if met. @@ -151,7 +151,7 @@ public function mangle_name(string $name): string { return $name; } - $firstbrace = strpos($name, "["); + $firstbrace = strpos($name, '['); if ($firstbrace) { // We want to turn abc[def] into prefix[abc][def], not prefix[abc[def]]. $beforebrace = substr($name, 0, $firstbrace); @@ -180,11 +180,11 @@ abstract public function next_unique_int(): int; public function reference_to_absolute(string $reference): string { $referee = $this->prefix; // Explode a $reference like qpy_form[abc][def] into an array ["qpy_form", "abc", "def"]. - $referenceparts = explode("[", str_replace("]", "", $reference)); - $refereeparts = explode("[", str_replace("]", "", $referee)); + $referenceparts = explode('[', str_replace(']', '', $reference)); + $refereeparts = explode('[', str_replace(']', '', $referee)); foreach ($referenceparts as $referencepart) { - if ($referencepart === "..") { + if ($referencepart === '..') { $removed = array_pop($refereeparts); if (is_numeric($removed)) { // The reference probably points from a repetition outward. @@ -197,7 +197,7 @@ public function reference_to_absolute(string $reference): string { } // Stitch $refereeparts back together. - return $refereeparts[0] . "[" . implode("][", array_slice($refereeparts, 1)) . "]"; + return $refereeparts[0] . '[' . implode('][', array_slice($refereeparts, 1)) . ']'; } /** diff --git a/classes/form/dynamic_help_icon.php b/classes/form/dynamic_help_icon.php index 6a372316..e2dea1df 100644 --- a/classes/form/dynamic_help_icon.php +++ b/classes/form/dynamic_help_icon.php @@ -62,7 +62,7 @@ public function __construct(string $text, ?string $title = null) { * @return string */ public function get_template_name(\renderer_base $renderer): string { - return "core/help_icon"; + return 'core/help_icon'; } /** diff --git a/classes/form/elements/checkbox_element.php b/classes/form/elements/checkbox_element.php index 76a38fee..1cfa4622 100644 --- a/classes/form/elements/checkbox_element.php +++ b/classes/form/elements/checkbox_element.php @@ -37,10 +37,10 @@ class checkbox_element extends form_element { /** @var string */ public string $name; /** @var string|null */ - #[array_key("left_label")] + #[array_key('left_label')] public ?string $leftlabel = null; /** @var string|null */ - #[array_key("right_label")] + #[array_key('right_label')] public ?string $rightlabel = null; /** @var bool */ public bool $required = false; @@ -74,18 +74,18 @@ public function __construct(string $name, ?string $leftlabel = null, ?string $ri */ public function render_to(render_context $context, ?int $group = null): void { $element = $context->add_element( - "advcheckbox", + 'advcheckbox', $this->name, $context->contextualize($this->leftlabel), $context->contextualize($this->rightlabel), - $group ? ["group" => $group] : null + $group ? ['group' => $group] : null ); if ($this->selected) { - $context->set_default($this->name, "1"); + $context->set_default($this->name, '1'); } if ($this->required) { - $context->add_rule($this->name, get_string("required"), "required"); + $context->add_rule($this->name, get_string('required'), 'required'); } $this->render_conditions($context, $this->name); diff --git a/classes/form/elements/fallback_element.php b/classes/form/elements/fallback_element.php index 524f3ca2..d515d28f 100644 --- a/classes/form/elements/fallback_element.php +++ b/classes/form/elements/fallback_element.php @@ -41,14 +41,14 @@ class fallback_element extends form_element { public function render_to(render_context $context): void { $name = $this->name; if (!$name) { - $name = "qpy_fallback_" . $context->next_unique_int(); + $name = 'qpy_fallback_' . $context->next_unique_int(); } $context->add_element( - "warning", + 'warning', $name, null, - get_string("form_fallback_element_text", "qtype_questionpy") + get_string('form_fallback_element_text', 'qtype_questionpy') ); } } diff --git a/classes/form/elements/form_element.php b/classes/form/elements/form_element.php index f060d1fc..852b3aee 100644 --- a/classes/form/elements/form_element.php +++ b/classes/form/elements/form_element.php @@ -27,17 +27,17 @@ * @copyright 2022 TU Berlin, innoCampus {@link https://www.questionpy.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -#[array_polymorphic("kind", variants: [ - "checkbox" => checkbox_element::class, - "checkbox_group" => checkbox_group_element::class, - "group" => group_element::class, - "hidden" => hidden_element::class, - "radio_group" => radio_group_element::class, - "repetition" => repetition_element::class, - "select" => select_element::class, - "static_text" => static_text_element::class, - "input" => text_input_element::class, - "textarea" => text_area_element::class, +#[array_polymorphic('kind', variants: [ + 'checkbox' => checkbox_element::class, + 'checkbox_group' => checkbox_group_element::class, + 'group' => group_element::class, + 'hidden' => hidden_element::class, + 'radio_group' => radio_group_element::class, + 'repetition' => repetition_element::class, + 'select' => select_element::class, + 'static_text' => static_text_element::class, + 'input' => text_input_element::class, + 'textarea' => text_area_element::class, ], fallbackvariant: fallback_element::class)] abstract class form_element implements qpy_renderable { } diff --git a/classes/form/elements/group_element.php b/classes/form/elements/group_element.php index 4ddb7998..8a55dce9 100644 --- a/classes/form/elements/group_element.php +++ b/classes/form/elements/group_element.php @@ -71,7 +71,7 @@ public function render_to(render_context $context): void { } $element = $context->add_element( - "group", + 'group', $groupname, $context->contextualize($this->label), $innercontext->elements, diff --git a/classes/form/elements/hidden_element.php b/classes/form/elements/hidden_element.php index 9c8abc4f..7f638619 100644 --- a/classes/form/elements/hidden_element.php +++ b/classes/form/elements/hidden_element.php @@ -53,7 +53,7 @@ public function __construct(string $name, string $value) { * @package qtype_questionpy */ public function render_to(render_context $context): void { - $context->add_element("hidden", $this->name, $this->value); + $context->add_element('hidden', $this->name, $this->value); $context->set_type($this->name, PARAM_TEXT); $this->render_conditions($context, $this->name); diff --git a/classes/form/elements/radio_group_element.php b/classes/form/elements/radio_group_element.php index c971fdd2..91738867 100644 --- a/classes/form/elements/radio_group_element.php +++ b/classes/form/elements/radio_group_element.php @@ -73,7 +73,7 @@ public function render_to(render_context $context): void { } $radioarray[] = $context->mform->createElement( - "radio", + 'radio', $mangledname, null, $context->contextualize($option->label), @@ -82,8 +82,8 @@ public function render_to(render_context $context): void { } $group = $context->add_element( - "group", - "radio_group_" . $this->name, + 'group', + 'radio_group_' . $this->name, $context->contextualize($this->label), $radioarray, null, @@ -94,7 +94,7 @@ public function render_to(render_context $context): void { $context->set_default($this->name, $default); } if ($this->required) { - $context->add_rule("radio_group_" . $this->name, null, "required"); + $context->add_rule('radio_group_' . $this->name, null, 'required'); } $this->render_conditions($context, $this->name); diff --git a/classes/form/elements/repetition_element.php b/classes/form/elements/repetition_element.php index 75dae22f..f194504e 100644 --- a/classes/form/elements/repetition_element.php +++ b/classes/form/elements/repetition_element.php @@ -36,18 +36,18 @@ class repetition_element extends form_element { public string $name; /** @var int number of repetitions to show initially */ - #[array_key("initial_repetitions")] + #[array_key('initial_repetitions')] public int $initialrepetitions; /** @var int minimum number of repetitions, which cannot be removed */ - #[array_key("minimum_repetitions")] + #[array_key('minimum_repetitions')] public int $minimumrepetitions = 1; /** @var int number of elements to add with each click of the button */ public int $increment; /** @var string|null label for the button which adds additional blanks, null to use default */ - #[array_key("button_label")] + #[array_key('button_label')] public ?string $buttonlabel; /** @var form_element[] */ @@ -84,7 +84,7 @@ public function render_to(render_context $context): void { * Moodle implements this in moodleform::repeat_elements(), but that method is inconsistent in how it names * elements, so we implement our own. */ - $mangledname = str_replace(["[", "]"], "_", $context->mangle_name($this->name)); + $mangledname = str_replace(['[', ']'], '_', $context->mangle_name($this->name)); $internalname = "qpy_repetition[$mangledname]"; $repeatsname = "{$internalname}[repeats]"; $addmorename = "{$internalname}[add_more]"; @@ -99,12 +99,12 @@ public function render_to(render_context $context): void { PARAM_INT ); - $addmore = $context->moodleform->optional_param($addmorename, "", PARAM_TEXT); + $addmore = $context->moodleform->optional_param($addmorename, '', PARAM_TEXT); if ($addmore) { $repeats += $this->increment; } - $context->mform->addElement("hidden", $repeatsname, $repeats); + $context->mform->addElement('hidden', $repeatsname, $repeats); $context->mform->setType($repeatsname, PARAM_INT); // Prevent repeats from being overridden with the submitted value. $context->mform->setConstant($repeatsname, $repeats); @@ -120,14 +120,14 @@ public function render_to(render_context $context): void { || $context->moodleform->optional_param("{$removednameprefix}[$i]", false, PARAM_RAW); if ($isremoved !== false) { $removed[] = $i; - $context->mform->addElement("hidden", "{$removednameprefix}[$i]", "removed"); + $context->mform->addElement('hidden', "{$removednameprefix}[$i]", 'removed'); $context->mform->setType("{$removednameprefix}[$i]", PARAM_RAW); } } $allowremoval = $repeats - count($removed) > $this->minimumrepetitions; - $removestring = get_string("remove"); + $removestring = get_string('remove'); global $OUTPUT; $removeicon = $OUTPUT->pix_icon('i/delete', $removestring, 'core'); @@ -139,23 +139,23 @@ public function render_to(render_context $context): void { } $humanrepno++; - $context->mform->addElement("html", '
'); + $context->mform->addElement('html', '
'); $innercontext = new repetition_render_context($context, $this->name, $i, $humanrepno); foreach ($this->elements as $element) { $element->render_to($innercontext); } - $context->mform->addElement("html", '
'); + $context->mform->addElement('html', '
'); if ($allowremoval) { - $context->mform->addElement("html", ""); } - $context->mform->addElement("html", '
'); + $context->mform->addElement('html', '
'); } $buttonlabel = $this->buttonlabel ?: get_string('addfields', 'form', $this->increment); - $context->mform->addElement("submit", $addmorename, $buttonlabel, [], false); + $context->mform->addElement('submit', $addmorename, $buttonlabel, [], false); $context->mform->registerNoSubmitButton($addmorename); } } diff --git a/classes/form/elements/select_element.php b/classes/form/elements/select_element.php index 1434d1c0..71722978 100644 --- a/classes/form/elements/select_element.php +++ b/classes/form/elements/select_element.php @@ -82,7 +82,7 @@ public function render_to(render_context $context): void { // phpcs:disable moodle.Commenting.InlineComment.DocBlock /** @var $element HTML_QuickForm_select */ $element = $context->add_element( - "select", + 'select', $this->name, $context->contextualize($this->label), $optionsassociative @@ -94,7 +94,7 @@ public function render_to(render_context $context): void { } if ($this->required) { - $context->add_rule($this->name, null, "required"); + $context->add_rule($this->name, null, 'required'); } $this->render_conditions($context, $this->name); diff --git a/classes/form/elements/static_text_element.php b/classes/form/elements/static_text_element.php index 907e9c2c..f1e4395b 100644 --- a/classes/form/elements/static_text_element.php +++ b/classes/form/elements/static_text_element.php @@ -59,7 +59,7 @@ public function __construct(string $name, string $label, string $text) { */ public function render_to(render_context $context): void { $element = $context->add_element( - "static", + 'static', $this->name, $context->contextualize($this->label), $context->contextualize($this->text) diff --git a/classes/form/elements/text_area_element.php b/classes/form/elements/text_area_element.php index 8b2b3e13..fe41cfce 100644 --- a/classes/form/elements/text_area_element.php +++ b/classes/form/elements/text_area_element.php @@ -30,5 +30,5 @@ */ class text_area_element extends text_input_element { /** @var string */ - protected const MFORM_ELEMENT = "textarea"; + protected const MFORM_ELEMENT = 'textarea'; } diff --git a/classes/form/elements/text_input_element.php b/classes/form/elements/text_input_element.php index 9e930f46..1764849d 100644 --- a/classes/form/elements/text_input_element.php +++ b/classes/form/elements/text_input_element.php @@ -33,7 +33,7 @@ class text_input_element extends form_element { use form_help; /** @var string moodle form element name, overridden by {@see text_area_element} */ - protected const MFORM_ELEMENT = "text"; + protected const MFORM_ELEMENT = 'text'; /** @var string */ public string $name; @@ -75,7 +75,7 @@ public function __construct( * @param render_context $context target context */ public function render_to(render_context $context): void { - $attributes = $this->placeholder ? ["placeholder" => $context->contextualize($this->placeholder)] : []; + $attributes = $this->placeholder ? ['placeholder' => $context->contextualize($this->placeholder)] : []; $element = $context->add_element( get_class($this)::MFORM_ELEMENT, @@ -89,7 +89,7 @@ public function render_to(render_context $context): void { $context->set_default($this->name, $context->contextualize($this->default)); } if ($this->required) { - $context->add_rule($this->name, null, "required"); + $context->add_rule($this->name, null, 'required'); } $this->render_conditions($context, $this->name); diff --git a/classes/form/form_conditions.php b/classes/form/form_conditions.php index e32ed3fc..efe397a2 100644 --- a/classes/form/form_conditions.php +++ b/classes/form/form_conditions.php @@ -31,11 +31,11 @@ */ trait form_conditions { /** @var condition[] */ - #[array_key("disable_if")] + #[array_key('disable_if')] #[array_element_class(condition::class)] public array $disableif = []; /** @var condition[] */ - #[array_key("hide_if")] + #[array_key('hide_if')] #[array_element_class(condition::class)] public array $hideif = []; diff --git a/classes/form/form_section.php b/classes/form/form_section.php index 0f924840..84aab198 100644 --- a/classes/form/form_section.php +++ b/classes/form/form_section.php @@ -59,8 +59,8 @@ public function __construct(string $name, string $header, array $elements) { * @param render_context $context target context */ public function render_to(render_context $context): void { - $mangled = $context->mangle_name("qpy_section_header_" . $this->name); - $context->add_element("header", $mangled, $this->header); + $mangled = $context->mangle_name('qpy_section_header_' . $this->name); + $context->add_element('header', $mangled, $this->header); $innercontext = new section_render_context($context, $this->name); foreach ($this->elements as $element) { $element->render_to($innercontext); diff --git a/classes/last_used_service.php b/classes/last_used_service.php index f626e42c..58692729 100644 --- a/classes/last_used_service.php +++ b/classes/last_used_service.php @@ -58,7 +58,7 @@ public static function add(int $contextid, int $packageid): void { */ public static function remove_by_package(int ...$packageids): void { global $DB; - [$insql, $inparams] = $DB->get_in_or_equal($packageids, SQL_PARAMS_NAMED, "packageids"); + [$insql, $inparams] = $DB->get_in_or_equal($packageids, SQL_PARAMS_NAMED, 'packageids'); $DB->delete_records_select('qtype_questionpy_lastused', "packageid $insql", $inparams); } } diff --git a/classes/package/package.php b/classes/package/package.php index 67b7b5ea..6843d73b 100644 --- a/classes/package/package.php +++ b/classes/package/package.php @@ -101,19 +101,19 @@ public static function delete_by_id(int ...$ids): void { $transaction = $DB->start_delegated_transaction(); - [$insql, $inparams] = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, "packageids"); + [$insql, $inparams] = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'packageids'); $DB->delete_records_select('qtype_questionpy_pkgversion', "packageid $insql", $inparams); $DB->delete_records_select('qtype_questionpy_language', "packageid $insql", $inparams); $DB->delete_records_select('qtype_questionpy_package', "id $insql", $inparams); $DB->delete_records_select('qtype_questionpy_pkgtag', "packageid $insql", $inparams); - $DB->execute(" + $DB->execute(' DELETE FROM {qtype_questionpy_tag} WHERE id NOT IN ( SELECT tagid FROM {qtype_questionpy_pkgtag} ) - "); + '); last_used_service::remove_by_package(...$ids); $fservice = \core_favourites\service_factory::get_service_for_component('qtype_questionpy'); @@ -196,12 +196,12 @@ private static function get_language_data(int $packageid): array { */ private static function get_tag_data(int $packageid): array { global $DB; - return $DB->get_fieldset_sql(" + return $DB->get_fieldset_sql(' SELECT DISTINCT t.tag FROM {qtype_questionpy_tag} t JOIN {qtype_questionpy_pkgtag} pt ON pt.id = :packageid AND pt.tagid = t.id - ", ['packageid' => $packageid]); + ', ['packageid' => $packageid]); } /** diff --git a/classes/package/package_base.php b/classes/package/package_base.php index cd99f8f5..ecde9817 100644 --- a/classes/package/package_base.php +++ b/classes/package/package_base.php @@ -32,8 +32,8 @@ class package_base { /** * @var string package shortname */ - #[array_key("short_name")] - #[array_alias("shortname")] + #[array_key('short_name')] + #[array_alias('shortname')] public readonly string $shortname; /** diff --git a/classes/package/package_info.php b/classes/package/package_info.php index 43c0ff80..17ddf5e0 100644 --- a/classes/package/package_info.php +++ b/classes/package/package_info.php @@ -152,14 +152,14 @@ public function update(int $id, int $timestamp): void { ]; } $DB->insert_records('qtype_questionpy_pkgtag', $tagsdata); - $DB->execute(" + $DB->execute(' DELETE FROM {qtype_questionpy_tag} WHERE id NOT IN ( SELECT tagid FROM {qtype_questionpy_pkgtag} ) - "); + '); $transaction->allow_commit(); } diff --git a/classes/package/package_raw.php b/classes/package/package_raw.php index 58ca039c..24f8f09f 100644 --- a/classes/package/package_raw.php +++ b/classes/package/package_raw.php @@ -32,8 +32,8 @@ class package_raw extends package_base { /** * @var string package hash */ - #[array_key("package_hash")] - #[array_alias("hash")] + #[array_key('package_hash')] + #[array_alias('hash')] public string $hash; /** diff --git a/classes/package/package_version.php b/classes/package/package_version.php index 38727e59..8cd46986 100644 --- a/classes/package/package_version.php +++ b/classes/package/package_version.php @@ -162,14 +162,14 @@ public function delete(): void { // Delete package related data. $DB->delete_records('qtype_questionpy_language', ['packageid' => $this->packageid]); $DB->delete_records('qtype_questionpy_pkgtag', ['packageid' => $this->packageid]); - $DB->execute(" + $DB->execute(' DELETE FROM {qtype_questionpy_tag} WHERE id NOT IN ( SELECT tagid FROM {qtype_questionpy_pkgtag} ) - "); + '); $DB->delete_records('qtype_questionpy_package', ['id' => $this->packageid]); // Remove the package from the last used table. diff --git a/classes/package/package_version_specific_info.php b/classes/package/package_version_specific_info.php index 7ed57e6b..cca6b810 100644 --- a/classes/package/package_version_specific_info.php +++ b/classes/package/package_version_specific_info.php @@ -30,8 +30,8 @@ class package_version_specific_info { /** * @var string $hash */ - #[array_key("package_hash")] - #[array_alias("hash")] + #[array_key('package_hash')] + #[array_alias('hash')] public readonly string $hash; /** diff --git a/classes/package_file_service.php b/classes/package_file_service.php index a160c40e..0d212e6b 100644 --- a/classes/package_file_service.php +++ b/classes/package_file_service.php @@ -93,9 +93,9 @@ public function get_file_for_local_question(int $qpyid, int $contextid): stored_ */ public function get_file_by_package_hash(string $packagehash, int $contextid): ?stored_file { global $DB; - $qpyid = $DB->get_field("qtype_questionpy", "id", [ - "islocal" => true, - "pkgversionhash" => $packagehash, + $qpyid = $DB->get_field('qtype_questionpy', 'id', [ + 'islocal' => true, + 'pkgversionhash' => $packagehash, ], IGNORE_MULTIPLE); if ($qpyid === false) { diff --git a/classes/package_settings.php b/classes/package_settings.php index 3682e492..d3052ef2 100644 --- a/classes/package_settings.php +++ b/classes/package_settings.php @@ -83,6 +83,6 @@ public function get_setting(): bool { * @return string empty string if ok, string error message otherwise */ public function write_setting($data): string { - return ""; + return ''; } } diff --git a/classes/question_service.php b/classes/question_service.php index 738641f7..05e46054 100644 --- a/classes/question_service.php +++ b/classes/question_service.php @@ -50,7 +50,7 @@ public function __construct(api $api, package_file_service $packagefileservice) } /** @var string table containing our question data, 0-1 record per question */ - private const QUESTION_TABLE = "qtype_questionpy"; + private const QUESTION_TABLE = 'qtype_questionpy'; /** * Retrieves the QuestionPy-specific question fields from the database and returns them in an associative array. diff --git a/classes/question_ui_metadata_extractor.php b/classes/question_ui_metadata_extractor.php index 3bf76f75..9622f1cc 100644 --- a/classes/question_ui_metadata_extractor.php +++ b/classes/question_ui_metadata_extractor.php @@ -49,8 +49,8 @@ public function __construct(string $xml) { $this->xml->loadXML($xml); $this->xpath = new DOMXPath($this->xml); - $this->xpath->registerNamespace("xhtml", constants::NAMESPACE_XHTML); - $this->xpath->registerNamespace("qpy", constants::NAMESPACE_QPY); + $this->xpath->registerNamespace('xhtml', constants::NAMESPACE_XHTML); + $this->xpath->registerNamespace('qpy', constants::NAMESPACE_QPY); } /** @@ -65,10 +65,10 @@ public function extract(): question_metadata { $this->metadata = new question_metadata(); /** @var DOMAttr $attr */ - foreach ($this->xpath->query("//@qpy:correct-response") as $attr) { + foreach ($this->xpath->query('//@qpy:correct-response') as $attr) { /** @var DOMElement $element */ $element = $attr->ownerElement; - $name = $element->getAttribute("name"); + $name = $element->getAttribute('name'); if (!$name) { continue; } @@ -77,9 +77,9 @@ public function extract(): question_metadata { $this->metadata->correctresponse = []; } - if ($element->tagName == "input" && $element->getAttribute("type") == "radio") { + if ($element->tagName == 'input' && $element->getAttribute('type') == 'radio') { // On radio buttons, we expect the correct option to be marked with correct-response. - $radiovalue = $element->getAttribute("value"); + $radiovalue = $element->getAttribute('value'); $this->metadata->correctresponse[$name] = $radiovalue; } else { $this->metadata->correctresponse[$name] = $attr->value; @@ -89,14 +89,14 @@ public function extract(): question_metadata { /** @var DOMElement $element */ foreach ( $this->xpath->query( - "//*[self::xhtml:input or self::xhtml:select or self::xhtml:textarea or self::xhtml:button]" + '//*[self::xhtml:input or self::xhtml:select or self::xhtml:textarea or self::xhtml:button]' ) as $element ) { - $name = $element->getAttribute("name"); + $name = $element->getAttribute('name'); if ($name) { $this->metadata->expecteddata[$name] = PARAM_RAW; - if ($element->hasAttribute("required")) { + if ($element->hasAttribute('required')) { $this->metadata->requiredfields[] = $name; } } diff --git a/classes/question_ui_renderer.php b/classes/question_ui_renderer.php index 201c817f..2b43ab63 100644 --- a/classes/question_ui_renderer.php +++ b/classes/question_ui_renderer.php @@ -78,8 +78,8 @@ public function __construct(string $xml, array $placeholders, question_display_o $this->xml->normalizeDocument(); $this->xpath = new DOMXPath($this->xml); - $this->xpath->registerNamespace("xhtml", constants::NAMESPACE_XHTML); - $this->xpath->registerNamespace("qpy", constants::NAMESPACE_QPY); + $this->xpath->registerNamespace('xhtml', constants::NAMESPACE_XHTML); + $this->xpath->registerNamespace('qpy', constants::NAMESPACE_QPY); } /** @@ -96,7 +96,7 @@ public function render(): string { $nextseed = mt_rand(); $id = $this->attempt->get_database_id(); if ($id === null) { - throw new coding_exception("question_attempt does not have an id"); + throw new coding_exception('question_attempt does not have an id'); } mt_srand($id); @@ -130,13 +130,13 @@ public function render(): string { */ private function hide_unwanted_feedback(): void { /** @var DOMElement $element */ - foreach (iterator_to_array($this->xpath->query("//*[@qpy:feedback]")) as $element) { - $feedback = $element->getAttributeNS(constants::NAMESPACE_QPY, "feedback"); + foreach (iterator_to_array($this->xpath->query('//*[@qpy:feedback]')) as $element) { + $feedback = $element->getAttributeNS(constants::NAMESPACE_QPY, 'feedback'); if ( !( - ($feedback == "general" && $this->options->generalfeedback) - || ($feedback == "specific" && $this->options->feedback) + ($feedback == 'general' && $this->options->generalfeedback) + || ($feedback == 'specific' && $this->options->feedback) ) ) { $element->parentNode->removeChild($element); @@ -153,8 +153,8 @@ private function hide_unwanted_feedback(): void { */ private function shuffle_contents(): void { /** @var DOMElement $element */ - foreach (iterator_to_array($this->xpath->query("//*[@qpy:shuffle-contents]")) as $element) { - $element->removeAttributeNS(constants::NAMESPACE_QPY, "shuffle-contents"); + foreach (iterator_to_array($this->xpath->query('//*[@qpy:shuffle-contents]')) as $element) { + $element->removeAttributeNS(constants::NAMESPACE_QPY, 'shuffle-contents'); $newelement = $element->cloneNode(); // We want to shuffle elements while leaving other nodes (such as text, spacing) where they are. @@ -194,37 +194,37 @@ private function shuffle_contents(): void { */ private function replace_shuffled_indices(DOMNode $element, int $index): void { /** @var DOMElement $indexelement */ - foreach (iterator_to_array($this->xpath->query(".//qpy:shuffled-index", $element)) as $indexelement) { + foreach (iterator_to_array($this->xpath->query('.//qpy:shuffled-index', $element)) as $indexelement) { // phpcs:ignore Squiz.ControlStructures.ForLoopDeclaration.SpacingAfterSecond for ( $ancestor = $indexelement->parentNode; $ancestor !== null && $ancestor !== $indexelement; $ancestor = $ancestor->parentNode ) { assert($ancestor instanceof DOMElement); - if ($ancestor->hasAttributeNS(constants::NAMESPACE_QPY, "shuffle-contents")) { + if ($ancestor->hasAttributeNS(constants::NAMESPACE_QPY, 'shuffle-contents')) { // The index element is in a nested shuffle-contents. // We want it to be replaced with the index of the inner shuffle, so we ignore it for now. continue 2; } } - $format = $indexelement->getAttribute("format") ?: "123"; + $format = $indexelement->getAttribute('format') ?: '123'; switch ($format) { default: - case "123": + case '123': $indexstr = strval($index); break; - case "abc": + case 'abc': $indexstr = strtolower(\question_utils::int_to_letter($index)); break; - case "ABC": + case 'ABC': $indexstr = \question_utils::int_to_letter($index); break; - case "iii": + case 'iii': $indexstr = \question_utils::int_to_roman($index); break; - case "III": + case 'III': $indexstr = strtoupper(\question_utils::int_to_roman($index)); break; } @@ -241,17 +241,17 @@ private function replace_shuffled_indices(DOMNode $element, int $index): void { private function mangle_ids_and_names(): void { /** @var DOMAttr $attr */ foreach ( - $this->xpath->query(" + $this->xpath->query(' //xhtml:*/@id | //xhtml:label/@for | //xhtml:output/@for | //xhtml:input/@list | (//xhtml:button | //xhtml:form | //xhtml:fieldset | //xhtml:iframe | //xhtml:input | //xhtml:object | //xhtml:output | //xhtml:select | //xhtml:textarea | //xhtml:map)/@name | //xhtml:img/@usemap - ") as $attr + ') as $attr ) { $original = $attr->value; - if ($attr->name === "usemap" && str_starts_with($original, "#")) { + if ($attr->name === 'usemap' && str_starts_with($original, '#')) { // See https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/useMap. - $attr->value = "#" . $this->attempt->get_qt_field_name(substr($original, 1)); + $attr->value = '#' . $this->attempt->get_qt_field_name(substr($original, 1)); } else { $attr->value = $this->attempt->get_qt_field_name($original); } @@ -270,19 +270,19 @@ private function mangle_ids_and_names(): void { */ private function set_input_values_and_readonly(): void { /** @var DOMElement $element */ - foreach ($this->xpath->query("//xhtml:button | //xhtml:input | //xhtml:select | //xhtml:textarea") as $element) { + foreach ($this->xpath->query('//xhtml:button | //xhtml:input | //xhtml:select | //xhtml:textarea') as $element) { if ($this->options->readonly) { - $element->setAttribute("disabled", "disabled"); + $element->setAttribute('disabled', 'disabled'); } // We want the unmangled name here, so this method must be called before mangle_ids_and_names. - $name = $element->getAttribute("name"); + $name = $element->getAttribute('name'); if (!$name) { continue; } - if ($element->tagName == "input") { - $type = $element->getAttribute("type") ?: "text"; + if ($element->tagName == 'input') { + $type = $element->getAttribute('type') ?: 'text'; } else { $type = $element->tagName; } @@ -290,22 +290,22 @@ private function set_input_values_and_readonly(): void { // Set the last saved value. $lastvalue = $this->attempt->get_last_qt_var($name); if (!is_null($lastvalue)) { - if ($type === "checkbox" || $type === "radio") { - if ($element->getAttribute("value") === $lastvalue) { - $element->setAttribute("checked", "checked"); + if ($type === 'checkbox' || $type === 'radio') { + if ($element->getAttribute('value') === $lastvalue) { + $element->setAttribute('checked', 'checked'); } - } else if ($type == "select") { + } else if ($type == 'select') { // Find the appropriate option and mark it as selected. /** @var DOMElement $option */ - foreach ($element->getElementsByTagName("option") as $option) { - $optvalue = $option->hasAttribute("value") ? $option->getAttribute("value") : $option->textContent; + foreach ($element->getElementsByTagName('option') as $option) { + $optvalue = $option->hasAttribute('value') ? $option->getAttribute('value') : $option->textContent; if ($optvalue == $lastvalue) { - $option->setAttribute("selected", "selected"); + $option->setAttribute('selected', 'selected'); break; } } - } else if ($type != "button" && $type != "submit" && $type != "hidden") { - $element->setAttribute("value", $lastvalue); + } else if ($type != 'button' && $type != 'submit' && $type != 'hidden') { + $element->setAttribute('value', $lastvalue); } } } @@ -318,7 +318,7 @@ private function set_input_values_and_readonly(): void { */ private function clean_up(): void { /** @var DOMNode|DOMNameSpaceNode $node */ - foreach (iterator_to_array($this->xpath->query("//qpy:* | //@qpy:* | //comment() | //namespace::*")) as $node) { + foreach (iterator_to_array($this->xpath->query('//qpy:* | //@qpy:* | //comment() | //namespace::*')) as $node) { if ($node instanceof DOMAttr || $node instanceof DOMNameSpaceNode) { $node->parentNode->removeAttributeNS($node->namespaceURI, $node->localName); } else { @@ -338,23 +338,23 @@ private function clean_up(): void { private function resolve_placeholders(): void { /** @var DOMProcessingInstruction $pi */ foreach (iterator_to_array($this->xpath->query("//processing-instruction('p')")) as $pi) { - $parts = preg_split("/\s+/", trim($pi->data)); + $parts = preg_split('/\s+/', trim($pi->data)); $key = $parts[0]; - $cleanoption = $parts[1] ?? "clean"; + $cleanoption = $parts[1] ?? 'clean'; if (!isset($this->placeholders[$key])) { $pi->parentNode->removeChild($pi); } else { $rawvalue = $this->placeholders[$key]; - if (strcasecmp($cleanoption, "clean") == 0) { + if (strcasecmp($cleanoption, 'clean') == 0) { // Allow (X)HTML, but clean using Moodle's clean_text to prevent XSS. $element = $this->xpath->document->createDocumentFragment(); $element->appendXML(clean_text($rawvalue)); - } else if (strcasecmp($cleanoption, "noclean") == 0) { + } else if (strcasecmp($cleanoption, 'noclean') == 0) { $element = $this->xpath->document->createDocumentFragment(); $element->appendXML($rawvalue); } else { - if (strcasecmp($cleanoption, "plain") != 0) { + if (strcasecmp($cleanoption, 'plain') != 0) { debugging("Unrecognized placeholder cleaning option: '$cleanoption', using 'plain'"); } // Treat the value as plain text and don't allow any kind of markup. @@ -376,42 +376,42 @@ private function resolve_placeholders(): void { */ private function soften_validation(): void { /** @var DOMElement $element */ - foreach ($this->xpath->query("//xhtml:input[@pattern]") as $element) { - $pattern = $element->getAttribute("pattern"); - $element->removeAttribute("pattern"); - $element->setAttribute("data-qpy_pattern", $pattern); + foreach ($this->xpath->query('//xhtml:input[@pattern]') as $element) { + $pattern = $element->getAttribute('pattern'); + $element->removeAttribute('pattern'); + $element->setAttribute('data-qpy_pattern', $pattern); } - foreach ($this->xpath->query("(//xhtml:input | //xhtml:select | //xhtml:textarea)[@required]") as $element) { - $element->removeAttribute("required"); - $element->setAttribute("data-qpy_required", "data-qpy_required"); - $element->setAttribute("aria-required", "true"); + foreach ($this->xpath->query('(//xhtml:input | //xhtml:select | //xhtml:textarea)[@required]') as $element) { + $element->removeAttribute('required'); + $element->setAttribute('data-qpy_required', 'data-qpy_required'); + $element->setAttribute('aria-required', 'true'); } - foreach ($this->xpath->query("(//xhtml:input | //xhtml:textarea)[@minlength]") as $element) { - $minlength = $element->getAttribute("minlength"); - $element->removeAttribute("minlength"); - $element->setAttribute("data-qpy_minlength", $minlength); + foreach ($this->xpath->query('(//xhtml:input | //xhtml:textarea)[@minlength]') as $element) { + $minlength = $element->getAttribute('minlength'); + $element->removeAttribute('minlength'); + $element->setAttribute('data-qpy_minlength', $minlength); } - foreach ($this->xpath->query("(//xhtml:input | //xhtml:textarea)[@maxlength]") as $element) { - $maxlength = $element->getAttribute("maxlength"); - $element->removeAttribute("maxlength"); - $element->setAttribute("data-qpy_maxlength", $maxlength); + foreach ($this->xpath->query('(//xhtml:input | //xhtml:textarea)[@maxlength]') as $element) { + $maxlength = $element->getAttribute('maxlength'); + $element->removeAttribute('maxlength'); + $element->setAttribute('data-qpy_maxlength', $maxlength); } - foreach ($this->xpath->query("//xhtml:input[@min]") as $element) { - $min = $element->getAttribute("min"); - $element->removeAttribute("min"); - $element->setAttribute("data-qpy_min", $min); - $element->setAttribute("aria-valuemin", $min); + foreach ($this->xpath->query('//xhtml:input[@min]') as $element) { + $min = $element->getAttribute('min'); + $element->removeAttribute('min'); + $element->setAttribute('data-qpy_min', $min); + $element->setAttribute('aria-valuemin', $min); } - foreach ($this->xpath->query("//xhtml:input[@max]") as $element) { - $max = $element->getAttribute("max"); - $element->removeAttribute("max"); - $element->setAttribute("data-qpy_max", $max); - $element->setAttribute("aria-valuemax", $max); + foreach ($this->xpath->query('//xhtml:input[@max]') as $element) { + $max = $element->getAttribute('max'); + $element->removeAttribute('max'); + $element->setAttribute('data-qpy_max', $max); + $element->setAttribute('aria-valuemax', $max); } } @@ -429,18 +429,18 @@ private function add_styles(): void { | //xhtml:select | //xhtml:textarea ") as $element ) { - $this->add_class_names($element, "form-control", "qpy-input"); + $this->add_class_names($element, 'form-control', 'qpy-input'); } foreach ( $this->xpath->query("//xhtml:input[@type = 'button' or @type = 'submit' or @type = 'reset'] | //xhtml:button") as $element ) { - $this->add_class_names($element, "btn", "btn-primary", "qpy-input"); + $this->add_class_names($element, 'btn', 'btn-primary', 'qpy-input'); } foreach ($this->xpath->query("//xhtml:input[@type = 'checkbox' or @type = 'radio']") as $element) { - $this->add_class_names($element, "qpy-input"); + $this->add_class_names($element, 'qpy-input'); } } @@ -455,7 +455,7 @@ private function add_styles(): void { private function defuse_buttons(): void { /** @var DOMElement $element */ foreach ($this->xpath->query("(//xhtml:input | //xhtml:button)[@type = 'submit' or @type = 'reset']") as $element) { - $element->setAttribute("type", "button"); + $element->setAttribute('type', 'button'); } } @@ -473,18 +473,18 @@ private function defuse_buttons(): void { */ private function hide_if_role(): void { /** @var DOMAttr $attr */ - foreach (iterator_to_array($this->xpath->query("//@qpy:if-role")) as $attr) { - $allowedroles = preg_split("/[\s|]+/", $attr->value, -1, PREG_SPLIT_NO_EMPTY); + foreach (iterator_to_array($this->xpath->query('//@qpy:if-role')) as $attr) { + $allowedroles = preg_split('/[\s|]+/', $attr->value, -1, PREG_SPLIT_NO_EMPTY); - $isteacher = has_capability("mod/quiz:viewreports", $this->options->context); - $isscorer = has_capability("mod/quiz:grade", $this->options->context); + $isteacher = has_capability('mod/quiz:viewreports', $this->options->context); + $isscorer = has_capability('mod/quiz:grade', $this->options->context); $isdeveloper = $isteacher && debugging(); if ( - !(in_array("teacher", $allowedroles) && $isteacher - || in_array("proctor", $allowedroles) && $isteacher - || in_array("scorer", $allowedroles) && $isscorer - || in_array("developer", $allowedroles) && $isdeveloper) + !(in_array('teacher', $allowedroles) && $isteacher + || in_array('proctor', $allowedroles) && $isteacher + || in_array('scorer', $allowedroles) && $isscorer + || in_array('developer', $allowedroles) && $isdeveloper) ) { $attr->ownerElement->parentNode->removeChild($attr->ownerElement); } @@ -499,23 +499,23 @@ private function hide_if_role(): void { */ private function format_floats(): void { /** @var DOMElement $element */ - foreach (iterator_to_array($this->xpath->query("//qpy:format-float")) as $element) { + foreach (iterator_to_array($this->xpath->query('//qpy:format-float')) as $element) { $float = floatval($element->textContent); - $precision = intval($element->hasAttribute("precision") ? $element->getAttribute("precision") : -1); - $stripzeroes = $element->hasAttribute("strip-zeros"); + $precision = intval($element->hasAttribute('precision') ? $element->getAttribute('precision') : -1); + $stripzeroes = $element->hasAttribute('strip-zeros'); $str = format_float($float, $precision, true, $stripzeroes); - $thousandssep = $element->getAttribute("thousands-separator"); - if ($thousandssep === "yes") { - $thousandssep = get_string("thousandssep", "langconfig"); - } else if ($thousandssep === "no") { - $thousandssep = ""; + $thousandssep = $element->getAttribute('thousands-separator'); + if ($thousandssep === 'yes') { + $thousandssep = get_string('thousandssep', 'langconfig'); + } else if ($thousandssep === 'no') { + $thousandssep = ''; } - if ($thousandssep !== "") { - $decsep = get_string("decsep", "langconfig"); + if ($thousandssep !== '') { + $decsep = get_string('decsep', 'langconfig'); $decimalpos = strpos($str, $decsep); if ($decimalpos === false) { // No decimal, start at the end of the number. @@ -541,7 +541,7 @@ private function format_floats(): void { */ private function add_class_names(DOMElement $element, string ...$newclasses): void { $classarray = []; - for ($class = strtok($element->getAttribute("class"), " \t\n"); $class; $class = strtok(" \t\n")) { + for ($class = strtok($element->getAttribute('class'), " \t\n"); $class; $class = strtok(" \t\n")) { $classarray[] = $class; } @@ -551,7 +551,7 @@ private function add_class_names(DOMElement $element, string ...$newclasses): vo } } - $element->setAttribute("class", implode(" ", $classarray)); + $element->setAttribute('class', implode(' ', $classarray)); } /** @@ -566,15 +566,15 @@ private function replace_qpy_urls(string $input): string { return preg_replace_callback( // The first two path segments are namespace and short name, and so more restrictive. - ";qpy://static((?:/[a-z_][a-z0-9_]{0,126}){2}(?:/[\w\-@:%+.~=]+)+);", + ';qpy://static((?:/[a-z_][a-z0-9_]{0,126}){2}(?:/[\w\-@:%+.~=]+)+);', function (array $match) use ($question) { $path = $match[1]; $url = \moodle_url::make_pluginfile_url( $question->contextid, - "qtype_questionpy", - "static", + 'qtype_questionpy', + 'static', null, - "/" . $question->packagehash . dirname($path) . "/", + '/' . $question->packagehash . dirname($path) . '/', basename($path) ); diff --git a/classes/static_file_service.php b/classes/static_file_service.php index 8472c4e8..1312efdf 100644 --- a/classes/static_file_service.php +++ b/classes/static_file_service.php @@ -65,14 +65,14 @@ public function __construct(api $api, package_file_service $packagefileservice) * @throws invalid_dataroot_permissions */ public function download_public_static_file(string $packagehash, string $namespace, string $shortname, string $path): ?array { - $path = ltrim($path, "/"); + $path = ltrim($path, '/'); $packagefileiflocal = $this->packagefileservice->get_file_by_package_hash($packagehash, context_system::instance()->id); $temppath = make_request_directory() . "/$packagehash/$namespace/$shortname/$path"; make_writable_directory(dirname($temppath)); $mimetype = $this->api->package($packagehash, $packagefileiflocal) - ->download_static_file($namespace, $shortname, "static", $path, $temppath); + ->download_static_file($namespace, $shortname, 'static', $path, $temppath); if (is_null($mimetype)) { return null; diff --git a/classes/utils.php b/classes/utils.php index 39c7d85f..48bbd34d 100644 --- a/classes/utils.php +++ b/classes/utils.php @@ -53,7 +53,7 @@ public static function &ensure_exists(array &$array, string $key): array { */ public static function array_get_nested(array $array, string $key) { // Explode a $name like qpy_form[abc][def] into an array ["qpy_form", "abc", "def"]. - $parts = explode("[", str_replace("]", "", $key)); + $parts = explode('[', str_replace(']', '', $key)); $current = $array; foreach ($parts as $key) { @@ -75,7 +75,7 @@ public static function array_get_nested(array $array, string $key) { */ public static function array_create_nested(string $key, $value): array { // Explode a $name like qpy_form[abc][def] into an array ["qpy_form", "abc", "def"]. - $parts = explode("[", str_replace("]", "", $key)); + $parts = explode('[', str_replace(']', '', $key)); $array = []; $current = &$array; diff --git a/lang/en/qtype_questionpy.php b/lang/en/qtype_questionpy.php index 16f1e964..ab9da1dc 100644 --- a/lang/en/qtype_questionpy.php +++ b/lang/en/qtype_questionpy.php @@ -29,8 +29,8 @@ $string['event_grading_response_failed'] = 'Grading response failed'; $string['event_starting_attempt_failed'] = 'Starting attempt failed'; $string['event_viewing_attempt_failed'] = 'Viewing attempt failed'; -$string['form_fallback_element_text'] = "The QuestionPy package is using a form element not supported by the Moodle" - . " plugin. Please ensure you are using a compatible package or contact your administrators."; +$string['form_fallback_element_text'] = 'The QuestionPy package is using a form element not supported by the Moodle' + . ' plugin. Please ensure you are using a compatible package or contact your administrators.'; $string['formerror_noqpy_package'] = 'Selected file must be of type .qpy'; $string['json_parsing_error'] = 'Could not parse data to JSON.'; $string['load_packages_button'] = 'Load Packages'; diff --git a/lib.php b/lib.php index ff53861f..6e4dd8c4 100644 --- a/lib.php +++ b/lib.php @@ -42,7 +42,7 @@ function qtype_questionpy_pluginfile($course, $cm, $context, $filearea, $args, $ global $CFG; require_once($CFG->libdir . '/questionlib.php'); - if ($filearea !== "static") { + if ($filearea !== 'static') { // TODO: Support static-private files. send_file_not_found(); } @@ -50,7 +50,7 @@ function qtype_questionpy_pluginfile($course, $cm, $context, $filearea, $args, $ $staticfileservice = di::get(static_file_service::class); [$packagehash, $namespace, $shortname] = $args; - $path = implode("/", array_slice($args, 3)); + $path = implode('/', array_slice($args, 3)); [$filepath, $mimetype] = $staticfileservice->download_public_static_file($packagehash, $namespace, $shortname, $path); if (is_null($filepath)) { @@ -64,6 +64,6 @@ function qtype_questionpy_pluginfile($course, $cm, $context, $filearea, $args, $ basename($path), lifetime: 31536000, mimetype: $mimetype, - options: ["immutable" => true, "cacheability" => "public"] + options: ['immutable' => true, 'cacheability' => 'public'] ); } diff --git a/question.php b/question.php index 5f2c0a1b..691fe868 100644 --- a/question.php +++ b/question.php @@ -198,7 +198,7 @@ public function apply_attempt_state(question_attempt_step $step) { private function get_behaviour(): qbehaviour_questionpy { if ($this->behaviour === null) { throw new coding_exception( - "qtype_questionpy_question->behaviour is not set, does the question use the wrong behaviour?" + 'qtype_questionpy_question->behaviour is not set, does the question use the wrong behaviour?' ); } return $this->behaviour; @@ -255,7 +255,7 @@ public function is_complete_response(array $response): bool { } foreach ($this->metadata->extract()->requiredfields as $requiredfield) { - if (!isset($response[$requiredfield]) || $response[$requiredfield] === "") { + if (!isset($response[$requiredfield]) || $response[$requiredfield] === '') { return false; } } @@ -371,7 +371,7 @@ public function grade_response(array $response): array { */ public function compute_final_grade($responses, $totaltries) { // TODO: This is necessary to support interactive countback. - throw new coding_exception("not implemented"); + throw new coding_exception('not implemented'); } /** @@ -383,7 +383,7 @@ public function compute_final_grade($responses, $totaltries) { * @throws coding_exception */ public function make_behaviour(question_attempt $qa, $preferredbehaviour): question_behaviour { - question_engine::load_behaviour_class("questionpy"); + question_engine::load_behaviour_class('questionpy'); $delegate = parent::make_behaviour($qa, $preferredbehaviour); return new qbehaviour_questionpy($qa, $preferredbehaviour, $delegate); } diff --git a/renderer.php b/renderer.php index 014a9f20..c2b7346a 100644 --- a/renderer.php +++ b/renderer.php @@ -38,7 +38,7 @@ class qtype_questionpy_renderer extends qtype_renderer { * @return string HTML fragment. */ public function head_code(question_attempt $qa) { - $this->page->requires->js_call_amd("qtype_questionpy/view_question", "init"); + $this->page->requires->js_call_amd('qtype_questionpy/view_question', 'init'); return parent::head_code($qa); } diff --git a/tests/array_converter/array_converter_test.php b/tests/array_converter/array_converter_test.php index a4102401..e9f3864f 100644 --- a/tests/array_converter/array_converter_test.php +++ b/tests/array_converter/array_converter_test.php @@ -34,73 +34,73 @@ */ final class array_converter_test extends \advanced_testcase { public function test_should_deserialize_from_rename(): void { - require_once(__DIR__ . "/test_classes/uses_rename_and_alias.php"); + require_once(__DIR__ . '/test_classes/uses_rename_and_alias.php'); - $result = array_converter::from_array(uses_rename_and_alias::class, ["my_prop_1" => "value1", "my_prop_2" => "value2"]); + $result = array_converter::from_array(uses_rename_and_alias::class, ['my_prop_1' => 'value1', 'my_prop_2' => 'value2']); $this->assertEquals(uses_rename_and_alias::class, get_class($result)); - $this->assertEquals("value1", $result->myprop1); - $this->assertEquals("value2", $result->myprop2); + $this->assertEquals('value1', $result->myprop1); + $this->assertEquals('value2', $result->myprop2); } public function test_should_serialize_to_rename(): void { - require_once(__DIR__ . "/test_classes/uses_rename_and_alias.php"); + require_once(__DIR__ . '/test_classes/uses_rename_and_alias.php'); - $instance = new uses_rename_and_alias("value2"); - $instance->myprop1 = "value1"; + $instance = new uses_rename_and_alias('value2'); + $instance->myprop1 = 'value1'; $result = array_converter::to_array($instance); $this->assertEquals($result, [ - "my_prop_1" => "value1", - "my_prop_2" => "value2", + 'my_prop_1' => 'value1', + 'my_prop_2' => 'value2', ]); } public function test_should_deserialize_from_alias(): void { - require_once(__DIR__ . "/test_classes/uses_rename_and_alias.php"); + require_once(__DIR__ . '/test_classes/uses_rename_and_alias.php'); - $result = array_converter::from_array(uses_rename_and_alias::class, ["my_alias_1" => "value1", "my_alias_2" => "value2"]); + $result = array_converter::from_array(uses_rename_and_alias::class, ['my_alias_1' => 'value1', 'my_alias_2' => 'value2']); $this->assertEquals(uses_rename_and_alias::class, get_class($result)); - $this->assertEquals("value1", $result->myprop1); - $this->assertEquals("value2", $result->myprop2); + $this->assertEquals('value1', $result->myprop1); + $this->assertEquals('value2', $result->myprop2); } public function test_should_deserialize_array_elements(): void { - require_once(__DIR__ . "/test_classes/uses_element_class.php"); + require_once(__DIR__ . '/test_classes/uses_element_class.php'); - $result = array_converter::from_array(uses_element_class::class, ["myarray" => [ - ["prop" => "value1"], - ["prop" => "value2"], + $result = array_converter::from_array(uses_element_class::class, ['myarray' => [ + ['prop' => 'value1'], + ['prop' => 'value2'], ]]); $this->assertEquals(uses_element_class::class, get_class($result)); - $this->assertEquals([new simple("value1"), new simple("value2")], $result->myarray); + $this->assertEquals([new simple('value1'), new simple('value2')], $result->myarray); } public function test_should_deserialize_polymorphic(): void { - require_once(__DIR__ . "/test_classes/polymorphic.php"); - require_once(__DIR__ . "/test_classes/variant2.php"); + require_once(__DIR__ . '/test_classes/polymorphic.php'); + require_once(__DIR__ . '/test_classes/variant2.php'); $result = array_converter::from_array(polymorphic::class, [ - "discriminator" => "var2", - "prop" => "value1", + 'discriminator' => 'var2', + 'prop' => 'value1', ]); $this->assertEquals(variant2::class, get_class($result)); - $this->assertEquals("value1", $result->prop); + $this->assertEquals('value1', $result->prop); } public function test_should_deserialize_polymorphic_fallback(): void { - require_once(__DIR__ . "/test_classes/polymorphic.php"); + require_once(__DIR__ . '/test_classes/polymorphic.php'); $result = array_converter::from_array(polymorphic::class, [ - "discriminator" => "abcdefg", - "prop" => "value2", + 'discriminator' => 'abcdefg', + 'prop' => 'value2', ]); $this->assertEquals(simple::class, get_class($result)); - $this->assertEquals("value2", $result->prop); + $this->assertEquals('value2', $result->prop); $this->assertDebuggingCalled("Unknown value for discriminator 'discriminator': 'abcdefg'. Using fallback " . "variant 'qtype_questionpy\\array_converter\\test_classes\\simple'."); diff --git a/tests/array_converter/test_classes/polymorphic.php b/tests/array_converter/test_classes/polymorphic.php index 179de1ee..b478bd01 100644 --- a/tests/array_converter/test_classes/polymorphic.php +++ b/tests/array_converter/test_classes/polymorphic.php @@ -20,7 +20,7 @@ defined('MOODLE_INTERNAL') || die; -require_once(__DIR__ . "/simple.php"); +require_once(__DIR__ . '/simple.php'); /** * Test class using {@see array_polymorphic}. @@ -30,6 +30,6 @@ * @copyright 2024 TU Berlin, innoCampus {@link https://www.questionpy.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -#[array_polymorphic("discriminator", ["var1" => variant1::class, "var2" => variant2::class], simple::class)] +#[array_polymorphic('discriminator', ['var1' => variant1::class, 'var2' => variant2::class], simple::class)] class polymorphic extends simple { } diff --git a/tests/array_converter/test_classes/uses_element_class.php b/tests/array_converter/test_classes/uses_element_class.php index b1bee436..941147f2 100644 --- a/tests/array_converter/test_classes/uses_element_class.php +++ b/tests/array_converter/test_classes/uses_element_class.php @@ -20,7 +20,7 @@ defined('MOODLE_INTERNAL') || die; -require_once(__DIR__ . "/simple.php"); +require_once(__DIR__ . '/simple.php'); /** * Test class using {@see array_element_class}. diff --git a/tests/array_converter/test_classes/uses_rename_and_alias.php b/tests/array_converter/test_classes/uses_rename_and_alias.php index 5fab7c99..5a3d09e4 100644 --- a/tests/array_converter/test_classes/uses_rename_and_alias.php +++ b/tests/array_converter/test_classes/uses_rename_and_alias.php @@ -29,8 +29,8 @@ */ class uses_rename_and_alias { /** @var string $myprop1 */ - #[array_key("my_prop_1")] - #[array_alias("my_alias_1")] + #[array_key('my_prop_1')] + #[array_alias('my_alias_1')] public string $myprop1; /** @@ -40,8 +40,8 @@ class uses_rename_and_alias { */ public function __construct( /** @var string $myprop2 */ - #[array_key("my_prop_2")] - #[array_alias("my_alias_2")] + #[array_key('my_prop_2')] + #[array_alias('my_alias_2')] public string $myprop2 ) { } diff --git a/tests/array_converter/test_classes/variant1.php b/tests/array_converter/test_classes/variant1.php index d103a35c..d759ba21 100644 --- a/tests/array_converter/test_classes/variant1.php +++ b/tests/array_converter/test_classes/variant1.php @@ -18,7 +18,7 @@ defined('MOODLE_INTERNAL') || die; -require_once(__DIR__ . "/polymorphic.php"); +require_once(__DIR__ . '/polymorphic.php'); /** * A variant of {@see polymorphic}. diff --git a/tests/array_converter/test_classes/variant2.php b/tests/array_converter/test_classes/variant2.php index 7df01a9e..1cebec82 100644 --- a/tests/array_converter/test_classes/variant2.php +++ b/tests/array_converter/test_classes/variant2.php @@ -18,7 +18,7 @@ defined('MOODLE_INTERNAL') || die; -require_once(__DIR__ . "/polymorphic.php"); +require_once(__DIR__ . '/polymorphic.php'); /** * A variant of {@see polymorphic}. diff --git a/tests/data_provider.php b/tests/data_provider.php index 51ab9b9e..a35b4c97 100644 --- a/tests/data_provider.php +++ b/tests/data_provider.php @@ -104,44 +104,44 @@ function package_versions_info_provider(?array $packageinfo = null, ?array $vers */ function element_provider(): array { return [ - ["checkbox", (new checkbox_element("my_checkbox", "Left", "Right", true, true)) - ->disable_if(new is_checked("chk1")) - ->help("Help text"), + ['checkbox', (new checkbox_element('my_checkbox', 'Left', 'Right', true, true)) + ->disable_if(new is_checked('chk1')) + ->help('Help text'), ], - ["checkbox_group", new checkbox_group_element( + ['checkbox_group', new checkbox_group_element( (new checkbox_element( - "my_checkbox", - "Left", - "Right", + 'my_checkbox', + 'Left', + 'Right', true, true - ))->help("Help text") + ))->help('Help text') ), ], - ["group", (new group_element("my_group", "Name", [ - new text_input_element("first_name", "", true, null, "Vorname"), - new text_input_element("last_name", "", false, null, "Nachname (optional)"), + ['group', (new group_element('my_group', 'Name', [ + new text_input_element('first_name', '', true, null, 'Vorname'), + new text_input_element('last_name', '', false, null, 'Nachname (optional)'), ])) - ->hide_if(new is_not_checked("chk1")) - ->help("Help text"), + ->hide_if(new is_not_checked('chk1')) + ->help('Help text'), ], - ["hidden", (new hidden_element("my_hidden_value", "42"))->disable_if(new equals("input1", 7))], - ["radio_group", (new radio_group_element("my_radio", "Label", [ - new option("Option 1", "opt1", true), - new option("Option 2", "opt2"), - ], true))->disable_if(new does_not_equal("input1", "")), + ['hidden', (new hidden_element('my_hidden_value', '42'))->disable_if(new equals('input1', 7))], + ['radio_group', (new radio_group_element('my_radio', 'Label', [ + new option('Option 1', 'opt1', true), + new option('Option 2', 'opt2'), + ], true))->disable_if(new does_not_equal('input1', '')), ], - ["repetition", new repetition_element("my_rep", 3, 2, null, [ - new text_input_element("item", "Label"), + ['repetition', new repetition_element('my_rep', 3, 2, null, [ + new text_input_element('item', 'Label'), ]), ], - ["select", (new select_element("my_select", "Label", [ - new option("Option 1", "opt1", true), - new option("Option 2", "opt2"), - ], true, true))->disable_if(new in("input1", ["valid", "also valid"])), + ['select', (new select_element('my_select', 'Label', [ + new option('Option 1', 'opt1', true), + new option('Option 2', 'opt2'), + ], true, true))->disable_if(new in('input1', ['valid', 'also valid'])), ], - ["static_text", new static_text_element("my_text", "Label", "Lorem ipsum dolor sit amet.")], - ["input", new text_input_element("my_field", "Label", true, "default", "placeholder")], - ["textarea", new text_area_element("my_field", "Label", true, "default", "placeholder")], + ['static_text', new static_text_element('my_text', 'Label', 'Lorem ipsum dolor sit amet.')], + ['input', new text_input_element('my_field', 'Label', true, 'default', 'placeholder')], + ['textarea', new text_area_element('my_field', 'Label', true, 'default', 'placeholder')], ]; } diff --git a/tests/external/search_packages_test.php b/tests/external/search_packages_test.php index 5c463c0e..3536a57e 100644 --- a/tests/external/search_packages_test.php +++ b/tests/external/search_packages_test.php @@ -175,7 +175,7 @@ public static function invalid_page_value_provider(): array { */ public function test_with_invalid_page_value(int $page): void { $this->expectException(\invalid_parameter_exception::class); - $this->expectExceptionMessageMatches("/.*can not be negative.*/"); + $this->expectExceptionMessageMatches('/.*can not be negative.*/'); search_packages::execute('Test query', [], 'all', 'alpha', 'asc', 1, $page, null); } @@ -656,9 +656,9 @@ public function test_recently_used_package_not_available_across_different_course $this->getDataGenerator()->enrol_user($user->id, $course2->id); // Create package in one course and use it. - [, [$id1]] = package_versions_info_provider(['namespace' => "ns1"])->upsert(); + [, [$id1]] = package_versions_info_provider(['namespace' => 'ns1'])->upsert(); self::add_last_used_entry($id1, $course1context->id); - [, [$id2]] = package_versions_info_provider(['namespace' => "ns2"])->upsert(); + [, [$id2]] = package_versions_info_provider(['namespace' => 'ns2'])->upsert(); self::add_last_used_entry($id2, $course2context->id); // Execute service with both context ids. @@ -705,8 +705,8 @@ public function test_favourites_returns_packages_marked_as_favourite_and_isfavou $this->setUser($user); // Create two packages. - [, [$pkgversionid]] = package_versions_info_provider(['namespace' => "ns1"])->upsert(); - package_versions_info_provider(['namespace' => "ns2"])->upsert(); + [, [$pkgversionid]] = package_versions_info_provider(['namespace' => 'ns1'])->upsert(); + package_versions_info_provider(['namespace' => 'ns2'])->upsert(); // Favourite one package. $usercontext = context_user::instance($user->id); @@ -752,8 +752,8 @@ public function test_favourites_are_not_shared_across_users(): void { $user2service = \core_favourites\service_factory::get_service_for_user_context($user2context); // Create two server packages. - [, [$pkgversion1]] = package_versions_info_provider(['namespace' => "ns1"])->upsert(); - [, [$pkgversion2]] = package_versions_info_provider(['namespace' => "ns2"])->upsert(); + [, [$pkgversion1]] = package_versions_info_provider(['namespace' => 'ns1'])->upsert(); + [, [$pkgversion2]] = package_versions_info_provider(['namespace' => 'ns2'])->upsert(); // Both users favourite different packages. self::favourite($user1service, $user1context, $pkgversion1); diff --git a/tests/form/elements/element_html_test.php b/tests/form/elements/element_html_test.php index 7ff5ab79..40127b3c 100644 --- a/tests/form/elements/element_html_test.php +++ b/tests/form/elements/element_html_test.php @@ -18,8 +18,8 @@ defined('MOODLE_INTERNAL') || die(); -require_once(__DIR__ . "/test_moodleform.php"); -require_once(__DIR__ . "/../../data_provider.php"); +require_once(__DIR__ . '/test_moodleform.php'); +require_once(__DIR__ . '/../../data_provider.php'); use qtype_questionpy\form\qpy_renderable; use function qtype_questionpy\element_provider; @@ -51,10 +51,10 @@ final class element_html_test extends \advanced_testcase { * @covers \qtype_questionpy\form\qpy_renderable */ public function test_rendered_html_should_match_snapshot(string $elementkind, qpy_renderable $element): void { - $snapshotfilepath = __DIR__ . "/html/" . $elementkind . ".html"; + $snapshotfilepath = __DIR__ . '/html/' . $elementkind . '.html'; // The sesskey is part of the form and therefore needs to be deterministic. - $_SESSION['USER']->sesskey = "sesskey"; + $_SESSION['USER']->sesskey = 'sesskey'; $form = new test_moodleform($element); $actualhtml = $form->render(); @@ -63,7 +63,7 @@ public function test_rendered_html_should_match_snapshot(string $elementkind, qp $actualdom->loadHTML($actualhtml); $actualdom->preserveWhiteSpace = false; - if (getenv("UPDATE_SNAPSHOTS")) { + if (getenv('UPDATE_SNAPSHOTS')) { $actualdom->saveHTMLFile($snapshotfilepath); echo "Updated snapshot $snapshotfilepath."; } diff --git a/tests/form/elements/element_json_test.php b/tests/form/elements/element_json_test.php index 706f3b3e..d03a62fc 100644 --- a/tests/form/elements/element_json_test.php +++ b/tests/form/elements/element_json_test.php @@ -18,7 +18,7 @@ defined('MOODLE_INTERNAL') || die(); -require_once(__DIR__ . "/../../data_provider.php"); +require_once(__DIR__ . '/../../data_provider.php'); use qtype_questionpy\array_converter\array_converter; use function qtype_questionpy\element_provider; @@ -41,7 +41,7 @@ final class element_json_test extends \advanced_testcase { * @covers \qtype_questionpy\form\elements */ public function test_deserialize(string $elementkind, $expected): void { - $json = file_get_contents(__DIR__ . "/json/" . $elementkind . ".json"); + $json = file_get_contents(__DIR__ . '/json/' . $elementkind . '.json'); $array = json_decode($json, true); $actual = array_converter::from_array(form_element::class, $array); @@ -60,7 +60,7 @@ public function test_deserialize(string $elementkind, $expected): void { public function test_serialize(string $elementkind, $value): void { $array = array_converter::to_array($value); $actualjson = json_encode($array); - $expectedjsonfilename = __DIR__ . "/json/" . $elementkind . ".json"; + $expectedjsonfilename = __DIR__ . '/json/' . $elementkind . '.json'; $this->assertJsonStringEqualsJsonFile($expectedjsonfilename, $actualjson); } diff --git a/tests/form/elements/test_moodleform.php b/tests/form/elements/test_moodleform.php index c3159224..76b62380 100644 --- a/tests/form/elements/test_moodleform.php +++ b/tests/form/elements/test_moodleform.php @@ -19,7 +19,7 @@ defined('MOODLE_INTERNAL') || die(); global $CFG; -require_once($CFG->libdir . "/formslib.php"); +require_once($CFG->libdir . '/formslib.php'); use qtype_questionpy\form\context\root_render_context; use qtype_questionpy\form\qpy_renderable; @@ -45,7 +45,7 @@ class test_moodleform extends \moodleform { */ public function __construct(qpy_renderable $element) { $this->element = $element; - parent::__construct(null, null, "post", "", ["id" => "my_form"]); + parent::__construct(null, null, 'post', '', ['id' => 'my_form']); } /** @@ -54,7 +54,7 @@ public function __construct(qpy_renderable $element) { * Output can be retrieved using {@see render}, which calls this method. */ protected function definition() { - $context = new root_render_context($this, $this->_form, "qpy_form", []); + $context = new root_render_context($this, $this->_form, 'qpy_form', []); $this->element->render_to($context); } } diff --git a/tests/question_service_test.php b/tests/question_service_test.php index a8c47708..a26e7228 100644 --- a/tests/question_service_test.php +++ b/tests/question_service_test.php @@ -18,7 +18,7 @@ defined('MOODLE_INTERNAL') || die(); -require_once(__DIR__ . "/data_provider.php"); +require_once(__DIR__ . '/data_provider.php'); use coding_exception; use dml_exception; @@ -53,7 +53,7 @@ protected function setUp(): void { $this->resetAfterTest(); $this->api = $this->createMock(api::class); $this->packageapi = $this->createMock(package_api::class); - $this->api->method("package") + $this->api->method('package') ->willReturn($this->packageapi); $packagefileservice = new package_file_service(); @@ -75,10 +75,10 @@ public function test_get_question_should_load_package_and_state(): void { $this->assertEquals( (object)[ - "qpy_id" => $qpyid, - "qpy_package_hash" => $pvi->versions[0]->hash, - "qpy_state" => $statestr, - "qpy_is_local" => "0", + 'qpy_id' => $qpyid, + 'qpy_package_hash' => $pvi->versions[0]->hash, + 'qpy_state' => $statestr, + 'qpy_is_local' => '0', ], $result ); @@ -106,28 +106,28 @@ public function test_get_question_should_return_empty_object_when_no_record(): v public function test_upsert_question_should_update_existing_record_if_changed(): void { global $PAGE; - $pvi = package_versions_info_provider(null, [["version" => "0.2.0"], ["version" => "0.1.0"]]); + $pvi = package_versions_info_provider(null, [['version' => '0.2.0'], ['version' => '0.1.0']]); $pvi->upsert(); $oldstate = $this->setup_question($pvi->versions[1]->hash)[0]; - $newstate = json_encode(["this is" => "new state"]); - $formdata = ["this is" => "form data"]; + $newstate = json_encode(['this is' => 'new state']); + $formdata = ['this is' => 'form data']; $this->packageapi ->expects($this->once()) - ->method("create_question") + ->method('create_question') ->with($oldstate, (object) $formdata) - ->willReturn(new question_response($newstate, "")); + ->willReturn(new question_response($newstate, '')); $this->questionservice->upsert_question( (object)[ - "id" => 1, - "qpy_package_hash" => $pvi->versions[0]->hash, - "qpy_form" => $formdata, - "qpy_package_source" => "search", - "oldparent" => 1, - "context" => $PAGE->context, + 'id' => 1, + 'qpy_package_hash' => $pvi->versions[0]->hash, + 'qpy_form' => $formdata, + 'qpy_package_source' => 'search', + 'oldparent' => 1, + 'context' => $PAGE->context, ] ); @@ -150,22 +150,22 @@ public function test_upsert_question_should_do_nothing_if_unchanged(): void { $oldstate = $this->setup_question($pvi->versions[0]->hash)[0]; - $formdata = ["this is" => "form data"]; + $formdata = ['this is' => 'form data']; $this->packageapi ->expects($this->once()) - ->method("create_question") + ->method('create_question') ->with($oldstate, (object) $formdata) - ->willReturn(new question_response($oldstate, "")); + ->willReturn(new question_response($oldstate, '')); $this->questionservice->upsert_question( (object)[ - "id" => 1, - "qpy_package_hash" => $pvi->versions[0]->hash, - "qpy_form" => $formdata, - "qpy_package_source" => "search", - "oldparent" => 1, - "context" => $PAGE->context, + 'id' => 1, + 'qpy_package_hash' => $pvi->versions[0]->hash, + 'qpy_form' => $formdata, + 'qpy_package_source' => 'search', + 'oldparent' => 1, + 'context' => $PAGE->context, ] ); @@ -190,25 +190,25 @@ public function test_upsert_question_should_insert_record(): void { // Since the package data is available in the database we should not contact the server. $this->api ->expects($this->never()) - ->method("get_package_info"); + ->method('get_package_info'); - $newstate = json_encode(["this is" => "new state"]); - $formdata = ["this is" => "form data"]; + $newstate = json_encode(['this is' => 'new state']); + $formdata = ['this is' => 'form data']; $this->packageapi ->expects($this->once()) - ->method("create_question") + ->method('create_question') ->with(null, (object) $formdata) - ->willReturn(new question_response($newstate, "")); + ->willReturn(new question_response($newstate, '')); $this->questionservice->upsert_question( (object)[ - "id" => 42, // Does not exist in the qtype_questionpy table yet. - "qpy_package_hash" => $pvi->versions[0]->hash, - "qpy_form" => $formdata, - "qpy_package_source" => "search", - "oldparent" => 1, - "context" => $PAGE->context, + 'id' => 42, // Does not exist in the qtype_questionpy table yet. + 'qpy_package_hash' => $pvi->versions[0]->hash, + 'qpy_form' => $formdata, + 'qpy_package_source' => 'search', + 'oldparent' => 1, + 'context' => $PAGE->context, ] ); @@ -224,36 +224,36 @@ public function test_upsert_question_should_insert_record(): void { public function test_upsert_question_should_retrieve_package_from_server_if_not_in_db(): void { global $PAGE; - $hash = hash("sha256", rand()); + $hash = hash('sha256', rand()); $rawpackage = array_converter::from_array( package_raw::class, - ["package_hash" => $hash, "short_name" => "sn", "namespace" => "ns", "name" => ["en" => "name"], "type" => "X"] + ['package_hash' => $hash, 'short_name' => 'sn', 'namespace' => 'ns', 'name' => ['en' => 'name'], 'type' => 'X'] ); // Retrieve the package data from the application serve. $this->api ->expects($this->once()) - ->method("get_package_info") + ->method('get_package_info') ->with($hash) ->willReturn($rawpackage); - $newstate = json_encode(["this is" => "new state"]); - $formdata = ["this is" => "form data"]; + $newstate = json_encode(['this is' => 'new state']); + $formdata = ['this is' => 'form data']; $this->packageapi ->expects($this->once()) - ->method("create_question") + ->method('create_question') ->with(null, (object) $formdata) - ->willReturn(new question_response($newstate, "")); + ->willReturn(new question_response($newstate, '')); $this->questionservice->upsert_question( (object)[ - "id" => 42, // Does not exist in the qtype_questionpy table yet. - "qpy_package_hash" => $hash, - "qpy_form" => $formdata, - "qpy_package_source" => "search", - "oldparent" => 1, - "context" => $PAGE->context, + 'id' => 42, // Does not exist in the qtype_questionpy table yet. + 'qpy_package_hash' => $hash, + 'qpy_form' => $formdata, + 'qpy_package_source' => 'search', + 'oldparent' => 1, + 'context' => $PAGE->context, ] ); @@ -277,23 +277,23 @@ public function test_upsert_question_should_add_package_to_last_used_table(): vo $package = package::get_by_version($pkgversionid); - $newstate = json_encode(["this is" => "new state"]); - $formdata = ["this is" => "form data"]; + $newstate = json_encode(['this is' => 'new state']); + $formdata = ['this is' => 'form data']; $this->packageapi ->expects($this->once()) - ->method("create_question") + ->method('create_question') ->with(null, (object) $formdata) - ->willReturn(new question_response($newstate, "")); + ->willReturn(new question_response($newstate, '')); $this->questionservice->upsert_question( (object)[ - "id" => 42, // Does not exist in the qtype_questionpy table yet. - "qpy_package_hash" => $pvi->versions[0]->hash, - "qpy_form" => $formdata, - "qpy_package_source" => "search", - "oldparent" => 1, - "context" => $PAGE->context, + 'id' => 42, // Does not exist in the qtype_questionpy table yet. + 'qpy_package_hash' => $pvi->versions[0]->hash, + 'qpy_form' => $formdata, + 'qpy_package_source' => 'search', + 'oldparent' => 1, + 'context' => $PAGE->context, ] ); @@ -319,23 +319,23 @@ public function test_upsert_question_in_same_context_with_same_package_should_on $package = package::get_by_version($pkgversionid); - $newstate = json_encode(["this is" => "new state"]); - $formdata = ["this is" => "form data"]; + $newstate = json_encode(['this is' => 'new state']); + $formdata = ['this is' => 'form data']; $this->packageapi ->expects($this->exactly(2)) - ->method("create_question") + ->method('create_question') ->with(null, (object) $formdata) - ->willReturn(new question_response($newstate, "")); + ->willReturn(new question_response($newstate, '')); $this->questionservice->upsert_question( (object)[ - "id" => 42, // Does not exist in the qtype_questionpy table yet. - "qpy_package_hash" => $pvi->versions[0]->hash, - "qpy_form" => $formdata, - "qpy_package_source" => "search", - "oldparent" => 1, - "context" => $PAGE->context, + 'id' => 42, // Does not exist in the qtype_questionpy table yet. + 'qpy_package_hash' => $pvi->versions[0]->hash, + 'qpy_form' => $formdata, + 'qpy_package_source' => 'search', + 'oldparent' => 1, + 'context' => $PAGE->context, ] ); @@ -347,12 +347,12 @@ public function test_upsert_question_in_same_context_with_same_package_should_on $this->questionservice->upsert_question( (object)[ - "id" => 43, // Does not exist in the qtype_questionpy table yet. - "qpy_package_hash" => $pvi->versions[0]->hash, - "qpy_form" => $formdata, - "qpy_package_source" => "search", - "oldparent" => 1, - "context" => $PAGE->context, + 'id' => 43, // Does not exist in the qtype_questionpy table yet. + 'qpy_package_hash' => $pvi->versions[0]->hash, + 'qpy_form' => $formdata, + 'qpy_package_source' => 'search', + 'oldparent' => 1, + 'context' => $PAGE->context, ] ); @@ -379,11 +379,11 @@ public function test_delete_question(): void { $this->setup_question($pvi->versions[0]->hash); global $DB; - $this->assertEquals(1, $DB->count_records("qtype_questionpy")); + $this->assertEquals(1, $DB->count_records('qtype_questionpy')); question_service::delete_question(1); - $this->assertEquals(0, $DB->count_records("qtype_questionpy")); + $this->assertEquals(0, $DB->count_records('qtype_questionpy')); } /** @@ -401,12 +401,12 @@ private function setup_question(string $pkgversionhash): array { '; global $DB; - $qpyid = $DB->insert_record("qtype_questionpy", [ - "id" => 1, - "questionid" => 1, - "pkgversionhash" => $pkgversionhash, - "islocal" => false, - "state" => $statestr, + $qpyid = $DB->insert_record('qtype_questionpy', [ + 'id' => 1, + 'questionid' => 1, + 'pkgversionhash' => $pkgversionhash, + 'islocal' => false, + 'state' => $statestr, ]); return [$statestr, $qpyid]; @@ -423,7 +423,7 @@ private function setup_question(string $pkgversionhash): array { */ private function assert_single_question(int $id, string $pkgversionhash, string $state) { global $DB; - $records = $DB->get_records("qtype_questionpy"); + $records = $DB->get_records('qtype_questionpy'); $this->assertCount(1, $records); $record = current($records); diff --git a/tests/question_test.php b/tests/question_test.php index 0acfff31..8e90eb76 100644 --- a/tests/question_test.php +++ b/tests/question_test.php @@ -74,7 +74,7 @@ protected function setUp(): void { * @throws coding_exception */ private function create_question(): qtype_questionpy_question { - question_engine::load_behaviour_class("questionpy"); + question_engine::load_behaviour_class('questionpy'); $question = new qtype_questionpy_question( hash('sha256', 'hash'), 'state', diff --git a/tests/question_ui_metadata_extractor_test.php b/tests/question_ui_metadata_extractor_test.php index f9b9904e..36f001bc 100644 --- a/tests/question_ui_metadata_extractor_test.php +++ b/tests/question_ui_metadata_extractor_test.php @@ -32,23 +32,23 @@ final class question_ui_metadata_extractor_test extends \advanced_testcase { * @covers \qtype_questionpy\question_metadata */ public function test_should_extract_correct_metadata(): void { - $input = file_get_contents(__DIR__ . "/question_uis/metadata.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/metadata.xhtml'); $metadata = new question_ui_metadata_extractor($input); $this->assertEquals(new question_metadata([ - "my_number" => "42", - "my_select" => "1", - "my_radio" => "2", - "my_text" => "Lorem ipsum dolor sit amet.", + 'my_number' => '42', + 'my_select' => '1', + 'my_radio' => '2', + 'my_text' => 'Lorem ipsum dolor sit amet.', ], [ - "my_number" => PARAM_RAW, - "my_select" => PARAM_RAW, - "my_radio" => PARAM_RAW, - "my_text" => PARAM_RAW, - "my_button" => PARAM_RAW, - "only_lowercase_letters" => PARAM_RAW, - "between_5_and_10_chars" => PARAM_RAW, - ], ["my_number"]), $metadata->extract()); + 'my_number' => PARAM_RAW, + 'my_select' => PARAM_RAW, + 'my_radio' => PARAM_RAW, + 'my_text' => PARAM_RAW, + 'my_button' => PARAM_RAW, + 'only_lowercase_letters' => PARAM_RAW, + 'between_5_and_10_chars' => PARAM_RAW, + ], ['my_number']), $metadata->extract()); } } diff --git a/tests/question_ui_renderer_test.php b/tests/question_ui_renderer_test.php index 77e3cddc..7ba08c95 100644 --- a/tests/question_ui_renderer_test.php +++ b/tests/question_ui_renderer_test.php @@ -19,7 +19,7 @@ defined('MOODLE_INTERNAL') || die(); global $CFG; -require_once($CFG->dirroot . "/question/type/questionpy/question.php"); +require_once($CFG->dirroot . '/question/type/questionpy/question.php'); use coding_exception; use PHPUnit\Framework\MockObject\Stub; @@ -67,7 +67,7 @@ private function assert_html_string_equals_html_string(string $expectedhtml, str * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_hide_inline_feedback(): void { - $input = file_get_contents(__DIR__ . "/question_uis/feedbacks.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/feedbacks.xhtml'); $qa = $this->create_question_attempt_stub(); $opts = new \question_display_options(); @@ -90,7 +90,7 @@ public function test_should_hide_inline_feedback(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_show_inline_feedback(): void { - $input = file_get_contents(__DIR__ . "/question_uis/feedbacks.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/feedbacks.xhtml'); $qa = $this->create_question_attempt_stub(); $opts = new \question_display_options(); @@ -114,7 +114,7 @@ public function test_should_show_inline_feedback(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_mangle_names(): void { - $input = file_get_contents(__DIR__ . "/question_uis/ids_and_names.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/ids_and_names.xhtml'); $qa = $this->create_question_attempt_stub(); @@ -152,7 +152,7 @@ public function test_should_mangle_names(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_shuffle_the_same_way_in_same_attempt(): void { - $input = file_get_contents(__DIR__ . "/question_uis/shuffle.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/shuffle.xhtml'); $qa = $this->create_question_attempt_stub(); $firstresult = (new question_ui_renderer($input, [], new \question_display_options(), $qa))->render(); @@ -170,12 +170,12 @@ public function test_should_shuffle_the_same_way_in_same_attempt(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_resolve_placeholders(): void { - $input = file_get_contents(__DIR__ . "/question_uis/placeholder.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/placeholder.xhtml'); $qa = $this->create_question_attempt_stub(); $ui = new question_ui_renderer($input, [ - "param" => "Value of param one.", - "description" => "My simple description.", + 'param' => "Value of param one.", + 'description' => 'My simple description.', ], new \question_display_options(), $qa); $result = $ui->render(); @@ -199,7 +199,7 @@ public function test_should_resolve_placeholders(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_remove_placeholders_when_no_corresponding_value(): void { - $input = file_get_contents(__DIR__ . "/question_uis/placeholder.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/placeholder.xhtml'); $qa = $this->create_question_attempt_stub(); $ui = new question_ui_renderer($input, [], new \question_display_options(), $qa); @@ -224,7 +224,7 @@ public function test_should_remove_placeholders_when_no_corresponding_value(): v * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_soften_validations(): void { - $input = file_get_contents(__DIR__ . "/question_uis/validations.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/validations.xhtml'); $qa = $this->create_question_attempt_stub(); $ui = new question_ui_renderer($input, [], new \question_display_options(), $qa); @@ -252,7 +252,7 @@ public function test_should_soften_validations(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_defuse_buttons(): void { - $input = file_get_contents(__DIR__ . "/question_uis/buttons.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/buttons.xhtml'); $qa = $this->create_question_attempt_stub(); $ui = new question_ui_renderer($input, [], new \question_display_options(), $qa); @@ -278,7 +278,7 @@ public function test_should_defuse_buttons(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_remove_element_with_if_role_attribute(): void { - $input = file_get_contents(__DIR__ . "/question_uis/if-role.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/if-role.xhtml'); $qa = $this->create_question_attempt_stub(); $this->resetAfterTest(); @@ -303,7 +303,7 @@ public function test_should_remove_element_with_if_role_attribute(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_not_remove_element_with_if_role_attribute(): void { - $input = file_get_contents(__DIR__ . "/question_uis/if-role.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/if-role.xhtml'); $qa = $this->create_question_attempt_stub(); $this->resetAfterTest(); @@ -335,7 +335,7 @@ public function test_should_not_remove_element_with_if_role_attribute(): void { * @covers \qtype_questionpy\question_ui_renderer */ public function test_should_format_floats_in_en(): void { - $input = file_get_contents(__DIR__ . "/question_uis/format-floats.xhtml"); + $input = file_get_contents(__DIR__ . '/question_uis/format-floats.xhtml'); $qa = $this->create_question_attempt_stub(); $ui = new question_ui_renderer($input, [], new \question_display_options(), $qa); @@ -362,8 +362,8 @@ public function test_should_format_floats_in_en(): void { * @covers \qtype_questionpy\question_ui_renderer::replace_qpy_urls */ public function test_should_replace_qpy_urls(): void { - $input = file_get_contents(__DIR__ . "/question_uis/qpy-urls.xhtml"); - $qa = $this->create_question_attempt_stub("deadbeef"); + $input = file_get_contents(__DIR__ . '/question_uis/qpy-urls.xhtml'); + $qa = $this->create_question_attempt_stub('deadbeef'); $ui = new question_ui_renderer($input, [], new \question_display_options(), $qa); $result = $ui->render(); @@ -385,15 +385,15 @@ public function test_should_replace_qpy_urls(): void { * @return question_attempt&Stub */ private function create_question_attempt_stub(?string $packagehash = null): question_attempt { - $packagehash ??= hash("sha256", random_string(64)); - $question = new qtype_questionpy_question($packagehash, "{}", null, $this->createStub(api::class)); + $packagehash ??= hash('sha256', random_string(64)); + $question = new qtype_questionpy_question($packagehash, '{}', null, $this->createStub(api::class)); $qa = $this->createStub(question_attempt::class); - $qa->method("get_database_id") + $qa->method('get_database_id') ->willReturn(mt_rand()); - $qa->method("get_question") + $qa->method('get_question') ->willReturn($question); - $qa->method("get_qt_field_name") + $qa->method('get_qt_field_name') ->willReturnCallback(function ($name) { return "mangled:$name"; }); diff --git a/tests/static_file_service_test.php b/tests/static_file_service_test.php index 6c16fcaf..d26b1eb4 100644 --- a/tests/static_file_service_test.php +++ b/tests/static_file_service_test.php @@ -19,8 +19,8 @@ defined('MOODLE_INTERNAL') || die(); global $CFG; -require_once($CFG->dirroot . "/question/engine/tests/helpers.php"); -require_once(__DIR__ . "/data_provider.php"); +require_once($CFG->dirroot . '/question/engine/tests/helpers.php'); +require_once(__DIR__ . '/data_provider.php'); use coding_exception; use core\di; @@ -72,13 +72,13 @@ protected function setUp(): void { $handlerstack = HandlerStack::create($this->mockhandler); $handlerstack->push(Middleware::history($this->requesthistory)); $api = new api(new qpy_http_client([ - "handler" => $handlerstack, + 'handler' => $handlerstack, ])); di::set(api::class, $api); $packagefileservice = $this->createStub(package_file_service::class); $packagefileservice - ->method("get_file_by_package_hash") + ->method('get_file_by_package_hash') ->willReturn(null); $this->staticfileservice = new static_file_service($api, $packagefileservice); @@ -95,23 +95,23 @@ protected function setUp(): void { public function test_should_download_public_static_file(): void { $hash = random_string(64); $this->mockhandler->append(new Response(200, [ - "Content-Type" => "text/markdown", - ], "Static file content")); + 'Content-Type' => 'text/markdown', + ], 'Static file content')); [$path, $mimetype] = $this->staticfileservice->download_public_static_file( $hash, - "local", - "example", - "/path/to/file.txt" + 'local', + 'example', + '/path/to/file.txt' ); - $this->assertStringEqualsFile($path, "Static file content"); - $this->assertEquals("text/markdown", $mimetype); + $this->assertStringEqualsFile($path, 'Static file content'); + $this->assertEquals('text/markdown', $mimetype); $this->assertCount(1, $this->requesthistory); /** @var Request $req */ - $req = $this->requesthistory[0]["request"]; - $this->assertEquals("POST", $req->getMethod()); + $req = $this->requesthistory[0]['request']; + $this->assertEquals('POST', $req->getMethod()); $this->assertStringEndsWith("/packages/$hash/file/local/example/static/path/to/file.txt", $req->getUri()); $this->assertEquals(0, $req->getBody()->getSize()); } @@ -125,17 +125,17 @@ public function test_should_download_public_static_file(): void { * @throws invalid_dataroot_permissions */ public function test_should_fall_back_and_warn_when_no_content_type(): void { - $this->mockhandler->append(new Response(200, [], "Static file content")); + $this->mockhandler->append(new Response(200, [], 'Static file content')); [, $mimetype] = $this->staticfileservice->download_public_static_file( random_string(64), - "local", - "example", - "/path/to/file.txt" + 'local', + 'example', + '/path/to/file.txt' ); - $this->assertEquals("application/octet-stream", $mimetype); - $this->assertDebuggingCalled("Server did not send Content-Type header, falling back to application/octet-stream"); + $this->assertEquals('application/octet-stream', $mimetype); + $this->assertDebuggingCalled('Server did not send Content-Type header, falling back to application/octet-stream'); } /** @@ -150,9 +150,9 @@ public function test_should_return_null_when_file_doesnt_exist(): void { $result = $this->staticfileservice->download_public_static_file( random_string(64), - "local", - "example", - "/path/to/file.txt" + 'local', + 'example', + '/path/to/file.txt' ); $this->assertNull($result); diff --git a/version.php b/version.php index 39620b73..764c9839 100644 --- a/version.php +++ b/version.php @@ -31,5 +31,5 @@ $plugin->release = '0.1'; $plugin->dependencies = [ - "qbehaviour_questionpy" => 2024101700, + 'qbehaviour_questionpy' => 2024101700, ];