summaryrefslogtreecommitdiff
path: root/src/Builder.php
blob: 1172fc815a9fc1838e8043f2351af5823b706a3b (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
81
82
83
84
85
86
87
88
89
<?php

namespace FlatFileForms;

use Symfony\Component\Yaml\Yaml;

class Builder
{
  public function __construct(
    private string $formPath
  )
  {}

  public function buildFields(mixed $page = null)
  {
    /**@var HookManager $hooks*/
    global $hooks;

    /**@var Form $form*/
    global $form;

    $parsed = Yaml::parseFile($this->formPath . '/fields/_fields.yaml');
    $fields = [];

    // if a page is requested
    if ($page) {
      if (! isset($parsed['pages'])) {
        throw new \Exception('Form has no pages');
      }

      if (! isset($parsed['pages'][$page])) {
        throw new \Exception('Form has no page ' . $page);
      }

      $fields = $this->buildSinglePageFields($parsed['pages'][$page]);
    }

    // else get all fields
    else {
      // if form is paged
      if (isset($parsed['pages'])) {
        $pages = $parsed['pages'];
        foreach ($pages as $pageKey => $pageFields) {
          $fields[$pageKey] = $this->buildSinglePageFields($pageFields);
        }
      }

      // if form is not paged
      else {
        foreach ($parsed as $key => $field) {
          $fields[$key] = $this->buildSingleField($key, $field);
        }
      }
    }

    $fields = $hooks->applyFilter("builder:{$form->name}:fields", $fields);
    $fields = $hooks->applyFilter('builder:fields', $fields);

    return $fields;
  }

  private function buildSinglePageFields(array $pageFields): array
  {
    $fields = [];

    if (! empty($pageFields['file'])) {
      $pageFields = array_replace_recursive($pageFields, Yaml::parseFile($this->formPath . '/fields/' . $pageFields['file']));
    }

    foreach ($pageFields['fields'] as $key => $field) {
      $fields[$key] = $this->buildSingleField($key, $field);
    }

    return $fields;
  }

  private function buildSingleField(string $key, array $field): array
  {
    if (! empty($field['file'])) {
      $field = array_replace_recursive($field, Yaml::parseFile($this->formPath . '/fields/' . $field['file']));
    }

    if (empty($field['name'])) {
      $field['name'] = $key;
    }

    return $field;
  }
}