summaryrefslogtreecommitdiff
path: root/src/App.php
blob: 5fc62fab1143f1722e0c54acaca6dce43d0cec22 (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
<?php

namespace FlatFileForms;

use FlatFileForms\Controllers\EntriesController;
use FlatFileForms\Controllers\FieldsController;
use FlatFileForms\Controllers\SubmissionController;
use FlatFileForms\Controllers\ValidationController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Yosymfony\Toml\Toml;
use Yosymfony\Toml\TomlBuilder;

class App
{
  public string $formPath;

  /**
   * App constructor.
   */
  public function __construct()
  {
    /**@var HookManager $hooks*/
    global $hooks;

    $hooks->doAction('init');

    $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)) {
        throw new HttpException('API key missing', Response::HTTP_BAD_REQUEST);
      }
      if (! in_array($apiKey, $config['api']['keys'])) {
        throw new HttpException('API key does not match', Response::HTTP_UNAUTHORIZED);
      }

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

          $builder = new Builder($formPath);

          $fieldsController = new FieldsController();

          $content = $fieldsController->getFields($builder);
        }

        else if (str_ends_with($path, '/entries')) {
          if (! isset($_GET['dateFrom'])) {
            throw new HttpException('dateFrom parameter missing', Response::HTTP_BAD_REQUEST);
          }

          $formPath = $contentRoot . str_replace('/entries', '', $path);

          $entriesController = new EntriesController();

          $content = $entriesController->getEntries($formPath);
        }

        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);

          $builder = new Builder($formPath);
          $validator = new Validator($formPath);

          $validationController = new ValidationController();

          $content = $validationController->validateRequest($builder, $validator);
        }

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

          $builder = new Builder($formPath);
          $validator = new Validator($formPath);

          $submissionController = new SubmissionController();

          $content = $submissionController->submit($builder, $validator, $formPath);

          if (! empty($content['error'])) {
            throw new HttpException($content['error'], Response::HTTP_UNPROCESSABLE_ENTITY);
          }
        }
      }
    } catch (\Exception $exception) {
      if ($exception instanceof HttpException) {
        $response->setStatusCode($exception->getCode());
      }

      $content['error'] = basename(get_class($exception)) . ': ' . $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();
  }

  public function buildConfig(string $requestPath): array
  {
    $config = [];
    $currentDirectory = $requestPath;
    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;
      }

      // include custom functions
      $functionsFile = $currentDirectory . '/config/functions.php';
      if (file_exists($functionsFile)) {
        include_once $functionsFile;
      }

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

      $currentDirectory = dirname($currentDirectory);
    }

    return $config;
  }
}