@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
/** Computes a form's total price as the sum of its elements' prices. */
|
||||
class RsvFormPriceCalculator {
|
||||
public function calculate(RsvFormDefinition $definition, RsvFormData $data): float {
|
||||
global $rsv_form_price_registry;
|
||||
|
||||
$total = 0.0;
|
||||
|
||||
foreach ($definition->getElements() as $element) {
|
||||
$calculator = $rsv_form_price_registry->get($element->getType());
|
||||
if ($calculator === null) {
|
||||
continue; // Unpriced element type contributes nothing.
|
||||
}
|
||||
|
||||
$total += (float) $calculator($element, $data->getValue($element->getName()));
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
class RsvFormPriceCalculatorRegistry {
|
||||
/** @var array<string, callable(RsvFormElementDefinition, mixed): float> */
|
||||
private array $calculators = [];
|
||||
|
||||
public function register(string $type, callable $calculator): void {
|
||||
$this->calculators[$type] = $calculator;
|
||||
}
|
||||
|
||||
public function get(string $type): ?callable {
|
||||
return $this->calculators[$type] ?? null;
|
||||
}
|
||||
|
||||
/** Builds the registry and lets other modules contribute calculators. */
|
||||
public static function boot(): self {
|
||||
$registry = new self();
|
||||
do_action('rsv-register-price-calculator', $registry);
|
||||
return $registry;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
/** Values derived from a submission (not entered by the visitor), exposed to templates. */
|
||||
final class RsvFormCalculatedValues {
|
||||
/** @return array<string, mixed> */
|
||||
public function for(RsvFormDefinition $definition, RsvFormData $data): array {
|
||||
return [
|
||||
'price' => (new RsvFormPriceCalculator())->calculate($definition, $data),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The names these values expose, so template validation accepts {{ price }}.
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function names(): array {
|
||||
return ['price'];
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ final class RsvFormDefinitionValidator {
|
||||
* @return list<string>
|
||||
*/
|
||||
private function symbols(array $elements): array {
|
||||
$names = [];
|
||||
$names = RsvFormCalculatedValues::names(); // calculated values are referencable too
|
||||
foreach ($elements as $el) {
|
||||
$name = is_array($el) ? ($el['name'] ?? '') : '';
|
||||
if (is_string($name) && $name !== '') {
|
||||
|
||||
Reference in New Issue
Block a user