Save.php 9.19 KB
Newer Older
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
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 1/30/16
 * Time: 7:59 PM
 */

namespace qfq;

require_once(__DIR__ . '/../qfq/store/Store.php');
require_once(__DIR__ . '/../qfq/Constants.php');
require_once(__DIR__ . '/../qfq/Evaluate.php');
//require_once(__DIR__ . '/../qfq/exceptions/UserException.php');
//require_once(__DIR__ . '/../qfq/exceptions/CodeException.php');
//require_once(__DIR__ . '/../qfq/exceptions/DbException.php');
//require_once(__DIR__ . '/../qfq/Evaluate.php');


class Save {

    private $formSpec = array();  // copy of the loaded form
    private $feSpecAction = array(); // copy of all formElement.class='action' of the loaded form
    private $feSpecNative = array(); // copy of all formElement.class='native' of the loaded form
    /**
     * @var null|Store
     */
    private $store = null;
    private $db = null;

    private $evaluate = null;

    /**
     * @param array $formSpec
     * @param array $feSpecAction
     * @param array $feSpecNative
     */
    public function __construct(array $formSpec, array $feSpecAction, array $feSpecNative) {
        $this->formSpec = $formSpec;
        $this->feSpecAction = $feSpecAction;
        $this->feSpecNative = $feSpecNative;
        $this->store = Store::getInstance();
        $this->db = new Database();
        $this->evaluate = new Evaluate($this->store, $this->db);
    }

    /**
48
49
     * Starts save process. On succcess, returns forwardmode/page.
     *
50
51
52
53
54
55
56
57
58
59
60
61
62
63
     * @throws CodeException
     * @throws DbException
     * @throws UserException
     */
    public function process() {

        if ($this->formSpec['multiMode'] !== 'none') {

            $parentRecords = $this->db->sql($this->formSpec['multiSql']);
            foreach ($parentRecords as $row) {
                $this->store->setVarArray($row, STORE_PARENT_RECORD, true);
                $this->elements($row['_id']);
            }
        } else {
64
            $this->elements($this->store->getVar(SIP_RECORD_ID, STORE_SIP . STORE_ZERO));
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        }
    }

    /**
     * @param $recordId
     * @return string
     * @throws CodeException
     * @throws DbException
     * @throws UserException
     */
    public function elements($recordId) {
        $html = '';
        $newValues = array();

        $tableColumns = array_keys($this->store->getStore(STORE_TABLE_COLUMN_TYPES));
        $clientValues = $this->store->getStore(STORE_CLIENT);
81

82
        // Retrieve SIP vars, e.g. for HIDDEN elements.
83
84
85
86
        $sipValues = $this->store->getStore(STORE_SIP);

        // Iterate over all table.columns. Built an assoc array $newValues.
        foreach ($tableColumns AS $column) {
87
            // Never save a predefined 'id': autoincrement values will be given by database..
88
89
90
91
92
93
94
95
            if ($column === 'id')
                continue;

            // Get related formElement.
            $formElement = $this->getFormElementByName($column);
            if ($formElement === false)
                continue;

96
            // Preparation for Log, Debug
97
98
99
100
101
102
103
            $this->store->setVar(SYSTEM_FORM_ELEMENT, $formElement['name'] . ' / ' . $formElement['id'], STORE_SYSTEM);

            if ($formElement['type'] == 'hidden') {
                // Hidden elements will be transferred by SIP
                if (!isset($sipValues[$column])) {
                    throw new CodeException("Missing the hidden field '$column' in SIP.", ERROR_MISSING_HIDDEN_FIELD_IN_SIP);
                }
104

105
106
107
108
                $newValues[$column] = $sipValues[$column];
                continue;
            }

109
            // construct the field name used in the form
110
111
112
            $clientFieldName = HelperFormElement::buildFormElementId($column, $recordId);

            if (isset($clientValues[$clientFieldName])) {
113
114
115
116
117
118
119
120
121
122
123

                // SELECT with multiple values, or Multi CHECKBOX are delivered as array: implode them
                if (is_array($clientValues[$clientFieldName])) {
                    // E.g. Checkboxes needs a 'HIDDEN' HTML input to detect 'unset' of values. These 'HIDDEN' element
                    //  needs to be removed, if there is at least one checkbox is checked (=submitted)
                    if (count($clientValues[$clientFieldName]) > 1)
                        array_shift($clientValues[$clientFieldName]);

                    $clientValues[$clientFieldName] = implode(',', $clientValues[$clientFieldName]);
                }

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
                $newValues[$column] = $this->validateValue($formElement, $clientValues[$clientFieldName]);
            }

        }

        return ($recordId == 0) ? $this->insertRecord($this->formSpec['tableName'], $newValues) : $this->updateRecord($this->formSpec['tableName'], $newValues, $recordId);
    }

