-
Notifications
You must be signed in to change notification settings - Fork 22
/
Editor.php
2611 lines (2237 loc) · 72.6 KB
/
Editor.php
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* DataTables PHP libraries.
*
* PHP libraries for DataTables and DataTables Editor.
*
* @author SpryMedia
*
* @version __VERSION__
*
* @copyright 2012 SpryMedia ( http://sprymedia.co.uk )
* @license http://editor.datatables.net/license DataTables Editor
*
* @see http://editor.datatables.net
*/
namespace DataTables;
use DataTables\Database\Query;
use DataTables\Editor\Field;
use DataTables\Editor\Join;
/**
* DataTables Editor base class for creating editable tables.
*
* Editor class instances are capable of servicing all of the requests that
* DataTables and Editor will make from the client-side - specifically:
*
* * Get data
* * Create new record
* * Edit existing record
* * Delete existing records
*
* The Editor instance is configured with information regarding the
* database table fields that you wish to make editable, and other information
* needed to read and write to the database (table name for example!).
*
* This documentation is very much focused on describing the API presented
* by these DataTables Editor classes. For a more general overview of how
* the Editor class is used, and how to install Editor on your server, please
* refer to the {@link https://editor.datatables.net/manual Editor manual}.
*
* @example
* A very basic example of using Editor to create a table with four fields.
* This is all that is needed on the server-side to create a editable
* table - the {@see Editor->process()} method determines what action DataTables /
* Editor is requesting from the server-side and will correctly action it.
*
* ```php
* (new Editor( $db, 'browsers' ))
* ->fields(
* (new Field( 'first_name' ))->validator( Validate::required() ),
* (new Field( 'last_name' ))->validator( Validate::required() ),
* new Field( 'country' ),
* new Field( 'details' )
* )
* ->process( $_POST )
* ->json();
* ```
*/
class Editor extends Ext
{
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Statics
*/
/** Request type - read */
const ACTION_READ = 'read';
/** Request type - create */
const ACTION_CREATE = 'create';
/** Request type - edit */
const ACTION_EDIT = 'edit';
/** Request type - delete */
const ACTION_DELETE = 'remove';
/** Request type - options search */
const ACTION_SEARCH = 'search';
/** Request type - upload */
const ACTION_UPLOAD = 'upload';
/**
* Determine the request type from an HTTP request.
*
* @param array $http Typically $_POST, but can be any array used to carry
* an Editor payload
* @param string $name The parameter name that the action should be read from.
*
* @return static::ACTION_* `Editor::ACTION_READ`, `Editor::ACTION_CREATE`,
* `Editor::ACTION_EDIT` or `Editor::ACTION_DELETE` indicating the request
* type.
*/
public static function action($http, $name = 'action')
{
if (!isset($http[$name])) {
return self::ACTION_READ;
}
switch ($http[$name]) {
case 'create':
return self::ACTION_CREATE;
case 'edit':
return self::ACTION_EDIT;
case 'remove':
return self::ACTION_DELETE;
case 'search':
return self::ACTION_SEARCH;
case 'upload':
return self::ACTION_UPLOAD;
default:
throw new \Exception('Unknown Editor action: ' . $http['action']);
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constructor
*/
/**
* Constructor.
*
* @param Database $db An instance of the DataTables Database class that we can
* use for the DB connection. Can be given here or with the 'db' method.
* @param string|array $table The table name in the database to read and write
* information from and to. Can be given here or with the 'table' method.
* @param string|array $pkey Primary key column name in the table given in
* the $table parameter. Can be given here or with the 'pkey' method.
*/
public function __construct($db = null, $table = null, $pkey = null)
{
// Set constructor parameters using the API - note that the get/set will
// ignore null values if they are used (i.e. not passed in)
$this->db($db);
$this->table($table);
$this->pkey($pkey);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public properties
*/
/** @var string */
public $version = '2.3.2';
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private properties
*/
/** @var Database */
private $_db;
/** @var Editor\Field[] */
private $_fields = [];
/** @var array */
private $_formData;
/** @var array */
private $_processData;
/** @var string */
private $_idPrefix = 'row_';
/** @var Editor\Join[] */
private $_join = [];
/** @var string[] */
private $_pkey = ['id'];
/** @var string[] */
private $_table = [];
/** @var string[] */
private $_readTableNames = [];
/** @var bool */
private $_transaction = true;
/** @var array */
private $_where = [];
/** @var bool */
private $_write = true;
/** @var array */
private $_leftJoin = [];
/** @var bool - deprecated */
private $_whereSet = false;
/** @var array */
private $_out = [];
/** @var array[] */
private $_events = [];
/** @var bool */
private $_debug = false;
/** @var array */
private $_debugInfo = [];
/** @var string Log output path */
private $_debugLog = '';
/** @var array */
private $_validator = [];
/** @var array */
private $_validatorAfterFields = [];
/** @var bool Enable true / catch when processing */
private $_tryCatch = true;
/** @var bool Enable / disable delete on left joined tables */
private $_leftJoinRemove = false;
/** @var string Action name allowing for configuration */
private $_actionName = 'action';
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public methods
*/
/**
* Get / set the action name to read in HTTP parameters. This can be useful
* to set if you are using a framework that uses the default name of `action`
* for something else (e.g. WordPress).
*
* @param string $_ Value to set. If not given, then used as a getter.
*
* @return ($_ is null ? string : $this) Value.
*/
public function actionName($_ = null)
{
return $this->_getSet($this->_actionName, $_);
}
/**
* Get the data constructed in this instance.
*
* This will get the PHP array of data that has been constructed for the
* command that has been processed by this instance. Therefore only useful after
* process has been called.
*
* @return array Processed data array.
*/
public function data()
{
return $this->_out;
}
/**
* Get / set the DB connection instance.
*
* @param Database $_ DataTable's Database class instance to use for database
* connectivity. If not given, then used as a getter.
*
* @return ($_ is null ? Database : $this) The Database connection instance if no parameter
* is given.
*/
public function db($_ = null)
{
return $this->_getSet($this->_db, $_);
}
/**
* Get / set debug mode and set a debug message.
*
* It can be useful to see the SQL statements that Editor is using. This
* method enables that ability. Information about the queries used is
* automatically added to the output data array / JSON under the property
* name `debugSql`.
*
* This method can also be called with a string parameter, which will be
* added to the debug information sent back to the client-side. This can
* be useful when debugging event listeners, etc.
*
* @param bool|mixed $_ Debug mode state. If not given, then used as a
* getter. If given as anything other than a boolean, it will be added
* to the debug information sent back to the client.
* @param string $path Set an output path to log debug information
*
* @return ($_ is null ? bool : $this) Debug mode state if no parameter is given.
*/
public function debug($_ = null, $path = null)
{
if (!is_bool($_)) {
$this->_debugInfo[] = $_;
return $this;
}
if ($path) {
$this->_debugLog = $path;
}
return $this->_getSet($this->_debug, $_);
}
/**
* Get / set field instance.
*
* The list of fields designates which columns in the table that Editor will work
* with (both get and set).
*
* @param Field|string ...$_ This parameter effects the return value of the
* function:
*
* * `null` - Get an array of all fields assigned to the instance
* * `string` - Get a specific field instance whose 'name' matches the
* field passed in
* * {@see Field} - Add a field to the instance's list of fields. This
* can be as many fields as required (i.e. multiple arguments)
* * `array` - An array of {@see Field} instances to add to the list
* of fields.
*
* @return ($_ is null ? ($_ is string ? Field : Field[]) : $this) The selected field, an array of fields, depending on the input parameter.
*
* @see {@see Field} for field documentation.
*/
public function field($_ = null)
{
$args = func_get_args();
if (is_string($_)) {
for ($i = 0, $ien = count($this->_fields); $i < $ien; ++$i) {
if ($this->_fields[$i]->name() === $_) {
return $this->_fields[$i];
}
}
throw new \Exception('Unknown field: ' . $_);
}
if ($_ !== null && !is_array($_)) {
$_ = $args;
}
return $this->_getSet($this->_fields, $_, true);
}
/**
* Get / set field instances.
*
* An alias of {@see field}, for convenience.
*
* @param Field|Field[] ...$_ Instances of the {@see Field} class, given as a single
* instance of {@see Field}, an array of {@see Field} instances, or multiple
* {@see Field} instance parameters for the function.
*
* @return ($_ is null ? Field[] : $this) Array of fields.
*
* @see {@see Field} for field documentation.
*/
public function fields($_ = null)
{
$args = func_get_args();
if ($_ !== null && !is_array($_)) {
$_ = $args;
}
return $this->_getSet($this->_fields, $_, true);
}
/**
* Get / set the DOM prefix.
*
* Typically primary keys are numeric and this is not a valid ID value in an
* HTML document - is also increases the likelihood of an ID clash if multiple
* tables are used on a single page. As such, a prefix is assigned to the
* primary key value for each row, and this is used as the DOM ID, so Editor
* can track individual rows.
*
* @param string $_ Primary key's name. If not given, then used as a getter.
*
* @return ($_ is null ? string : $this) Primary key value if no parameter is given.
*/
public function idPrefix($_ = null)
{
return $this->_getSet($this->_idPrefix, $_);
}
/**
* Get the data that is being processed by the Editor instance. This is only
* useful once the `process()` method has been called, and is available for
* use in validation and formatter methods.
*
* @return array Data given to `process()`.
*/
public function inData()
{
return $this->_processData;
}
/**
* Get / set join instances. Note that for the majority of use cases you
* will want to use the `leftJoin()` method. It is significantly easier
* to use if you are just doing a simple left join!
*
* The list of Join instances that Editor will join the parent table to
* (i.e. the one that the {@see Editor->table()} and {@see Editor->fields}
* methods refer to in this class instance).
*
* @param Join ...$_ Instances of the {@see Join} class, given as a
* single instance of {@see Join}, an array of {@see Join} instances,
* or multiple {@see Join} instance parameters for the function.
*
* @return ($_ is null ? Join[] : $this) Array of joins.
*/
public function join($_ = null)
{
$args = func_get_args();
if ($_ !== null && !is_array($_)) {
$_ = $args;
}
return $this->_getSet($this->_join, $_, true);
}
/**
* Get the JSON for the data constructed in this instance.
*
* Basically the same as the {@see Editor->data()} method, but in this case we echo, or
* return the JSON string of the data.
*
* @param bool $print Echo the JSON string out (true, default) or return it
* (false).
* @param int $options JSON encode option https://www.php.net/manual/en/json.constants.php
*
* @return ($print is false ? string : $this) JSON representation of the processed data if
* false is given as the first parameter.
*/
public function json($print = true, $options = 0)
{
if ($print) {
$json = json_encode($this->_out, $options);
header('Content-Type: application/json; charset=utf-8');
if ($json !== false) {
echo $json;
} else {
echo json_encode([
'error' => 'JSON encoding error: ' . json_last_error_msg(),
]);
}
return $this;
}
return json_encode($this->_out);
}
/**
* Echo out JSONP for the data constructed and processed in this instance.
* This is basically the same as {@see Editor->json()} but wraps the return in a
* JSONP callback.
*
* @param string $callback The callback function name to use. If not given
* or `null`, then `$_GET['callback']` is used (the jQuery default).
*
* @return $this
*/
public function jsonp($callback = null)
{
if (!$callback) {
$callback = $_GET['callback'];
}
if (preg_match('/[^a-zA-Z0-9_]/', $callback)) {
throw new \Exception('Invalid JSONP callback function name');
}
header('Content-Type: application/javascript; charset=utf-8');
echo $callback . '(' . json_encode($this->_out) . ');';
return $this;
}
/**
* Add a left join condition to the Editor instance, allowing it to operate
* over multiple tables. Multiple `leftJoin()` calls can be made for a
* single Editor instance to join multiple tables.
*
* A left join is the most common type of join that is used with Editor
* so this method is provided to make its use very easy to configure. Its
* parameters are basically the same as writing an SQL left join statement,
* but in this case Editor will handle the create, update and remove
* requirements of the join for you:
*
* * Create - On create Editor will insert the data into the primary table
* and then into the joined tables - selecting the required data for each
* table.
* * Edit - On edit Editor will update the main table, and then either
* update the existing rows in the joined table that match the join and
* edit conditions, or insert a new row into the joined table if required.
* * Remove - On delete Editor will remove the main row and then loop over
* each of the joined tables and remove the joined data matching the join
* link from the main table.
*
* Please note that when using join tables, Editor requires that you fully
* qualify each field with the field's table name. SQL can result table
* names for ambiguous field names, but for Editor to provide its full CRUD
* options, the table name must also be given. For example the field
* `first_name` in the table `users` would be given as `users.first_name`.
*
* @param string $table Table name to do a join onto
* @param string $field1 Field from the parent table to use as the join link
* @param string $operator Join condition (`=`, '<`, etc)
* @param string $field2 Field from the child table to use as the join link
*
* @return $this
*
* @example
* Simple join:
*
* ```php
* ->field(
* new Field( 'users.first_name as myField' ),
* new Field( 'users.last_name' ),
* new Field( 'users.dept_id' ),
* new Field( 'dept.name' )
* )
* ->leftJoin( 'dept', 'users.dept_id', '=', 'dept.id' )
* ->process($_POST)
* ->json();
* ```</code>```
*
* This is basically the same as the following SQL statement:
*
* ```sql
* SELECT users.first_name, users.last_name, user.dept_id, dept.name
* FROM users
* LEFT JOIN dept ON users.dept_id = dept.id
* ```
*/
public function leftJoin($table, $field1, $operator = null, $field2 = null)
{
$this->_leftJoin[] = [
'table' => $table,
'field1' => $field1,
'field2' => $field2,
'operator' => $operator,
];
return $this;
}
/**
* Indicate if a remove should be performed on left joined tables when deleting
* from the parent row. Note that this is disabled by default and will be
* removed completely in v2. Use `ON DELETE CASCADE` in your database instead.
*
* @deprecated
*
* @param bool $_ Value to set. If not given, then used as a getter.
*
* @return ($_ is null ? bool : $this) Value if no parameter is given.
*/
public function leftJoinRemove($_ = null)
{
return $this->_getSet($this->_leftJoinRemove, $_);
}
/**
* Add an event listener. The `Editor` class will trigger an number of
* events that some action can be taken on.
*
* @param string $name Event name
* @param callable($this, mixed, mixed, mixed, mixed, mixed): ?false $callback Callback function to execute when the event
* occurs
*
* @return $this
*/
public function on($name, $callback)
{
if (!isset($this->_events[$name])) {
$this->_events[$name] = [];
}
$this->_events[$name][] = $callback;
return $this;
}
/**
* Get / set the primary key.
*
* The primary key must be known to Editor so it will know which rows are being
* edited / deleted upon those actions. The default value is ['id'].
*
* @param string|string[] $_ Primary key's name. If not given, then used as a
* getter. An array of column names can be given to allow composite keys to
* be used.
*
* @return ($_ is null ? string[] : $this) Primary key value if no parameter is given.
*/
public function pkey($_ = null)
{
if (is_string($_)) {
$this->_pkey = [$_];
return $this;
}
return $this->_getSet($this->_pkey, $_);
}
/**
* Convert a primary key array of field values to a combined value.
*
* @param array $row The row of data that the primary key value should
* be extracted from.
* @param bool $flat Flag to indicate if the given array is flat
* (useful for `where` conditions) or nested for join tables.
*
* @return string The created primary key value.
*/
public function pkeyToValue($row, $flat = false)
{
$pkey = $this->_pkey;
$id = [];
for ($i = 0, $ien = count($pkey); $i < $ien; ++$i) {
$column = $pkey[$i];
if ($flat) {
if (isset($row[$column])) {
if ($row[$column] === null) {
throw new \Exception('Primary key value is null.', 1);
}
$val = $row[$column];
} else {
$val = null;
}
} else {
$val = $this->_readProp($column, $row);
}
if ($val === null) {
throw new \Exception('Primary key element is not available in data set.', 1);
}
$id[] = $val;
}
return implode($this->_pkey_separator(), $id);
}
/**
* Convert a primary key combined value to an array of field values.
*
* @param string $value The id that should be split apart
* @param bool $flat Flag to indicate if the returned array should be
* flat (useful for `where` conditions) or nested for join tables.
* @param string[] $pkey The primary key name - will use the instance value
* if not given
*
* @return array Array of field values that the id was made up of.
*/
public function pkeyToArray($value, $flat = false, $pkey = null)
{
$arr = [];
$value = str_replace($this->idPrefix(), '', $value);
$idParts = explode($this->_pkey_separator(), $value);
if ($pkey === null) {
$pkey = $this->_pkey;
}
if (count($pkey) !== count($idParts)) {
throw new \Exception("Primary key data doesn't match submitted data", 1);
}
for ($i = 0, $ien = count($idParts); $i < $ien; ++$i) {
if ($flat) {
$arr[$pkey[$i]] = $idParts[$i];
} else {
$this->_writeProp($arr, $pkey[$i], $idParts[$i]);
}
}
return $arr;
}
/**
* Process a request from the Editor client-side to get / set data.
*
* @param array $data Typically $_POST or $_GET as required by what is sent
* by Editor
*
* @return $this
*/
public function process($data)
{
if ($this->_debug) {
$debugInfo = &$this->_debugInfo;
$debugInfo[] = 'Editor PHP libraries - version ' . $this->version;
$this->_db->debug(static function ($mess) use (&$debugInfo) {
$debugInfo[] = $mess;
});
}
if ($this->_tryCatch) {
try {
$this->_process($data);
} catch (\Exception $e) {
// Error feedback
$this->_out['error'] = $e->getMessage();
if ($this->_transaction) {
$this->_db->rollback();
}
}
} else {
$this->_process($data);
}
if ($this->_debug) {
$this->_out['debug'] = $this->_debugInfo;
// Save to a log file
if ($this->_debugLog) {
file_put_contents($this->_debugLog, json_encode($this->_debugInfo) . "\n", \FILE_APPEND);
}
$this->_db->debug(false);
}
return $this;
}
/**
* The CRUD read table name. If this method is used, Editor will create from the
* table name(s) given rather than those given by `Editor->table()`. This can be
* a useful distinction to allow a read from a VIEW (which could make use of a
* complex SELECT) while writing to a different table.
*
* @param string|array ...$_ Read table names given as a single string, an array
* of strings or multiple string parameters for the function.
*
* @return ($_ is null ? string[] : $this) Array of read tables names.
*/
public function readTable($_ = null)
{
$args = func_get_args();
if ($_ !== null && !is_array($_)) {
$_ = $args;
}
return $this->_getSet($this->_readTableNames, $_, true);
}
/**
* Get / set the table name.
*
* The table name designated which DB table Editor will use as its data
* source for working with the database. Table names can be given with an
* alias, which can be used to simplify larger table names. The field
* names would also need to reflect the alias, just like an SQL query. For
* example: `users as a`.
*
* @param string|array ...$_ Table names given as a single string, an array of
* strings or multiple string parameters for the function.
*
* @return ($_ is null ? string[] : $this) Array of tables names.
*/
public function table($_ = null)
{
$args = func_get_args();
if ($_ !== null && !is_array($_)) {
$_ = $args;
}
return $this->_getSet($this->_table, $_, true);
}
/**
* Get / set transaction support.
*
* When enabled (which it is by default) Editor will use an SQL transaction
* to ensure data integrity while it is performing operations on the table.
* This can be optionally disabled using this method, if required by your
* database configuration.
*
* @param bool $_ Enable (`true`) or disabled (`false`) transactions.
* If not given, then used as a getter.
*
* @return ($_ is null ? bool : $this) Transactions enabled flag.
*/
public function transaction($_ = null)
{
return $this->_getSet($this->_transaction, $_);
}
/**
* Enable / try catch when `process()` is called. Disabling this can be
* useful for debugging, but is not recommended for production.
*
* @param bool $_ `true` to enable (default), otherwise false to disable
*
* @return ($_ is null ? bool : $this) Value if used as a getter.
*/
public function tryCatch($_ = null)
{
return $this->_getSet($this->_tryCatch, $_);
}
/**
* Perform validation on a data set.
*
* Note that validation is performed on data only when the action is
* `create` or `edit`. Additionally, validation is performed on the _wire
* data_ - i.e. that which is submitted from the client, without formatting.
* Any formatting required by `setFormatter` is performed after the data
* from the client has been validated.
*
* @param array $errors Output array to which field error information will
* be written. Each element in the array represents a field in an error
* condition. These elements are themselves arrays with two properties
* set; `name` and `status`.
* @param array $data The format data to check
*
* @return bool `true` if the data is valid, `false` if not.
*/
public function validate(&$errors, $data)
{
// Validation is only performed on create and edit
if ($data[$this->_actionName] != 'create' && $data[$this->_actionName] != 'edit') {
return true;
}
foreach ($data['data'] as $id => $values) {
for ($i = 0; $i < count($this->_fields); ++$i) {
$field = $this->_fields[$i];
$validation = $field->validate(
$values,
$this,
str_replace($this->idPrefix(), '', $id)
);
if ($validation !== true) {
$errors[] = [
'name' => $field->name(),
'status' => $validation,
];
}
}
// MJoin validation
for ($i = 0; $i < count($this->_join); ++$i) {
$this->_join[$i]->validate($errors, $this, $values, $data[$this->_actionName]);
}
}
// Global validators to run _after_ field validation
for ($i = 0; $i < count($this->_validatorAfterFields); ++$i) {
$validator = $this->_validatorAfterFields[$i];
$ret = $validator($this, $this->_actionName, $data);
if (is_string($ret)) {
$this->_out['error'] = $ret;
return false;
}
}
return count($errors) > 0 ? false : true;
}
/**
* Get / set a global validator that will be triggered for the create, edit
* and remove actions performed from the client-side. Multiple validators
* can be added.
*
* @param bool|callable $afterFields `true` to run the validator after field validation,
* `false` to run before. Can be omitted (which is the equivalent of `false`).
* @param callable($this, self::ACTION_*, array): ?string $_ Function to execute when validating the input data.
* It is passed three parameters: 1. The editor instance, 2. The action
* and 3. The values.
*
* @return ($_ is null ? callable : $this) The validator function.
*/
public function validator($afterFields, $_ = null)
{
if (is_bool($afterFields) && $afterFields === true) {
return $this->_getSet($this->_validatorAfterFields, $_, true);
}
// Argument shift
$_ = $afterFields;
return $this->_getSet($this->_validator, $_, true);
}
/**
* Where condition to add to the query used to get data from the database.
*
* Can be used in two different ways:
*
* * Simple case: `where( field, value, operator )`
* * Complex: `where( fn )`
*
* The simple case is fairly self explanatory, a condition is applied to the
* data that looks like `field operator value` (e.g. `name = 'Allan'`). The
* complex case allows full control over the query conditions by providing a
* closure function that has access to the database Query that Editor is
* using, so you can use the `where()`, `or_where()`, `and_where()` and
* `where_group()` methods as you require.
*
* Please be very careful when using this method! If an edit made by a user
* using Editor removes the row from the where condition, the result is
* undefined (since Editor expects the row to still be available, but the
* condition removes it from the result set).
*
* @param string|\Closure(Query): void $key Single field name or a closure function
* @param string $value Single field value.
* @param string $op Condition operator: <, >, = etc
*
* @return ($key is null ? string[] : $this) Where condition array.
*/
public function where($key = null, $value = null, $op = '=')
{
if ($key === null) {
return $this->_where;
}
if ($key instanceof \Closure) {
$this->_where[] = $key;
} else {
$this->_where[] = [
'key' => $key,
'value' => $value,
'op' => $op,
];
}
return $this;
}
/**
* Get / set if the WHERE conditions should be included in the create and
* edit actions.
*
* @param bool $_ Include (`true`), or not (`false`)
*
* @return ($_ is null ? bool : $this) Current value
*
* @deprecated Note that `whereSet` is now deprecated and replaced with the
* ability to set values for columns on create and edit. The C# libraries
* do not support this option at all.
*/
public function whereSet($_ = null)
{
return $this->_getSet($this->_whereSet, $_);
}
/**
* @param bool $_writeVal
*
* @return ($_writeVal is null ? bool : $this)
*/
public function write($_writeVal = null)
{
return $this->_getSet($this->_write, $_writeVal);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods
*/
/**
* Process a request from the Editor client-side to get / set data.
*
* @param array $data Data to process
*/
private function _process($data)
{
$this->_out = [
'cancelled' => [],
'data' => [],
'error' => '',
'fieldErrors' => [],
'ipOpts' => [],
'options' => [],
];
$action = Editor::action($data);