summaryrefslogtreecommitdiff
path: root/src/App.php
blob: 107113a0e20049528b771ae67e0cb73598f25123 (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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?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 = $_ENV['app']['contentFolderPath'];

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

    try {
      $config = $this->buildConfig($contentRoot . $path);

      // check api key
      $apiKey = $_GET['key'] ?? $_POST['key'] ?? null;
      if (empty($apiKey)) {
	$response->setStatusCode(Response::HTTP_BAD_REQUEST);
	throw new \Exception('API key missing');
      }
      if (! in_array($apiKey, $config['api']['keys'])) {
	$response->setStatusCode(Response::HTTP_UNAUTHORIZED);
	throw new \Exception('API key does not match');
      }

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

	  $fields = $this->buildFields($formPath, $_GET['page'] ?? null);

	  // flatten paged form
	  if ($this->isPagedFieldSet($fields) && isset($_GET['flat'])) {
	    $fields = array_merge(...array_values($fields));
	  }

	  $content['data'] = $fields;
	}

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

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

	  $fields = $this->buildFields($formPath, $_GET['page'] ?? null);

	  $content = $this->validateRequest($fields);
	}

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

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

	  $content = $this->validateRequest($fields);

	  // if there were no validation errors then add entry
	  if (empty($content['error'])) {
	    $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 . '/' . $_ENV['form']['entriesFolderName'] . '/' . $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->headers->set('Access-Control-Allow-Origin', implode(',', $config['api']['cors']['origins']));
    $response->setContent(json_encode($content));
    $response->send();
  }

  /**
   * @param array $fields
   */
  public function validateRequest($fields) {
    $content = [];
    $hasInvalidFields = false;

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

    if ($this->isPagedFieldSet($fields)) {
      // remove surplus field values from response
      $fields = array_map(function ($page) {
	return array_map(function ($field) {
	  return array_intersect_key($field, array_flip([
	    'is_valid',
	  ]));
	}, $page);
      }, $fields);

      $flattened = array_merge(...array_values($fields));
      $hasInvalidFields = in_array(false, array_column($flattened, 'is_valid'));
    } else {
      // remove surplus field values from response
      $fields = array_map(function ($field) {
	return array_intersect_key($field, array_flip([
	  'is_valid',
	]));
      }, $fields);

      $hasInvalidFields = in_array(false, array_column($fields, 'is_valid'));
    }

    $content['data'] = $fields;

    if ($hasInvalidFields) {
      $content['error'] = 'Invalid fields';
    }

    return $content;
  }

  /**
   * @param string $formPath
   * @param mixed $page
   */
  public function buildFields($formPath, $page = null)
  {
    $parsed = Toml::parseFile($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);
      }

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

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

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

    return $fields;
  }

  /**
   * @param string $formPath
   * @param string $key
   * @param string $field
   */
  public function buildSingleField($formPath, $key, $field)
  {
    if (! empty($field['file'])) {
      $field = array_replace_recursive($field, Toml::parseFile($formPath . '/fields/' . $field['file']));
    }

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

    return $field;
  }

  /**
   * @param array $fields
   */
  public function validateFields($fields)
  {
    if ($this->isPagedFieldSet($fields)) {
      foreach ($fields as $pageKey => &$pageFields) {
	foreach ($pageFields as $key => &$field) {
	  $field = $this->validateSingleField($field);
	}
      }
    } else {
      foreach ($fields as $key => &$field) {
	$field = $this->validateSingleField($field);
      }
    }

    return $fields;
  }

  /**
   * @param array $field
   */
  public function validateSingleField($field)
  {
    $field['is_valid'] = true;

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

    return $field;
  }

  /**
   * @param string $formPath
   */
  public function buildConfig($formPath)
  {
    $config = [];
    $currentDirectory = $formPath;
    while (true) {
      $configFile = $currentDirectory . '/config/config.toml';
      if (file_exists($configFile)) {
	$parsedConfig = Toml::parseFile($configFile);

	$apiKeys = array_merge($parsedConfig['api']['keys'] ?? [], $config['api']['keys'] ?? []);
	$config = array_replace_recursive($parsedConfig, $config);
	$config['api']['keys'] = $apiKeys;
      }

      if (str_ends_with($currentDirectory, '/' . basename($_ENV['app']['contentFolderPath'])) || $currentDirectory == '/') {
	break;
      }

      $currentDirectory = dirname($currentDirectory);
    }

    return $config;
  }

  /**
   * @param array $fields
   */
  public function isPagedFieldSet($fields)
  {
    $firstItem = reset($fields);

    return ! (isset($firstItem['name']) && ! is_array($firstItem['name']));
  }
}