Files
myep-team/src/Config/QuestionnaireCatalog.php
T

364 lines
14 KiB
PHP

<?php
namespace App\Config;
use App\Enum\ChoiceWidget;
use App\Enum\ConditionOperator;
use App\Enum\QuestionType;
use App\Model\Questionnaire\Condition;
use App\Model\Questionnaire\Definition;
use App\Model\Questionnaire\Option;
use App\Model\Questionnaire\Question;
use App\Model\Questionnaire\Section;
use Symfony\Component\Yaml\Yaml;
/**
* Reads questionnaire definitions from config/questionnaires/.
*
* `<key>.yaml` is the current version of a questionnaire; `<key>.v<n>.yaml` keeps an older one that
* responses were submitted under, so they can still be rendered with the labels they were given.
*
* Files are parsed lazily and memoised, like EmailTextCatalog. A definition is checked strictly
* while it is built - unknown fields, unknown types, duplicate keys and show_if conditions that
* point at a later question or a non-existent option all throw - because a typo in the YAML should
* fail in QuestionnaireCatalogTest, not in front of a teamer.
*/
class QuestionnaireCatalog
{
/**
* The questionnaire a teamer fills in after a bus escort; see DispositionVoter::QUESTIONNAIRE.
*/
public const string TEAMER_ESCORT = 'teamer_escort';
private const array ROOT_FIELDS = ['key', 'version', 'title', 'description', 'sections'];
private const array SECTION_FIELDS = ['key', 'title', 'questions'];
private const array QUESTION_FIELDS = ['key', 'label', 'type', 'required', 'help', 'widget', 'options', 'show_if'];
private const array OPTION_FIELDS = ['key', 'label'];
// A question key becomes a form field name and a JSON key in stored answers.
private const string KEY_PATTERN = '/^[a-z][a-z0-9_]*$/';
private const int RATING_MIN = 1;
private const int RATING_MAX = 5;
/**
* @var array<string, Definition> keyed by file path
*/
private array $definitions = [];
public function __construct(
private readonly string $questionnaireDir,
) {
}
/**
* The services.yaml parameter questionnaire_go_live as a date: the teamer questionnaire is
* offered for assignments ending on or after it, and to nobody while it is null.
*/
public static function parseGoLive(?string $goLive): ?\DateTimeImmutable
{
if (null === $goLive) {
return null;
}
return \DateTimeImmutable::createFromFormat('!Y-m-d', $goLive)
?: throw new \InvalidArgumentException(sprintf('questionnaire_go_live "%s" is not a Y-m-d date', $goLive));
}
/**
* @param int|null $version null for the current version
*/
public function get(string $key, ?int $version = null): Definition
{
$current = $this->load($this->questionnaireDir.'/'.$key.'.yaml');
if (null === $version || $version === $current->version) {
return $current;
}
return $this->load(sprintf('%s/%s.v%d.yaml', $this->questionnaireDir, $key, $version));
}
/**
* Every definition in the directory, archived versions included.
*
* @return list<Definition>
*/
public function all(): array
{
$files = glob($this->questionnaireDir.'/*.yaml') ?: [];
sort($files);
return array_map($this->load(...), $files);
}
private function load(string $file): Definition
{
if (!is_file($file)) {
throw new \InvalidArgumentException(sprintf('Questionnaire definition "%s" does not exist', $file));
}
return $this->definitions[$file] ??= $this->build(Yaml::parseFile($file), basename($file));
}
private function build(mixed $data, string $file): Definition
{
$this->assertFields($data, self::ROOT_FIELDS, ['key', 'version', 'title', 'sections'], $file);
if (1 !== preg_match('/^(?<key>[a-z0-9_]+)(\.v(?<version>\d+))?\.yaml$/', $file, $name)) {
throw $this->error($file, 'file name must be <key>.yaml or <key>.v<version>.yaml');
}
if ($data['key'] !== $name['key']) {
throw $this->error($file, sprintf('key "%s" does not match the file name', $data['key']));
}
if (!is_int($data['version']) || $data['version'] < 1) {
throw $this->error($file, 'version must be a positive integer');
}
if (isset($name['version']) && (int) $name['version'] !== $data['version']) {
throw $this->error($file, sprintf('version %d does not match the file name', $data['version']));
}
if (!is_array($data['sections']) || [] === $data['sections'] || !array_is_list($data['sections'])) {
throw $this->error($file, 'sections must be a non-empty list');
}
$sections = [];
$sectionKeys = [];
/** @var array<string, Question> $questions every question parsed so far, for show_if */
$questions = [];
foreach ($data['sections'] as $index => $sectionData) {
$context = sprintf('%s: section #%d', $file, $index + 1);
$this->assertFields($sectionData, self::SECTION_FIELDS, ['key', 'questions'], $context);
$key = $this->key($sectionData['key'], $context);
if (in_array($key, $sectionKeys, true)) {
throw $this->error($context, sprintf('duplicate section key "%s"', $key));
}
$sectionKeys[] = $key;
$context = sprintf('%s: section "%s"', $file, $key);
if (!is_array($sectionData['questions']) || [] === $sectionData['questions'] || !array_is_list($sectionData['questions'])) {
throw $this->error($context, 'questions must be a non-empty list');
}
$sectionQuestions = [];
foreach ($sectionData['questions'] as $questionData) {
$question = $this->buildQuestion($questionData, $questions, $context);
$questions[$question->key] = $question;
$sectionQuestions[] = $question;
}
$sections[] = new Section($key, $this->optionalString($sectionData['title'] ?? null, 'title', $context), $sectionQuestions);
}
return new Definition(
$data['key'],
$data['version'],
$this->string($data['title'], 'title', $file),
$this->optionalString($data['description'] ?? null, 'description', $file),
$sections,
);
}
/**
* @param array<string, Question> $earlier
*/
private function buildQuestion(mixed $data, array $earlier, string $context): Question
{
$this->assertFields($data, self::QUESTION_FIELDS, ['key', 'label', 'type'], $context.': question');
$key = $this->key($data['key'], $context.': question');
$context = sprintf('%s: question "%s"', $context, $key);
if (isset($earlier[$key])) {
throw $this->error($context, 'duplicate question key');
}
$type = QuestionType::tryFrom((string) $data['type'])
?? throw $this->error($context, sprintf('unknown type "%s"', $data['type']));
$required = $data['required'] ?? false;
if (!is_bool($required)) {
throw $this->error($context, 'required must be true or false');
}
$widget = null;
if (array_key_exists('widget', $data)) {
if (QuestionType::CHOICE !== $type) {
throw $this->error($context, 'widget is only allowed on a choice question');
}
$widget = ChoiceWidget::tryFrom((string) $data['widget'])
?? throw $this->error($context, sprintf('unknown widget "%s"', $data['widget']));
} elseif (QuestionType::CHOICE === $type) {
$widget = ChoiceWidget::RADIO;
}
$options = [];
if ($type->hasOptions()) {
$options = $this->buildOptions($data['options'] ?? null, $context);
} elseif (array_key_exists('options', $data)) {
throw $this->error($context, sprintf('options are not allowed on a %s question', $type->value));
}
$showIf = array_key_exists('show_if', $data)
? $this->buildCondition($data['show_if'], $earlier, $context)
: null;
return new Question(
$key,
$this->string($data['label'], 'label', $context),
$type,
$required,
$this->optionalString($data['help'] ?? null, 'help', $context),
$widget,
$options,
$showIf,
);
}
/**
* @return list<Option>
*/
private function buildOptions(mixed $data, string $context): array
{
if (!is_array($data) || [] === $data || !array_is_list($data)) {
throw $this->error($context, 'options must be a non-empty list');
}
$options = [];
$keys = [];
foreach ($data as $optionData) {
$this->assertFields($optionData, self::OPTION_FIELDS, self::OPTION_FIELDS, $context.': option');
// An option key is stored as the answer; YAML would turn an unquoted 1 into an int.
$key = $this->key((string) $optionData['key'], $context.': option');
if (in_array($key, $keys, true)) {
throw $this->error($context, sprintf('duplicate option key "%s"', $key));
}
$keys[] = $key;
$options[] = new Option($key, $this->string($optionData['label'], 'option label', $context));
}
return $options;
}
/**
* @param array<string, Question> $earlier
*/
private function buildCondition(mixed $data, array $earlier, string $context): Condition
{
$context .= ': show_if';
$operators = array_map(static fn (ConditionOperator $operator): string => $operator->value, ConditionOperator::cases());
$this->assertFields($data, ['question', ...$operators], ['question'], $context);
$given = array_values(array_intersect($operators, array_keys($data)));
if (1 !== count($given)) {
throw $this->error($context, sprintf('needs exactly one of %s', implode(', ', $operators)));
}
$operator = ConditionOperator::from($given[0]);
$value = $data[$given[0]];
// Only an earlier question can be answered by the time this one is reached, and it rules
// out cycles without having to look for them.
$controlling = $earlier[$data['question']]
?? throw $this->error($context, sprintf('question "%s" is not an earlier question', $data['question']));
match ($operator) {
ConditionOperator::EQUALS, ConditionOperator::IN => $this->assertOptionValue($controlling, $operator, $value, $context),
ConditionOperator::LTE => $this->assertRatingValue($controlling, $value, $context),
};
return new Condition($controlling->key, $operator, $value);
}
private function assertOptionValue(Question $controlling, ConditionOperator $operator, mixed $value, string $context): void
{
if (QuestionType::CHOICE !== $controlling->type) {
throw $this->error($context, sprintf('%s needs a choice question, "%s" is %s', $operator->value, $controlling->key, $controlling->type->value));
}
$values = ConditionOperator::IN === $operator ? $value : [$value];
if (!is_array($values) || [] === $values || !array_is_list($values)) {
throw $this->error($context, 'in needs a non-empty list of option keys');
}
foreach ($values as $optionKey) {
if (!is_string($optionKey) || null === $controlling->getOption($optionKey)) {
throw $this->error($context, sprintf('"%s" is not an option of "%s"', is_string($optionKey) ? $optionKey : json_encode($optionKey), $controlling->key));
}
}
}
private function assertRatingValue(Question $controlling, mixed $value, string $context): void
{
if (QuestionType::RATING !== $controlling->type) {
throw $this->error($context, sprintf('lte needs a rating question, "%s" is %s', $controlling->key, $controlling->type->value));
}
if (!is_int($value) || $value < self::RATING_MIN || $value > self::RATING_MAX) {
throw $this->error($context, sprintf('lte needs a rating from %d to %d', self::RATING_MIN, self::RATING_MAX));
}
}
/**
* @param list<string> $allowed
* @param list<string> $required
*/
private function assertFields(mixed $data, array $allowed, array $required, string $context): void
{
if (!is_array($data) || array_is_list($data)) {
throw $this->error($context, 'must be a mapping');
}
if ([] !== $unknown = array_diff(array_keys($data), $allowed)) {
throw $this->error($context, sprintf('unknown field(s) %s', implode(', ', $unknown)));
}
if ([] !== $missing = array_diff($required, array_keys($data))) {
throw $this->error($context, sprintf('missing field(s) %s', implode(', ', $missing)));
}
}
private function key(mixed $value, string $context): string
{
if (!is_string($value) || 1 !== preg_match(self::KEY_PATTERN, $value)) {
throw $this->error($context, sprintf('key %s must be lower snake_case', json_encode($value)));
}
return $value;
}
private function string(mixed $value, string $field, string $context): string
{
if (!is_string($value) || '' === trim($value)) {
throw $this->error($context, sprintf('%s must be a non-empty string', $field));
}
return $value;
}
private function optionalString(mixed $value, string $field, string $context): ?string
{
return null === $value ? null : $this->string($value, $field, $context);
}
private function error(string $context, string $message): \UnexpectedValueException
{
return new \UnexpectedValueException(sprintf('%s: %s', $context, $message));
}
}