opnform/app/Service/Forms/FormLogicPropertyResolver.php

70 lines
2.3 KiB
PHP
Raw Permalink Normal View History

2022-09-20 19:59:52 +00:00
<?php
namespace App\Service\Forms;
class FormLogicPropertyResolver
{
private $property = [];
2024-02-23 10:54:12 +00:00
2022-09-20 19:59:52 +00:00
private $formData = [];
2024-02-23 10:54:12 +00:00
2022-09-20 19:59:52 +00:00
private $logic = false;
public function __construct(private array $prop, private array $values)
{
$this->property = $prop;
$this->formData = $values;
$this->logic = isset($this->property['logic']) ? $this->property['logic'] : false;
}
public static function isRequired(array $property, array $values): bool
{
return (new self($property, $values))->shouldBeRequired();
}
public static function isHidden(array $property, array $values): bool
{
return (new self($property, $values))->shouldBeHidden();
}
2022-09-20 19:59:52 +00:00
public function shouldBeRequired(): bool
{
2024-02-23 10:54:12 +00:00
if (! isset($this->property['required'])) {
2022-09-20 19:59:52 +00:00
return false;
}
2024-02-23 10:54:12 +00:00
if (! $this->logic) {
2022-09-20 19:59:52 +00:00
return $this->property['required'];
}
$conditionsMet = FormLogicConditionChecker::conditionsMet($this->logic['conditions'], $this->formData);
if ($conditionsMet && $this->property['required'] && count($this->logic['actions']) > 0 && (in_array('make-it-optional', $this->logic['actions']) || in_array('hide-block', $this->logic['actions']))) {
2022-09-20 19:59:52 +00:00
return false;
2024-02-23 10:54:12 +00:00
} elseif ($conditionsMet && ! $this->property['required'] && count($this->logic['actions']) > 0 && in_array('require-answer', $this->logic['actions'])) {
2022-09-20 19:59:52 +00:00
return true;
} else {
return $this->property['required'];
}
}
public function shouldBeHidden(): bool
{
if (! isset($this->property['hidden'])) {
return false;
}
2024-02-23 10:54:12 +00:00
if (! $this->logic) {
return $this->property['hidden'];
}
$conditionsMet = FormLogicConditionChecker::conditionsMet($this->logic['conditions'], $this->formData);
if ($conditionsMet && $this->property['hidden'] && count($this->logic['actions']) > 0 && in_array('show-block', $this->logic['actions'])) {
return false;
2024-02-23 10:54:12 +00:00
} elseif ($conditionsMet && ! $this->property['hidden'] && count($this->logic['actions']) > 0 && in_array('hide-block', $this->logic['actions'])) {
return true;
} else {
return $this->property['hidden'];
}
}
2022-09-20 19:59:52 +00:00
}