    /**
     * Get the complete FormElement for $name
     *
     * @param $name
     * @return bool|array if found the FormElement, else false.
     */
    private function getFormElementByName($name) {
        foreach ($this->feSpecNative as $formElement) {
            if ($formElement['name'] === $name)
                return $formElement;
        }
        return false;
    }

    /**
     * Check $value against given checkType/pattern. Throws an UserException if check fails.
     *
     * @param $formElement
     * @param $value
     * @return string
     * @throws CodeException
     * @throws UserException
     */
    public function validateValue($formElement, $value) {
        $pattern = '';
        $minMax = array();

159
160
        $this->store->setVar(SYSTEM_FORM_ELEMENT, $formElement['name'], STORE_SYSTEM);

161
162
163
164
165
        switch ($formElement['checkType']) {
            case 'min|max':
                $valueCompare = $value;

                $minMax = explode('|', $formElement['checkPattern']);
166
167
168
169
                if ($minMax[0] === '' || $minMax[1] === '') {
                    $this->store->setVar(SYSTEM_FORM_ELEMENT_MESSAGE, 'Missing definition of value for min or max.', STORE_SYSTEM);
                    throw new UserException('Missing definition of value for min or max.', ERROR_MISSING_MIN_MAX);
                }
170
171
172
173
174
175
176
177
178
179
180
181
                $errorText = "Value '$value' is smaller than min '$minMax[0]' or bigger than max '$minMax[1]'.";

                // Date/Time: convert in object to make a comparison.
                if (preg_match('date|time', $formElement['type']) === 1) {
                    $valueCompare = date_create($value);
                    $minMax[0] = date_create($minMax[0]);
                    $minMax[1] = date_create($minMax[1]);
                }

                if ($minMax[0] <= $valueCompare && $valueCompare <= $minMax[1])
                    return $value;

182
                $this->store->setVar(SYSTEM_FORM_ELEMENT_MESSAGE, $errorText, STORE_SYSTEM);
183
184
185
186
187
188
189
190
191
                throw new UserException($errorText, ERROR_MIN_MAX_VIOLATION);

                break;
            case 'pattern':
                $pattern = $formElement['checkPattern'];
                break;

            case 'number':
            case 'email':
192
193
            $arr = OnArray::inputCheckPatternArray();
            $htmlPatternAttribute = $arr[$formElement['checkType']];
194
195
196
197
198
199
200
201
202
203
204
205
206
207
                // remove 'pattern="' and closing ".
                $pattern = substr($htmlPatternAttribute, 9, strlen($htmlPatternAttribute) - 9 - 1);
                break;

            case '': // no checktype specified.
                return $value;

            default:
                throw new CodeException("Unknown checkType: " . $formElement['checkType'], ERROR_UNKNOWN_CHECKTYPE);
        }

        if (preg_match($pattern, $value) === 1)
            return $value;

208
209
210
        $errorText = "Value $value violates checkrule " . $formElement['checkType'] . " with pattern '$pattern'.";
        $this->store->setVar(SYSTEM_FORM_ELEMENT_MESSAGE, $errorText, STORE_SYSTEM);
        throw new UserException($errorText, ERROR_PATTERN_VIOLATION);
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
    }

    /**
     * Insert new record in table $this->formSpec['tableName'].
     *
     * @param array $values
     * @return string
     * @throws DbException
     */
    public function insertRecord($tableName, array $values) {

        if (count($values) === 0)
            return 0;

        $paramList = str_repeat('?, ', count($values));
        $paramList = substr($paramList, 0, strlen($paramList) - 2);
        $columnList = '`' . implode('`, `', array_keys($values)) . '`';

        $sql = 'INSERT INTO ' . $tableName . ' ( ' . $columnList . ' ) VALUES ( ' . $paramList . ' )';

        $this->db->sql($sql, ROW_REGULAR, array_values($values));

        return $this->db->getLastInsertId();
    }

    /**
     * @param array $values
     * @param $recordId
     * @return string
     * @throws DbException
     */
    public function updateRecord($tableName, array $values, $recordId) {

        if (count($values) === 0)
            return;

        if ($recordId === 0)
            throw new CodeException('RecordId=0 - this is not possible for update.', ERROR_RECORDID_0_FORBIDDEN);

        $paramList = str_repeat('?, ', count($values));
        $paramList = substr($paramList, 0, strlen($paramList) - 2);

        $sql = 'UPDATE `' . $tableName . '` SET ';

        foreach ($values as $column => $value) {
256

257
258
259
260
261
262
263
264
265
266
            $sql .= '`' . $column . '` = ?, ';
        }

        $sql = substr($sql, 0, strlen($sql) - 2) . ' WHERE id = ?';
        $values[] = $recordId;

        $this->db->sql($sql, ROW_REGULAR, array_values($values));
    }

}