summaryrefslogtreecommitdiff
path: root/src/Builder.php
blob: 308fa82112bf6c9d4428820372f59bed16c0cf44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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;
  }
}