summaryrefslogtreecommitdiff
path: root/src/App.php
blob: 20cec62da3f3e472e8be93fa59d93c7abca39827 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?php

namespace FlatFileForms;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Yosymfony\Toml\Toml;
use Yosymfony\Toml\TomlBuilder;

class App
{
  /**
   * App constructor.
   */
  public function __construct()
  {
    $request = Request::createFromGlobals();
    $response = new Response();

    $content = [
      'data' => '',
    ];
    $contentRoot = dirname(__DIR__) . '/content';

    $method = $request->getMethod();
    $path = $request->getPathInfo();

    try {
      // GET
      if ($method == 'GET')  {
	if (str_ends_with($path, '/fields')) {
	  $formPath = $contentRoot . str_replace('/fields', '', $path);

	  $content['data'] = $this->buildFields($formPath);
	}
	else {
	  $content['data'] = Toml::parseFile($contentRoot . $path . '.toml');
	}
      }

      // POST
      else if ($method == 'POST') {
	if (str_ends_with($path, '/submit')) {
	  $formPath = $contentRoot . str_replace('/submit', '', $path);

	  $fields = $this->buildFields($formPath);
	  $fields = $this->validateFields($fields);

	  // remove surplus fields from response
	  $fields = array_map(function ($field) {
	    return array_intersect_key($field, array_flip([
	      'is_valid',
	    ]));
	  }, $fields);

	  $content['data'] = $fields;

	  $hasInvalidFields = in_array(false, array_column($fields, 'is_valid'));
	  if ($hasInvalidFields) {
	    $content['error'] = 'Invalid fields';
	  } else {
	    $date = new \Datetime();
	    $entry = [
	      'fields' => $_POST,
	      'date' => $date->format('c'),
	    ];

	    $builder = new TomlBuilder();
	    $builder->addValue('date', $entry['date']);
	    $builder->addTable('fields');
	    foreach ($entry['fields'] as $entryKey => $entryValue) {
	      $builder->addValue($entryKey, $entryValue);
	    }

	    $entryDirectory = $formPath . '/entries/' . $date->format('Y/m/d');
	    @mkdir($entryDirectory, 0774, true);
	    $entryFilename = $date->format('Ymd_Hi_') . hash('adler32', serialize($entry)) . '.toml';
	    file_put_contents(
	      $entryDirectory . '/' . $entryFilename,
	      $builder->getTomlString()
	    );
	  }
	}
      }
    } catch (\Exception $exception) {
      $content['error'] = $exception->getMessage();
    }

    $response->headers->set('Content-Type', 'application/json');
    $response->setContent(json_encode($content));
    $response->send();
  }

  /**
   * @param string $formPath
   */
  public function buildFields($formPath)
  {
    $fields = Toml::parseFile($formPath . '/fields/_fields.toml')['field'] ?? [];
    foreach ($fields as $key => $field) {
      if (empty($field['name'])) {
	$field['name'] = $key;
      }

      if (! empty($field['file'])) {
	$field = array_merge($field, Toml::parseFile($formPath . '/fields/' . $field['file']));
      }

      $fields[$key] = $field;
    }

    return $fields;
  }

  /**
   * @param array $fields
   */
  public function validateFields($fields)
  {
    foreach ($fields as $key => &$field) {
      $field['is_valid'] = true;

      if (($field['required'] ?? false) && empty($_POST[$field['name']])) {
	$field['is_valid'] = false;
      }
    }

    return $fields;
  }
}