Skip to content

Commit

Permalink
fix(question_condition): better performance
Browse files Browse the repository at this point in the history
use static var to cache condition results

Signed-off-by: Thierry Bugier <tbugier@teclib.com>
  • Loading branch information
btry committed Nov 7, 2019
1 parent dc402d9 commit 8a54258
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
7 changes: 6 additions & 1 deletion ajax/showfields.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@

include ('../../../inc/includes.php');

$visibility = PluginFormcreatorFields::updateVisibility($_POST);
try {
$visibility = PluginFormcreatorFields::updateVisibility($_POST);
} catch (Exception $e) {
http_response_code(500);
exit();
}
echo json_encode($visibility);
exit();
27 changes: 16 additions & 11 deletions inc/fields.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,22 +112,27 @@ public static function getNames() {
*/
public static function isVisible($id, $fields) {
/**
* Keep track of questions being evaluated to detect infinite loops
* Keep track of questions results and computation status
* null = is beinc computed
* true or false = result of a previous evaluation
* not set = not evaluated yet and not being evaluated
*/
static $evalQuestion = [];
if (isset($evalQuestion[$id])) {
// TODO : how to deal a infinite loop while evaluating visibility of question ?
return true;
if (!isset($evalQuestion[$id])) {
$evalQuestion[$id] = null;
} else if ($evalQuestion[$id] !== null) {
return $evalQuestion[$id];
} else {
throw new Exception("Infinite loop in show conditions evaluation");
}
$evalQuestion[$id] = $id;

$question = new PluginFormcreatorQuestion();
$question->getFromDB($id);
$conditions = [];

// If the field is always shown
if ($question->getField('show_rule') == PluginFormcreatorQuestion::SHOW_RULE_ALWAYS) {
unset($evalQuestion[$id]);
$evalQuestion[$id] = true;
return true;
}

Expand All @@ -137,7 +142,7 @@ public static function isVisible($id, $fields) {
$questionConditions = $question_condition->getConditionsFromQuestion($questionId);
if (count($questionConditions) < 1) {
// No condition defined, then always show the question
unset($evalQuestion[$id]);
$evalQuestion[$id] = true;
return true;
}

Expand Down Expand Up @@ -277,15 +282,15 @@ public static function isVisible($id, $fields) {
$return = ($return xor $lowPrecedenceReturnPart);
}

unset($evalQuestion[$id]);

if ($question->fields['show_rule'] == PluginFormcreatorQuestion::SHOW_RULE_HIDDEN) {
// If the field is hidden by default, show it if condition is true
return $return;
$evalQuestion[$id] = $return;
} else {
// else show it if condition is false
return !$return;
$evalQuestion[$id] = !$return;
}

return $evalQuestion[$id];
}

/**
Expand Down

0 comments on commit 8a54258

Please sign in to comment.