summaryrefslogtreecommitdiff
path: root/src/Controllers/SubmissionController.php
blob: 8d7d9e67f5035bb834e424f3e07d15363f1d401b (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
<?php

namespace FlatFileForms\Controllers;

use FlatFileForms\Builder;
use FlatFileForms\Form;
use FlatFileForms\HookManager;
use FlatFileForms\Validator;
use Symfony\Component\Yaml\Yaml;

class SubmissionController
{
  public function submit(Builder $builder, Validator $validator, string $formPath): array
  {
    /**@var HookManager $hooks*/
    global $hooks;

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

    $fields = $builder->buildFields();

    // run through validation
    $result = $validator->validateRequest($fields);

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

    // if there were no validation errors then add entry
    if (empty($result['error'])) {
      $date = new \Datetime();
      $entry = [
        'date' => $date->format('c'),
        'fields' => $_POST,
      ];

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

      $entryDirectory = $formPath . '/entries/' . $date->format('Y/m/d');
      @mkdir($entryDirectory, 0774, true);
      $entryFilename = $date->format('Ymd_Hi_') . hash('adler32', serialize($entry)) . '.yaml';
      file_put_contents(
        $entryDirectory . '/' . $entryFilename,
        Yaml::dump($entry, 4)
      );
    }
    else {
      $content['error'] = $result['error'];
    }

    return $content;
  }
}