summaryrefslogtreecommitdiff
path: root/src/Builder.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/Builder.php')
-rw-r--r--src/Builder.php80
1 files changed, 80 insertions, 0 deletions
diff --git a/src/Builder.php b/src/Builder.php
new file mode 100644
index 0000000..308fa82
--- /dev/null
+++ b/src/Builder.php
@@ -0,0 +1,80 @@
+<?php
+
+namespace FlatFileForms;
+
+use Yosymfony\Toml\Toml;
+
+class Builder
+{
+ public function __construct(
+ private string $formPath
+ )
+ {}
+
+ public function buildFields(mixed $page = null)
+ {
+ $parsed = Toml::parseFile($this->formPath . '/fields/_fields.toml');
+ $fields = [];
+
+ // if a page is requested
+ if ($page) {
+ if (! isset($parsed['page'])) {
+ throw new \Exception('Form has no pages');
+ }
+
+ if (! isset($parsed['page'][$page])) {
+ throw new \Exception('Form has no page ' . $page);
+ }
+
+ $fields = $this->buildSinglePageFields($parsed['page'][$page]);
+ }
+
+ // else get all fields
+ else {
+ // if form is paged
+ if (isset($parsed['page'])) {
+ $pages = $parsed['page'];
+ foreach ($pages as $pageKey => $pageFields) {
+ $fields[$pageKey] = $this->buildSinglePageFields($pageFields);
+ }
+ }
+
+ // if form is not paged
+ else {
+ foreach ($parsed['field'] as $key => $field) {
+ $fields[$key] = $this->buildSingleField($key, $field);
+ }
+ }
+ }
+
+ return $fields;
+ }
+
+ public function buildSinglePageFields(array $pageFields): array
+ {
+ $fields = [];
+
+ if (! empty($pageFields['file'])) {
+ $pageFields = array_replace_recursive($pageFields, Toml::parseFile($this->formPath . '/fields/' . $pageFields['file']));
+ }
+
+ foreach ($pageFields['field'] as $key => $field) {
+ $fields[$key] = $this->buildSingleField($key, $field);
+ }
+
+ return $fields;
+ }
+
+ public function buildSingleField(string $key, array $field): array
+ {
+ if (! empty($field['file'])) {
+ $field = array_replace_recursive($field, Toml::parseFile($this->formPath . '/fields/' . $field['file']));
+ }
+
+ if (empty($field['name'])) {
+ $field['name'] = $key;
+ }
+
+ return $field;
+ }
+}