Passed
Push — master ( febce6...7a83de )
by Thomas
12:12
created

TabulatorGrid::getRowHeight()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace LeKoala\Tabulator;
4
5
use Exception;
6
use RuntimeException;
7
use SilverStripe\i18n\i18n;
8
use SilverStripe\Forms\Form;
9
use InvalidArgumentException;
10
use SilverStripe\ORM\SS_List;
11
use SilverStripe\Core\Convert;
12
use SilverStripe\ORM\DataList;
13
use SilverStripe\ORM\ArrayList;
14
use SilverStripe\Core\ClassInfo;
15
use SilverStripe\ORM\DataObject;
16
use SilverStripe\View\ArrayData;
17
use SilverStripe\Forms\FieldList;
18
use SilverStripe\Forms\FormField;
19
use SilverStripe\Control\Director;
20
use SilverStripe\View\Requirements;
21
use SilverStripe\Control\Controller;
22
use SilverStripe\Control\HTTPRequest;
23
use SilverStripe\Control\HTTPResponse;
24
use SilverStripe\ORM\FieldType\DBEnum;
25
use SilverStripe\Control\RequestHandler;
26
use SilverStripe\Core\Injector\Injector;
27
use SilverStripe\Security\SecurityToken;
28
use SilverStripe\ORM\DataObjectInterface;
29
use SilverStripe\ORM\FieldType\DBBoolean;
30
use SilverStripe\Forms\GridField\GridFieldConfig;
31
use SilverStripe\ORM\Filters\PartialMatchFilter;
32
33
/**
34
 * This is a replacement for most GridField usages in SilverStripe
35
 * It can easily work in the frontend too
36
 *
37
 * @link http://www.tabulator.info/
38
 */
39
class TabulatorGrid extends FormField
40
{
41
    const POS_START = 'start';
42
    const POS_END = 'end';
43
44
    // @link http://www.tabulator.info/examples/5.5?#fittodata
45
    const LAYOUT_FIT_DATA = "fitData";
46
    const LAYOUT_FIT_DATA_FILL = "fitDataFill";
47
    const LAYOUT_FIT_DATA_STRETCH = "fitDataStretch";
48
    const LAYOUT_FIT_DATA_TABLE = "fitDataTable";
49
    const LAYOUT_FIT_COLUMNS = "fitColumns";
50
51
    const RESPONSIVE_LAYOUT_HIDE = "hide";
52
    const RESPONSIVE_LAYOUT_COLLAPSE = "collapse";
53
54
    // @link http://www.tabulator.info/docs/5.5/format
55
    const FORMATTER_PLAINTEXT = 'plaintext';
56
    const FORMATTER_TEXTAREA = 'textarea';
57
    const FORMATTER_HTML = 'html';
58
    const FORMATTER_MONEY = 'money';
59
    const FORMATTER_IMAGE = 'image';
60
    const FORMATTER_LINK = 'link';
61
    const FORMATTER_DATETIME = 'datetime';
62
    const FORMATTER_DATETIME_DIFF = 'datetimediff';
63
    const FORMATTER_TICKCROSS = 'tickCross';
64
    const FORMATTER_COLOR = 'color';
65
    const FORMATTER_STAR = 'star';
66
    const FORMATTER_TRAFFIC = 'traffic';
67
    const FORMATTER_PROGRESS = 'progress';
68
    const FORMATTER_LOOKUP = 'lookup';
69
    const FORMATTER_BUTTON_TICK = 'buttonTick';
70
    const FORMATTER_BUTTON_CROSS = 'buttonCross';
71
    const FORMATTER_ROWNUM = 'rownum';
72
    const FORMATTER_HANDLE = 'handle';
73
    // @link http://www.tabulator.info/docs/5.5/format#format-module
74
    const FORMATTER_ROW_SELECTION = 'rowSelection';
75
    const FORMATTER_RESPONSIVE_COLLAPSE = 'responsiveCollapse';
76
77
    // our built in functions
78
    const JS_BOOL_GROUP_HEADER = 'SSTabulator.boolGroupHeader';
79
    const JS_DATA_AJAX_RESPONSE = 'SSTabulator.dataAjaxResponse';
80
81
    /**
82
     * @config
83
     */
84
    private static array $allowed_actions = [
85
        'load',
86
        'handleItem',
87
        'handleTool',
88
        'configProvider',
89
        'autocomplete',
90
        'handleBulkAction',
91
    ];
92
93
    private static $url_handlers = [
94
        'item/$ID' => 'handleItem',
95
        'tool/$ID' => 'handleTool',
96
        'bulkAction/$ID' => 'handleBulkAction',
97
    ];
98
99
    private static array $casting = [
100
        'JsonOptions' => 'HTMLFragment',
101
        'ShowTools' => 'HTMLFragment',
102
        'dataAttributesHTML' => 'HTMLFragment',
103
    ];
104
105
    /**
106
     * @config
107
     */
108
    private static bool $load_styles = true;
109
110
    /**
111
     * @config
112
     */
113
    private static string $luxon_version = '3';
114
115
    /**
116
     * @config
117
     */
118
    private static string $last_icon_version = '2';
119
120
    /**
121
     * @config
122
     */
123
    private static bool $use_cdn = false;
124
125
    /**
126
     * @config
127
     */
128
    private static bool $enable_luxon = false;
129
130
    /**
131
     * @config
132
     */
133
    private static bool $enable_last_icon = false;
134
135
    /**
136
     * @config
137
     */
138
    private static bool $enable_requirements = true;
139
140
    /**
141
     * @config
142
     */
143
    private static bool $enable_js_modules = true;
144
145
    /**
146
     * @link http://www.tabulator.info/docs/5.5/options
147
     * @config
148
     */
149
    private static array $default_options = [
150
        'index' => "ID", // http://tabulator.info/docs/5.5/data#row-index
151
        'layout' => 'fitColumns', // http://www.tabulator.info/docs/5.5/layout#layout
152
        'height' => '100%', // http://www.tabulator.info/docs/5.5/layout#height-fixed
153
        'responsiveLayout' => "hide", // http://www.tabulator.info/docs/5.5/layout#responsive
154
    ];
155
156
    /**
157
     * @link http://tabulator.info/docs/5.5/columns#defaults
158
     * @config
159
     */
160
    private static array $default_column_options = [
161
        'resizable' => false,
162
    ];
163
164
    private static bool $enable_ajax_init = true;
165
166
    /**
167
     * @config
168
     */
169
    private static bool $default_lazy_init = false;
170
171
    /**
172
     * Data source.
173
     */
174
    protected ?SS_List $list;
175
176
    /**
177
     * @link http://www.tabulator.info/docs/5.5/columns
178
     */
179
    protected array $columns = [];
180
181
    /**
182
     * @link http://tabulator.info/docs/5.5/columns#defaults
183
     */
184
    protected array $columnDefaults = [];
185
186
    /**
187
     * @link http://www.tabulator.info/docs/5.5/options
188
     */
189
    protected array $options = [];
190
191
    protected bool $autoloadDataList = true;
192
193
    protected bool $rowClickTriggersAction = false;
194
195
    protected int $pageSize = 10;
196
197
    protected string $itemRequestClass = '';
198
199
    protected string $modelClass = '';
200
201
    protected bool $lazyInit = false;
202
203
    protected array $tools = [];
204
205
    /**
206
     * @var AbstractBulkAction[]
207
     */
208
    protected array $bulkActions = [];
209
210
    protected array $listeners = [];
211
212
    protected array $linksOptions = [
213
        'ajaxURL'
214
    ];
215
216
    protected array $dataAttributes = [];
217
218
    protected string $controllerFunction = "";
219
220
    protected string $editUrl = "";
221
222
    protected string $moveUrl = "";
223
224
    protected string $bulkUrl = "";
225
226
    protected bool $globalSearch = false;
227
228
    protected array $wildcardFields = [];
229
230
    protected array $quickFilters = [];
231
232
    protected string $defaultFilter = 'PartialMatch';
233
234
    protected bool $groupLayout = false;
235
236
    protected bool $enableGridManipulation = false;
237
238
    /**
239
     * @param string $fieldName
240
     * @param string|null|bool $title
241
     * @param SS_List $value
242
     */
243
    public function __construct($name, $title = null, $value = null)
244
    {
245
        // Set options and defaults first
246
        $this->options = self::config()->default_options ?? [];
247
        $this->columnDefaults = self::config()->default_column_options ?? [];
248
249
        parent::__construct($name, $title, $value);
250
        $this->setLazyInit(self::config()->default_lazy_init);
251
252
        // We don't want regular setValue for this since it would break with loadFrom logic
253
        if ($value) {
254
            $this->setList($value);
255
        }
256
    }
257
258
    /**
259
     * This helps if some third party code expects the TabulatorGrid to be a GridField
260
     * Only works to a really basic extent
261
     */
262
    public function getConfig(): GridFieldConfig
263
    {
264
        return new GridFieldConfig;
265
    }
266
267
    /**
268
     * This helps if some third party code expects the TabulatorGrid to be a GridField
269
     * Only works to a really basic extent
270
     */
271
    public function setConfig($config)
272
    {
273
        // ignore
274
    }
275
276
    /**
277
     * @return string
278
     */
279
    public function getValueJson()
280
    {
281
        $v = $this->value ?? '';
282
        if (is_array($v)) {
283
            $v = json_encode($v);
284
        }
285
        if (strpos($v, '[') !== 0) {
286
            return '[]';
287
        }
288
        return $v;
289
    }
290
291
    public function saveInto(DataObjectInterface $record)
292
    {
293
        if ($this->enableGridManipulation) {
294
            $value = $this->dataValue();
295
            if (is_array($value)) {
296
                $this->value = json_encode(array_values($value));
297
            }
298
            parent::saveInto($record);
299
        }
300
    }
301
302
    /**
303
     * Temporary link that will be replaced by a real link by processLinks
304
     * TODO: not really happy with this, find a better way
305
     *
306
     * @param string $action
307
     * @return string
308
     */
309
    public function TempLink(string $action, bool $controller = true): string
310
    {
311
        // It's an absolute link
312
        if (strpos($action, '/') === 0 || strpos($action, 'http') === 0) {
313
            return $action;
314
        }
315
        // Already temp
316
        if (strpos($action, ':') !== false) {
317
            return $action;
318
        }
319
        $prefix = $controller ? "controller" : "form";
320
        return "$prefix:$action";
321
    }
322
323
    public function ControllerLink(string $action): string
324
    {
325
        return $this->getForm()->getController()->Link($action);
326
    }
327
328
    public function getCreateLink(): string
329
    {
330
        return Controller::join_links($this->Link('item'), 'new');
331
    }
332
333
    /**
334
     * @param FieldList $fields
335
     * @param string $name
336
     * @return TabulatorGrid|null
337
     */
338
    public static function replaceGridField(FieldList $fields, string $name)
339
    {
340
        /** @var \SilverStripe\Forms\GridField\GridField $gridField */
341
        $gridField = $fields->dataFieldByName($name);
342
        if (!$gridField) {
0 ignored issues
show
introduced by
$gridField is of type SilverStripe\Forms\GridField\GridField, thus it always evaluated to true.
Loading history...
343
            return;
344
        }
345
        if ($gridField instanceof TabulatorGrid) {
0 ignored issues
show
introduced by
$gridField is never a sub-type of LeKoala\Tabulator\TabulatorGrid.
Loading history...
346
            return $gridField;
347
        }
348
        $tabulatorGrid = new TabulatorGrid($name, $gridField->Title(), $gridField->getList());
349
        // In the cms, this is mostly never happening
350
        if ($gridField->getForm()) {
351
            $tabulatorGrid->setForm($gridField->getForm());
352
        }
353
        $tabulatorGrid->configureFromDataObject($gridField->getModelClass());
354
        $tabulatorGrid->setLazyInit(true);
355
        $fields->replaceField($name, $tabulatorGrid);
356
357
        return $tabulatorGrid;
358
    }
359
360
    public function configureFromDataObject($className = null): void
361
    {
362
        $this->columns = [];
363
364
        if (!$className) {
365
            $className = $this->getModelClass();
366
        }
367
        if (!$className) {
368
            throw new RuntimeException("Could not find the model class");
369
        }
370
        $this->modelClass = $className;
371
372
        /** @var DataObject $singl */
373
        $singl = singleton($className);
374
375
        // Mock some base columns using SilverStripe built-in methods
376
        $columns = [];
377
378
        foreach ($singl->summaryFields() as $field => $title) {
379
            // Deal with this in load() instead
380
            // if (strpos($field, '.') !== false) {
381
            // $fieldParts = explode(".", $field);
382
383
            // It can be a relation Users.Count or a field Field.Nice
384
            // $classOrField = $fieldParts[0];
385
            // $relationOrMethod = $fieldParts[1];
386
            // }
387
            $title = str_replace(".", " ", $title);
388
            $columns[$field] = [
389
                'field' => $field,
390
                'title' => $title,
391
            ];
392
393
            $dbObject = $singl->dbObject($field);
394
            if ($dbObject) {
395
                if ($dbObject instanceof DBBoolean) {
396
                    $columns[$field]['formatter'] = "customTickCross";
397
                }
398
            }
399
        }
400
        foreach ($singl->searchableFields() as $key => $searchOptions) {
401
            /*
402
            "filter" => "NameOfTheFilter"
403
            "field" => "SilverStripe\Forms\FormField"
404
            "title" => "Title of the field"
405
            */
406
            if (!isset($columns[$key])) {
407
                continue;
408
            }
409
            $columns[$key]['headerFilter'] = true;
410
            // $columns[$key]['headerFilterPlaceholder'] = $searchOptions['title'];
411
            //TODO: implement filter mapping
412
            switch ($searchOptions['filter']) {
413
                default:
414
                    $columns[$key]['headerFilterFunc'] =  "like";
415
                    break;
416
            }
417
418
            // Restrict based on data type
419
            $dbObject = $singl->dbObject($key);
420
            if ($dbObject) {
421
                if ($dbObject instanceof DBBoolean) {
422
                    $columns[$key]['headerFilter'] = 'tickCross';
423
                    $columns[$key]['headerFilterFunc'] =  "=";
424
                    $columns[$key]['headerFilterParams'] =  [
425
                        'tristate' => true
426
                    ];
427
                }
428
                if ($dbObject instanceof DBEnum) {
429
                    $columns[$key]['headerFilter'] = 'list';
430
                    $columns[$key]['headerFilterFunc'] =  "=";
431
                    $columns[$key]['headerFilterParams'] =  [
432
                        'values' => $dbObject->enumValues()
433
                    ];
434
                }
435
            }
436
        }
437
438
        // Allow customizing our columns based on record
439
        if ($singl->hasMethod('tabulatorColumns')) {
440
            $fields = $singl->tabulatorColumns();
441
            if (!is_array($fields)) {
442
                throw new RuntimeException("tabulatorColumns must return an array");
443
            }
444
            foreach ($fields as $key => $columnOptions) {
445
                $baseOptions = $columns[$key] ?? [];
446
                $columns[$key] = array_merge($baseOptions, $columnOptions);
447
            }
448
        }
449
450
        $this->extend('updateConfiguredColumns', $columns);
451
452
        foreach ($columns as $col) {
453
            $this->addColumn($col['field'], $col['title'], $col);
454
        }
455
456
        // Sortable ?
457
        if ($singl->hasField('Sort')) {
458
            $this->wizardMoveable();
459
        }
460
461
        // Actions
462
        // We use a pseudo link, because maybe we cannot call Link() yet if it's not linked to a form
463
464
        $this->bulkUrl = $this->TempLink("bulkAction/", false);
465
466
        // - Core actions, handled by TabulatorGrid
467
        $itemUrl = $this->TempLink('item/{ID}', false);
468
        if ($singl->canEdit()) {
469
            $this->addButton("ui_edit", $itemUrl, "edit", "Edit");
470
            $this->editUrl = $this->TempLink("item/{ID}/ajaxEdit", false);
471
        } elseif ($singl->canView()) {
472
            $this->addButton("ui_view", $itemUrl, "visibility", "View");
473
        }
474
475
        // - Tools
476
        $this->tools = [];
477
        if ($singl->canCreate()) {
478
            $this->addTool(self::POS_START, new TabulatorAddNewButton($this), 'add_new');
0 ignored issues
show
Unused Code introduced by
The call to LeKoala\Tabulator\Tabula...ewButton::__construct() has too many arguments starting with $this. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

478
            $this->addTool(self::POS_START, /** @scrutinizer ignore-call */ new TabulatorAddNewButton($this), 'add_new');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
479
        }
480
        if (class_exists(\LeKoala\ExcelImportExport\ExcelImportExport::class)) {
0 ignored issues
show
Bug introduced by
The type LeKoala\ExcelImportExport\ExcelImportExport was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
481
            $this->addTool(self::POS_END, new TabulatorExportButton($this), 'export');
0 ignored issues
show
Unused Code introduced by
The call to LeKoala\Tabulator\Tabula...rtButton::__construct() has too many arguments starting with $this. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

481
            $this->addTool(self::POS_END, /** @scrutinizer ignore-call */ new TabulatorExportButton($this), 'export');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
482
        }
483
484
        // - Custom actions are forwarded to the model itself
485
        if ($singl->hasMethod('tabulatorRowActions')) {
486
            $rowActions = $singl->tabulatorRowActions();
487
            if (!is_array($rowActions)) {
488
                throw new RuntimeException("tabulatorRowActions must return an array");
489
            }
490
            foreach ($rowActions as $key => $actionConfig) {
491
                $action = $actionConfig['action'] ?? $key;
492
                $url = $this->TempLink("item/{ID}/customAction/$action", false);
493
                $icon = $actionConfig['icon'] ?? "cog";
494
                $title = $actionConfig['title'] ?? "";
495
496
                $button = $this->makeButton($url, $icon, $title);
497
                if (!empty($actionConfig['ajax'])) {
498
                    $button['formatterParams']['ajax'] = true;
499
                }
500
                $this->addButtonFromArray("ui_customaction_$action", $button);
501
            }
502
        }
503
504
        $this->setRowClickTriggersAction(true);
505
    }
506
507
    public static function requirements(): void
508
    {
509
        $load_styles = self::config()->load_styles;
510
        $luxon_version = self::config()->luxon_version;
511
        $enable_luxon = self::config()->enable_luxon;
512
        $last_icon_version = self::config()->last_icon_version;
513
        $enable_last_icon = self::config()->enable_last_icon;
514
        $enable_js_modules = self::config()->enable_js_modules;
515
516
        $jsOpts = [];
517
        if ($enable_js_modules) {
518
            $jsOpts['type'] = 'module';
519
        }
520
521
        if ($luxon_version && $enable_luxon) {
522
            // Do not load as module or we would get undefined luxon global var
523
            Requirements::javascript("https://cdn.jsdelivr.net/npm/luxon@$luxon_version/build/global/luxon.min.js");
524
        }
525
        if ($last_icon_version && $enable_last_icon) {
526
            Requirements::css("https://cdn.jsdelivr.net/npm/last-icon@$last_icon_version/last-icon.min.css");
527
            // Do not load as module even if asked to ensure load speed
528
            Requirements::javascript("https://cdn.jsdelivr.net/npm/last-icon@$last_icon_version/last-icon.min.js");
529
        }
530
531
        Requirements::javascript('lekoala/silverstripe-tabulator:client/TabulatorField.js', $jsOpts);
532
        if ($load_styles) {
533
            Requirements::css('lekoala/silverstripe-tabulator:client/custom-tabulator.css');
534
            Requirements::javascript('lekoala/silverstripe-tabulator:client/tabulator-grid.min.js', $jsOpts);
535
        } else {
536
            // you must load th css yourself based on your preferences
537
            Requirements::javascript('lekoala/silverstripe-tabulator:client/tabulator-grid.raw.min.js', $jsOpts);
538
        }
539
    }
540
541
    public function setValue($value, $data = null)
542
    {
543
        // Allow set raw json as value
544
        if ($value && is_string($value) && strpos($value, '[') === 0) {
545
            $value = json_decode($value);
546
        }
547
        if ($value instanceof DataList) {
548
            $this->configureFromDataObject($value->dataClass());
549
        }
550
        return parent::setValue($value, $data);
551
    }
552
553
    public function Field($properties = [])
554
    {
555
        if (self::config()->enable_requirements) {
556
            self::requirements();
557
        }
558
559
        // Make sure we can use a standalone version of the field without a form
560
        // Function should match the name
561
        if (!$this->form) {
562
            $this->form = new Form(Controller::curr(), $this->getControllerFunction());
563
        }
564
565
        // Data attributes for our custom behaviour
566
        $this->setDataAttribute("row-click-triggers-action", $this->rowClickTriggersAction);
567
568
        $this->setDataAttribute("listeners", $this->listeners);
569
        if ($this->editUrl) {
570
            $url = $this->processLink($this->editUrl);
571
            $this->setDataAttribute("edit-url", $url);
572
        }
573
        if ($this->moveUrl) {
574
            $url = $this->processLink($this->moveUrl);
575
            $this->setDataAttribute("move-url", $url);
576
        }
577
        if (!empty($this->bulkActions)) {
578
            $url = $this->processLink($this->bulkUrl);
579
            $this->setDataAttribute("bulk-url", $url);
580
        }
581
582
        return parent::Field($properties);
583
    }
584
585
    public function ShowTools(): string
586
    {
587
        if (empty($this->tools)) {
588
            return '';
589
        }
590
        $html = '';
591
        $html .= '<div class="tabulator-tools">';
592
        $html .= '<div class="tabulator-tools-start">';
593
        foreach ($this->tools as $tool) {
594
            if ($tool['position'] != self::POS_START) {
595
                continue;
596
            }
597
            $html .= ($tool['tool'])->forTemplate();
598
        }
599
        $html .= '</div>';
600
        $html .= '<div class="tabulator-tools-end">';
601
        foreach ($this->tools as $tool) {
602
            if ($tool['position'] != self::POS_END) {
603
                continue;
604
            }
605
            $html .= ($tool['tool'])->forTemplate();
606
        }
607
        // Show bulk actions at the end
608
        if (!empty($this->bulkActions)) {
609
            $selectLabel = _t(__CLASS__ . ".BULKSELECT", "Select a bulk action");
610
            $confirmLabel = _t(__CLASS__ . ".BULKCONFIRM", "Go");
611
            $html .= "<select class=\"tabulator-bulk-select\">";
612
            $html .= "<option>" . $selectLabel . "</option>";
613
            foreach ($this->bulkActions as $bulkAction) {
614
                $v = $bulkAction->getName();
615
                $xhr = $bulkAction->getXhr();
616
                $destructive = $bulkAction->getDestructive();
617
                $html .= "<option value=\"$v\" data-xhr=\"$xhr\" data-destructive=\"$destructive\">" . $bulkAction->getLabel() . "</option>";
618
            }
619
            $html .= "</select>";
620
            $html .= "<button class=\"tabulator-bulk-confirm btn\">" . $confirmLabel . "</button>";
621
        }
622
        $html .= '</div>';
623
        $html .= '</div>';
624
        return $html;
625
    }
626
627
    public function JsonOptions(): string
628
    {
629
        $this->processLinks();
630
631
        $data = $this->list ?? [];
632
        if ($this->autoloadDataList && $data instanceof DataList) {
633
            $data = null;
634
        }
635
        $opts = $this->options;
636
        $opts['columnDefaults'] = $this->columnDefaults;
637
638
        if (empty($this->columns)) {
639
            $opts['autoColumns'] = true;
640
        } else {
641
            $opts['columns'] = array_values($this->columns);
642
        }
643
644
        if ($data && is_iterable($data)) {
645
            if ($data instanceof ArrayList) {
646
                $data = $data->toArray();
647
            } else {
648
                if (is_iterable($data) && !is_array($data)) {
649
                    $data = iterator_to_array($data);
650
                }
651
            }
652
            $opts['data'] = $data;
653
        }
654
655
        // i18n
656
        $locale = strtolower(str_replace('_', '-', i18n::get_locale()));
657
        $paginationTranslations = [
658
            "first" => _t("TabulatorPagination.first", "First"),
659
            "first_title" =>  _t("TabulatorPagination.first_title", "First Page"),
660
            "last" =>  _t("TabulatorPagination.last", "Last"),
661
            "last_title" => _t("TabulatorPagination.last_title", "Last Page"),
662
            "prev" => _t("TabulatorPagination.prev", "Previous"),
663
            "prev_title" =>  _t("TabulatorPagination.prev_title", "Previous Page"),
664
            "next" => _t("TabulatorPagination.next", "Next"),
665
            "next_title" =>  _t("TabulatorPagination.next_title", "Next Page"),
666
            "all" =>  _t("TabulatorPagination.all", "All"),
667
        ];
668
        $dataTranslations = [
669
            "loading" => _t("TabulatorData.loading", "Loading"),
670
            "error" => _t("TabulatorData.error", "Error"),
671
        ];
672
        $groupsTranslations = [
673
            "item" => _t("TabulatorGroups.item", "Item"),
674
            "items" => _t("TabulatorGroups.items", "Items"),
675
        ];
676
        $headerFiltersTranslations = [
677
            "default" => _t("TabulatorHeaderFilters.default", "filter column..."),
678
        ];
679
        $bulkActionsTranslations = [
680
            "no_action" => _t("TabulatorBulkActions.no_action", "Please select an action"),
681
            "no_records" => _t("TabulatorBulkActions.no_records", "Please select a record"),
682
            "destructive" => _t("TabulatorBulkActions.destructive", "Confirm destructive action ?"),
683
        ];
684
        $translations = [
685
            'data' => $dataTranslations,
686
            'groups' => $groupsTranslations,
687
            'pagination' => $paginationTranslations,
688
            'headerFilters' => $headerFiltersTranslations,
689
            'bulkActions' => $bulkActionsTranslations,
690
        ];
691
        $opts['locale'] = $locale;
692
        $opts['langs'] = [
693
            $locale => $translations
694
        ];
695
696
        // Apply state
697
        $state = $this->getState();
698
        if (!empty($state['filter'])) {
699
            // @link https://tabulator.info/docs/5.5/filter#initial
700
            // We need to split between global filters and header filters
701
            $allFilters = $state['filter'] ?? [];
702
            $globalFilters = [];
703
            $headerFilters = [];
704
            foreach ($allFilters as $allFilter) {
705
                if (strpos($allFilter['field'], '__') === 0) {
706
                    $globalFilters[] = $allFilter;
707
                } else {
708
                    $headerFilters[] = $allFilter;
709
                }
710
            }
711
            $opts['initialFilter'] = $globalFilters;
712
            $opts['initialHeaderFilter'] = $headerFilters;
713
        }
714
        if (!empty($state['sort'])) {
715
            // @link https://tabulator.info/docs/5.5/sort#initial
716
            $opts['initialSort'] = $state['sort'];
717
        }
718
719
        // Restore state from server
720
        $opts['_state'] = $state;
721
722
        // Add our extension initCallback
723
        $opts['_initCallback'] = ['__fn' => 'SSTabulator.initCallback'];
724
725
        unset($opts['height']);
726
        $json = json_encode($opts);
727
728
        // Escape '
729
        $json = str_replace("'", '&#39;', $json);
730
731
732
        return $json;
733
    }
734
735
    /**
736
     * @param Controller $controller
737
     * @return CompatLayerInterface
738
     */
739
    public function getCompatLayer(Controller $controller)
740
    {
741
        if (is_subclass_of($controller, \SilverStripe\Admin\LeftAndMain::class)) {
0 ignored issues
show
Bug introduced by
The type SilverStripe\Admin\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
742
            return new SilverstripeAdminCompat();
743
        }
744
        if (is_subclass_of($controller, \LeKoala\Admini\LeftAndMain::class)) {
0 ignored issues
show
Bug introduced by
The type LeKoala\Admini\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
745
            return new AdminiCompat();
746
        }
747
    }
748
749
    public function getAttributes()
750
    {
751
        $attrs = parent::getAttributes();
752
        unset($attrs['type']);
753
        unset($attrs['name']);
754
        unset($attrs['value']);
755
        return $attrs;
756
    }
757
758
    public function getOption(string $k)
759
    {
760
        return $this->options[$k] ?? null;
761
    }
762
763
    public function setOption(string $k, $v): self
764
    {
765
        $this->options[$k] = $v;
766
        return $this;
767
    }
768
769
    public function getRowHeight(): int
770
    {
771
        return $this->getOption('rowHeight');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getOption('rowHeight') could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
772
    }
773
774
    /**
775
     * Prevent row height automatic computation
776
     * @link https://tabulator.info/docs/5.5/layout#height-row
777
     */
778
    public function setRowHeight(int $v): self
779
    {
780
        $this->setOption('rowHeight', $v);
781
        return $this;
782
    }
783
784
    public function makeHeadersSticky(): self
785
    {
786
        // note: we could also use the "sticky" attribute on the custom element
787
        $this->addExtraClass("tabulator-sticky");
788
        return $this;
789
    }
790
791
    public function setRemoteSource(string $url, array $extraParams = [], bool $dataResponse = false): self
792
    {
793
        $this->setOption("ajaxURL", $url); //set url for ajax request
794
        $params = array_merge([
795
            'SecurityID' => SecurityToken::getSecurityID()
796
        ], $extraParams);
797
        $this->setOption("ajaxParams", $params);
798
        // Accept response where data is nested under the data key
799
        if ($dataResponse) {
800
            $this->setOption("ajaxResponse", ['__fn' => self::JS_DATA_AJAX_RESPONSE]);
801
        }
802
        return $this;
803
    }
804
805
    /**
806
     * @link http://www.tabulator.info/docs/5.5/page#remote
807
     * @param string $url
808
     * @param array $params
809
     * @param integer $pageSize
810
     * @param integer $initialPage
811
     */
812
    public function setRemotePagination(string $url, array $params = [], int $pageSize = 0, int $initialPage = 1): self
813
    {
814
        $this->setOption("pagination", true); //enable pagination
815
        $this->setOption("paginationMode", 'remote'); //enable remote pagination
816
        $this->setRemoteSource($url, $params);
817
        if (!$pageSize) {
818
            $pageSize = $this->pageSize;
819
        } else {
820
            $this->pageSize = $pageSize;
821
        }
822
        $this->setOption("paginationSize", $pageSize);
823
        $this->setOption("paginationInitialPage", $initialPage);
824
        $this->setOption("paginationCounter", 'rows'); // http://www.tabulator.info/docs/5.5/page#counter
825
        return $this;
826
    }
827
828
    public function wizardRemotePagination(int $pageSize = 0, int $initialPage = 1, array $params = []): self
829
    {
830
        $this->setRemotePagination($this->TempLink('load', false), $params, $pageSize, $initialPage);
831
        $this->setOption("sortMode", "remote"); // http://www.tabulator.info/docs/5.5/sort#ajax-sort
832
        $this->setOption("filterMode", "remote"); // http://www.tabulator.info/docs/5.5/filter#ajax-filter
833
        return $this;
834
    }
835
836
    public function setProgressiveLoad(string $url, array $params = [], int $pageSize = 0, int $initialPage = 1, string $mode = 'scroll', int $scrollMargin = 0): self
837
    {
838
        $this->setOption("ajaxURL", $url);
839
        if (!empty($params)) {
840
            $this->setOption("ajaxParams", $params);
841
        }
842
        $this->setOption("progressiveLoad", $mode);
843
        if ($scrollMargin > 0) {
844
            $this->setOption("progressiveLoadScrollMargin", $scrollMargin);
845
        }
846
        if (!$pageSize) {
847
            $pageSize = $this->pageSize;
848
        } else {
849
            $this->pageSize = $pageSize;
850
        }
851
        $this->setOption("paginationSize", $pageSize);
852
        $this->setOption("paginationInitialPage", $initialPage);
853
        $this->setOption("paginationCounter", 'rows'); // http://www.tabulator.info/docs/5.5/page#counter
854
        return $this;
855
    }
856
857
    public function wizardProgressiveLoad(int $pageSize = 0, int $initialPage = 1, string $mode = 'scroll', int $scrollMargin = 0, array $extraParams = []): self
858
    {
859
        $params = array_merge([
860
            'SecurityID' => SecurityToken::getSecurityID()
861
        ], $extraParams);
862
        $this->setProgressiveLoad($this->TempLink('load', false), $params, $pageSize, $initialPage, $mode, $scrollMargin);
863
        $this->setOption("sortMode", "remote"); // http://www.tabulator.info/docs/5.5/sort#ajax-sort
864
        $this->setOption("filterMode", "remote"); // http://www.tabulator.info/docs/5.5/filter#ajax-filter
865
        return $this;
866
    }
867
868
    /**
869
     * @link https://tabulator.info/docs/5.5/layout#responsive
870
     * @param boolean $startOpen
871
     * @param string $mode collapse|hide|flexCollapse
872
     * @return self
873
     */
874
    public function wizardResponsiveCollapse(bool $startOpen = false, string $mode = "collapse"): self
875
    {
876
        $this->setOption("responsiveLayout", $mode);
877
        $this->setOption("responsiveLayoutCollapseStartOpen", $startOpen);
878
        if ($mode != "hide") {
879
            $this->columns = array_merge([
880
                'ui_responsive_collapse' => [
881
                    "cssClass" => 'tabulator-cell-btn',
882
                    'formatter' => 'responsiveCollapse',
883
                    'headerSort' => false,
884
                    'width' => 40,
885
                ]
886
            ], $this->columns);
887
        }
888
        return $this;
889
    }
890
891
    public function wizardDataTree(bool $startExpanded = false, bool $filter = false, bool $sort = false, string $el = null): self
892
    {
893
        $this->setOption("dataTree", true);
894
        $this->setOption("dataTreeStartExpanded", $startExpanded);
895
        $this->setOption("dataTreeFilter", $filter);
896
        $this->setOption("dataTreeSort", $sort);
897
        if ($el) {
898
            $this->setOption("dataTreeElementColumn", $el);
899
        }
900
        return $this;
901
    }
902
903
    public function wizardSelectable(array $actions = []): self
904
    {
905
        $this->columns = array_merge([
906
            'ui_selectable' => [
907
                "hozAlign" => 'center',
908
                "cssClass" => 'tabulator-cell-btn tabulator-cell-selector',
909
                'formatter' => 'rowSelection',
910
                'titleFormatter' => 'rowSelection',
911
                'headerSort' => false,
912
                'width' => 40,
913
            ]
914
        ], $this->columns);
915
        $this->setBulkActions($actions);
916
        return $this;
917
    }
918
919
    public function wizardMoveable(string $callback = "SSTabulator.rowMoved", $field = "Sort"): self
920
    {
921
        $this->moveUrl = $this->TempLink("item/{ID}/ajaxMove", false);
922
        $this->setOption("movableRows", true);
923
        $this->addListener("rowMoved", $callback);
924
        $this->columns = array_merge([
925
            'ui_move' => [
926
                "hozAlign" => 'center',
927
                "cssClass" => 'tabulator-cell-btn tabulator-cell-selector',
928
                'rowHandle' => true,
929
                'formatter' => 'handle',
930
                'headerSort' => false,
931
                'frozen' => true,
932
                'width' => 40,
933
            ],
934
            // We need a hidden sort column
935
            'ui_sort' => [
936
                "field" => $field,
937
                'visible' => false,
938
            ],
939
        ], $this->columns);
940
        return $this;
941
    }
942
943
    /**
944
     * @param string $field
945
     * @param string $toggleElement arrow|header|false (header by default)
946
     * @param boolean $isBool
947
     * @return void
948
     */
949
    public function wizardGroupBy(string $field, string $toggleElement = 'header', bool $isBool = false)
950
    {
951
        $this->setOption("groupBy", $field);
952
        $this->setOption("groupToggleElement", $toggleElement);
953
        if ($isBool) {
954
            $this->setOption("groupHeader", ['_fn' => self::JS_BOOL_GROUP_HEADER]);
955
        }
956
    }
957
958
    /**
959
     * @param HTTPRequest $request
960
     * @return HTTPResponse
961
     */
962
    public function handleItem($request)
963
    {
964
        // Our getController could either give us a true Controller, if this is the top-level GridField.
965
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
966
        $requestHandler = $this->getForm()->getController();
967
        $record = $this->getRecordFromRequest($request);
968
        if (!$record) {
969
            return $requestHandler->httpError(404, 'That record was not found');
970
        }
971
        $handler = $this->getItemRequestHandler($record, $requestHandler);
972
        return $handler->handleRequest($request);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $handler->handleRequest($request) also could return the type SilverStripe\Control\RequestHandler|array|string which is incompatible with the documented return type SilverStripe\Control\HTTPResponse.
Loading history...
973
    }
974
975
    /**
976
     * @param HTTPRequest $request
977
     * @return HTTPResponse
978
     */
979
    public function handleTool($request)
980
    {
981
        // Our getController could either give us a true Controller, if this is the top-level GridField.
982
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
983
        $requestHandler = $this->getForm()->getController();
984
        $tool = $this->getToolFromRequest($request);
985
        if (!$tool) {
986
            return $requestHandler->httpError(404, 'That tool was not found');
987
        }
988
        return $tool->handleRequest($request);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $tool->handleRequest($request) also could return the type SilverStripe\Control\RequestHandler|array|string which is incompatible with the documented return type SilverStripe\Control\HTTPResponse.
Loading history...
989
    }
990
991
    /**
992
     * @param HTTPRequest $request
993
     * @return HTTPResponse
994
     */
995
    public function handleBulkAction($request)
996
    {
997
        // Our getController could either give us a true Controller, if this is the top-level GridField.
998
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
999
        $requestHandler = $this->getForm()->getController();
1000
        $bulkAction = $this->getBulkActionFromRequest($request);
1001
        if (!$bulkAction) {
1002
            return $requestHandler->httpError(404, 'That bulk action was not found');
1003
        }
1004
        return $bulkAction->handleRequest($request);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $bulkAction->handleRequest($request) also could return the type SilverStripe\Control\RequestHandler|array|string which is incompatible with the documented return type SilverStripe\Control\HTTPResponse.
Loading history...
1005
    }
1006
1007
    /**
1008
     * @return string name of {@see TabulatorGrid_ItemRequest} subclass
1009
     */
1010
    public function getItemRequestClass(): string
1011
    {
1012
        if ($this->itemRequestClass) {
1013
            return $this->itemRequestClass;
1014
        } elseif (ClassInfo::exists(static::class . '_ItemRequest')) {
1015
            return static::class . '_ItemRequest';
1016
        }
1017
        return TabulatorGrid_ItemRequest::class;
1018
    }
1019
1020
    /**
1021
     * Build a request handler for the given record
1022
     *
1023
     * @param DataObject $record
1024
     * @param RequestHandler $requestHandler
1025
     * @return TabulatorGrid_ItemRequest
1026
     */
1027
    protected function getItemRequestHandler($record, $requestHandler)
1028
    {
1029
        $class = $this->getItemRequestClass();
1030
        $assignedClass = $this->itemRequestClass;
1031
        $this->extend('updateItemRequestClass', $class, $record, $requestHandler, $assignedClass);
1032
        /** @var TabulatorGrid_ItemRequest $handler */
1033
        $handler = Injector::inst()->createWithArgs(
1034
            $class,
1035
            [$this, $record, $requestHandler]
1036
        );
1037
        if ($template = $this->getTemplate()) {
1038
            $handler->setTemplate($template);
1039
        }
1040
        $this->extend('updateItemRequestHandler', $handler);
1041
        return $handler;
1042
    }
1043
1044
    public function getStateKey()
1045
    {
1046
        $nested = [];
1047
        $form = $this->getForm();
1048
        $scope = $this->modelClass ? str_replace('_', '\\', $this->modelClass) :  "default";
1049
        if ($form) {
0 ignored issues
show
introduced by
$form is of type SilverStripe\Forms\Form, thus it always evaluated to true.
Loading history...
1050
            $controller = $form->getController();
1051
1052
            // We are in a nested form, track by id since each records needs it own state
1053
            while ($controller instanceof TabulatorGrid_ItemRequest) {
1054
                $record = $controller->getRecord();
1055
                $nested[str_replace('_', '\\', get_class($record))] = $record->ID;
1056
1057
                // Move to parent controller
1058
                $controller = $controller->getController();
1059
            }
1060
1061
            // Scope by top controller class
1062
            $scope = str_replace('_', '\\', get_class($controller));
1063
        }
1064
1065
        $prefix = "TabulatorState";
1066
        $name = $this->getName();
1067
        $key = "$prefix.$scope.$name";
1068
        foreach ($nested as $k => $v) {
1069
            $key .= "$k.$v";
1070
        }
1071
        return $key;
1072
    }
1073
1074
    /**
1075
     * @param HTTPRequest|null $request
1076
     * @return array{'page': int, 'limit': int, 'sort': array, 'filter': array}
1077
     */
1078
    public function getState(HTTPRequest $request = null)
1079
    {
1080
        if ($request === null) {
1081
            $request = Controller::curr()->getRequest();
1082
        }
1083
        $stateKey = $this->getStateKey();
1084
        $state = $request->getSession()->get($stateKey);
1085
        return $state ?? [
1086
            'page' => 1,
1087
            'limit' => $this->pageSize,
1088
            'sort' => [],
1089
            'filter' => [],
1090
        ];
1091
    }
1092
1093
    public function setState(HTTPRequest $request, $state)
1094
    {
1095
        $stateKey = $this->getStateKey();
1096
        $request->getSession()->set($stateKey, $state);
1097
        // If we are in a new controller, we can clear other states
1098
        $matches = [];
1099
        preg_match_all('/\.(.*?)\./', $stateKey, $matches);
1100
        $scope = $matches[1][0] ?? null;
1101
        if ($scope) {
1102
            self::clearAllStates($scope);
1103
        }
1104
    }
1105
1106
    public function clearState(HTTPRequest $request)
1107
    {
1108
        $stateKey = $this->getStateKey();
1109
        $request->getSession()->clear($stateKey);
1110
    }
1111
1112
    public static function clearAllStates(string $exceptScope = null)
1113
    {
1114
        $request = Controller::curr()->getRequest();
1115
        $allStates = $request->getSession()->get('TabulatorState');
1116
        if (!$allStates) {
1117
            return;
1118
        }
1119
        foreach ($allStates as $scope => $data) {
1120
            if ($exceptScope && $scope == $exceptScope) {
1121
                continue;
1122
            }
1123
            $request->getSession()->clear("TabulatorState.$scope");
1124
        }
1125
    }
1126
1127
    public function StateValue($key, $field): ?string
1128
    {
1129
        $state = $this->getState();
1130
        $arr = $state[$key] ?? [];
1131
        foreach ($arr as $s) {
1132
            if ($s['field'] === $field) {
1133
                return $s['value'];
1134
            }
1135
        }
1136
        return null;
1137
    }
1138
1139
    /**
1140
     * Provides autocomplete lists
1141
     *
1142
     * @param HTTPRequest $request
1143
     * @return HTTPResponse
1144
     */
1145
    public function autocomplete(HTTPRequest $request)
1146
    {
1147
        if ($this->isDisabled() || $this->isReadonly()) {
1148
            return $this->httpError(403);
1149
        }
1150
        $SecurityID = $request->getVar('SecurityID');
1151
        if (!SecurityToken::inst()->check($SecurityID)) {
1152
            return $this->httpError(404, "Invalid SecurityID");
1153
        }
1154
1155
        $name = $request->getVar("Column");
1156
        $col = $this->getColumn($name);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $key of LeKoala\Tabulator\TabulatorGrid::getColumn() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1156
        $col = $this->getColumn(/** @scrutinizer ignore-type */ $name);
Loading history...
1157
        if (!$col) {
1158
            return $this->httpError(403, "Invalid column");
1159
        }
1160
1161
        // Don't use % term as it prevents use of indexes
1162
        $term = $request->getVar('term') . '%';
1163
        $term = str_replace(' ', '%', $term);
1164
1165
        $parts = explode(".", $name);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1165
        $parts = explode(".", /** @scrutinizer ignore-type */ $name);
Loading history...
1166
        if (count($parts) > 2) {
1167
            array_pop($parts);
1168
        }
1169
        if (count($parts) == 2) {
1170
            $class = $parts[0];
1171
            $field = $parts[1];
1172
        } elseif (count($parts) == 1) {
1173
            $class = preg_replace("/ID$/", "", $parts[0]);
1174
            $field = 'Title';
1175
        } else {
1176
            return $this->httpError(403, "Invalid field");
1177
        }
1178
1179
        /** @var DataObject $sng */
1180
        $sng = $class::singleton();
1181
        $baseTable = $sng->baseTable();
1182
1183
        $searchField = null;
1184
        $searchCandidates = [
1185
            $field, 'Name', 'Surname', 'Email', 'ID'
1186
        ];
1187
1188
        // Ensure field exists, this is really rudimentary
1189
        $db = $class::config()->db;
1190
        foreach ($searchCandidates as $searchCandidate) {
1191
            if ($searchField) {
1192
                continue;
1193
            }
1194
            if (isset($db[$searchCandidate])) {
1195
                $searchField = $searchCandidate;
1196
            }
1197
        }
1198
        $searchCols = [$searchField];
1199
1200
        // For members, do something better
1201
        if ($baseTable == 'Member') {
1202
            $searchField = ['FirstName', 'Surname'];
1203
            $searchCols = ['FirstName', 'Surname', 'Email'];
1204
        }
1205
1206
        if (!empty($col['editorParams']['customSearchField'])) {
1207
            $searchField = $col['editorParams']['customSearchField'];
1208
        }
1209
        if (!empty($col['editorParams']['customSearchCols'])) {
1210
            $searchCols = $col['editorParams']['customSearchCols'];
1211
        }
1212
1213
1214
        /** @var DataList $list */
1215
        $list = $sng::get();
1216
1217
        // Make sure at least one field is not null...
1218
        $where = [];
1219
        foreach ($searchCols as $searchCol) {
1220
            $where[] = $searchCol . ' IS NOT NULL';
1221
        }
1222
        $list = $list->where($where);
1223
        // ... and matches search term ...
1224
        $where = [];
1225
        foreach ($searchCols as $searchCol) {
1226
            $where[$searchCol . ' LIKE ?'] = $term;
1227
        }
1228
        $list = $list->whereAny($where);
1229
1230
        // ... and any user set requirements
1231
        if (!empty($col['editorParams']['where'])) {
1232
            // Deal with in clause
1233
            $customWhere = [];
1234
            foreach ($col['editorParams']['where'] as $col => $param) {
1235
                // For array, we need a IN statement with a ? for each value
1236
                if (is_array($param)) {
1237
                    $prepValue = [];
1238
                    $params = [];
1239
                    foreach ($param as $paramValue) {
1240
                        $params[] = $paramValue;
1241
                        $prepValue[] = "?";
1242
                    }
1243
                    $customWhere["$col IN (" . implode(',', $prepValue) . ")"] = $params;
1244
                } else {
1245
                    $customWhere["$col = ?"] = $param;
1246
                }
1247
            }
1248
            $list = $list->where($customWhere);
1249
        }
1250
1251
        $results = iterator_to_array($list);
1252
        $data = [];
1253
        foreach ($results as $record) {
1254
            if (is_array($searchField)) {
1255
                $labelParts = [];
1256
                foreach ($searchField as $sf) {
1257
                    $labelParts[] = $record->$sf;
1258
                }
1259
                $label = implode(" ", $labelParts);
1260
            } else {
1261
                $label = $record->$searchField;
1262
            }
1263
            $data[] = [
1264
                'value' => $record->ID,
1265
                'label' => $label,
1266
            ];
1267
        }
1268
1269
        $json = json_encode($data);
1270
        $response = new HTTPResponse($json);
1271
        $response->addHeader('Content-Type', 'application/script');
1272
        return $response;
1273
    }
1274
1275
    /**
1276
     * @link http://www.tabulator.info/docs/5.5/page#remote-response
1277
     * @param HTTPRequest $request
1278
     * @return HTTPResponse
1279
     */
1280
    public function load(HTTPRequest $request)
1281
    {
1282
        if ($this->isDisabled() || $this->isReadonly()) {
1283
            return $this->httpError(403);
1284
        }
1285
        $SecurityID = $request->getVar('SecurityID');
1286
        if (!SecurityToken::inst()->check($SecurityID)) {
1287
            return $this->httpError(404, "Invalid SecurityID");
1288
        }
1289
1290
        $page = (int) $request->getVar('page');
1291
        $limit = (int) $request->getVar('size');
1292
1293
        $sort = $request->getVar('sort');
1294
        $filter = $request->getVar('filter');
1295
1296
        // Persist state to allow the ItemEditForm to display navigation
1297
        $state = [
1298
            'page' => $page,
1299
            'limit' => $limit,
1300
            'sort' => $sort,
1301
            'filter' => $filter,
1302
        ];
1303
        $this->setState($request, $state);
1304
1305
        $offset = ($page - 1) * $limit;
1306
        $data = $this->getManipulatedData($limit, $offset, $sort, $filter);
1307
        $data['state'] = $state;
1308
1309
        $encodedData = json_encode($data);
1310
        if (!$encodedData) {
1311
            throw new Exception(json_last_error_msg());
1312
        }
1313
1314
        $response = new HTTPResponse($encodedData);
1315
        $response->addHeader('Content-Type', 'application/json');
1316
        return $response;
1317
    }
1318
1319
    /**
1320
     * @param HTTPRequest $request
1321
     * @return DataObject|null
1322
     */
1323
    protected function getRecordFromRequest(HTTPRequest $request): ?DataObject
1324
    {
1325
        /** @var DataObject $record */
1326
        if (is_numeric($request->param('ID'))) {
1327
            /** @var Filterable $dataList */
1328
            $dataList = $this->getList();
1329
            $record = $dataList->byID($request->param('ID'));
1330
        } else {
1331
            $record = Injector::inst()->create($this->getModelClass());
1332
        }
1333
        return $record;
1334
    }
1335
1336
    /**
1337
     * @param HTTPRequest $request
1338
     * @return AbstractTabulatorTool|null
1339
     */
1340
    protected function getToolFromRequest(HTTPRequest $request): ?AbstractTabulatorTool
1341
    {
1342
        $toolID = $request->param('ID');
1343
        $tool = $this->getTool($toolID);
1344
        return $tool;
1345
    }
1346
1347
    /**
1348
     * @param HTTPRequest $request
1349
     * @return AbstractBulkAction|null
1350
     */
1351
    protected function getBulkActionFromRequest(HTTPRequest $request): ?AbstractBulkAction
1352
    {
1353
        $toolID = $request->param('ID');
1354
        $tool = $this->getBulkAction($toolID);
1355
        return $tool;
1356
    }
1357
1358
    /**
1359
     * Get the value of a named field  on the given record.
1360
     *
1361
     * Use of this method ensures that any special rules around the data for this gridfield are
1362
     * followed.
1363
     *
1364
     * @param DataObject $record
1365
     * @param string $fieldName
1366
     *
1367
     * @return mixed
1368
     */
1369
    public function getDataFieldValue($record, $fieldName)
1370
    {
1371
        if ($record->hasMethod('relField')) {
1372
            return $record->relField($fieldName);
1373
        }
1374
1375
        if ($record->hasMethod($fieldName)) {
1376
            return $record->$fieldName();
1377
        }
1378
1379
        return $record->$fieldName;
1380
    }
1381
1382
    public function getManipulatedList(): SS_List
1383
    {
1384
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list could return the type null which is incompatible with the type-hinted return SilverStripe\ORM\SS_List. Consider adding an additional type-check to rule them out.
Loading history...
1385
    }
1386
1387
    public function getList(): SS_List
1388
    {
1389
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list could return the type null which is incompatible with the type-hinted return SilverStripe\ORM\SS_List. Consider adding an additional type-check to rule them out.
Loading history...
1390
    }
1391
1392
    public function setList(SS_List $list): self
1393
    {
1394
        if ($this->autoloadDataList && $list instanceof DataList) {
1395
            $this->wizardRemotePagination();
1396
        }
1397
        $this->list = $list;
1398
        return $this;
1399
    }
1400
1401
    public function hasArrayList(): bool
1402
    {
1403
        return $this->list instanceof ArrayList;
1404
    }
1405
1406
    public function getArrayList(): ArrayList
1407
    {
1408
        if (!$this->list instanceof ArrayList) {
1409
            throw new RuntimeException("Value is not a ArrayList, it is a: " . get_class($this->list));
0 ignored issues
show
Bug introduced by
It seems like $this->list can also be of type null; however, parameter $object of get_class() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1409
            throw new RuntimeException("Value is not a ArrayList, it is a: " . get_class(/** @scrutinizer ignore-type */ $this->list));
Loading history...
1410
        }
1411
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list returns the type null which is incompatible with the type-hinted return SilverStripe\ORM\ArrayList.
Loading history...
1412
    }
1413
1414
    public function hasDataList(): bool
1415
    {
1416
        return $this->list instanceof DataList;
1417
    }
1418
1419
    /**
1420
     * A properly typed on which you can call byID
1421
     * @return ArrayList|DataList
1422
     */
1423
    public function getByIDList()
1424
    {
1425
        return $this->list;
1426
    }
1427
1428
    public function hasByIDList(): bool
1429
    {
1430
        return $this->hasDataList() || $this->hasArrayList();
1431
    }
1432
1433
    public function getDataList(): DataList
1434
    {
1435
        if (!$this->list instanceof DataList) {
1436
            throw new RuntimeException("Value is not a DataList, it is a: " . get_class($this->list));
0 ignored issues
show
Bug introduced by
It seems like $this->list can also be of type null; however, parameter $object of get_class() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1436
            throw new RuntimeException("Value is not a DataList, it is a: " . get_class(/** @scrutinizer ignore-type */ $this->list));
Loading history...
1437
        }
1438
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list returns the type null which is incompatible with the type-hinted return SilverStripe\ORM\DataList.
Loading history...
1439
    }
1440
1441
    public function getManipulatedData(int $limit, int $offset, array $sort = null, array $filter = null): array
1442
    {
1443
        if (!$this->hasDataList()) {
1444
            $data = $this->list->toNestedArray();
0 ignored issues
show
Bug introduced by
The method toNestedArray() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1444
            /** @scrutinizer ignore-call */ 
1445
            $data = $this->list->toNestedArray();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1445
1446
            $lastRow = $this->list->count();
1447
            $lastPage = ceil($lastRow / $limit);
1448
1449
            $result = [
1450
                'last_row' => $lastRow,
1451
                'last_page' => $lastPage,
1452
                'data' => $data,
1453
            ];
1454
1455
            return $result;
1456
        }
1457
1458
        $dataList = $this->getDataList();
1459
1460
        $schema = DataObject::getSchema();
1461
        $dataClass = $dataList->dataClass();
1462
        /** @var DataObject $singleton */
1463
        $singleton = singleton($dataClass);
1464
        $resolutionMap = [];
1465
1466
        $sortSql = [];
1467
        if ($sort) {
1468
            foreach ($sort as $sortValues) {
1469
                $cols = array_keys($this->columns);
1470
                $field = $sortValues['field'];
1471
                if (!in_array($field, $cols)) {
1472
                    throw new Exception("Invalid sort field: $field");
1473
                }
1474
                $dir = $sortValues['dir'];
1475
                if (!in_array($dir, ['asc', 'desc'])) {
1476
                    throw new Exception("Invalid sort dir: $dir");
1477
                }
1478
1479
                // Nested sort
1480
                if (strpos($field, '.') !== false) {
1481
                    $parts = explode(".", $field);
1482
1483
                    // Resolve relation only once in case of multiples similar keys
1484
                    if (!isset($resolutionMap[$parts[0]])) {
1485
                        $resolutionMap[$parts[0]] = $singleton->relObject($parts[0]);
1486
                    }
1487
                    // Not matching anything (maybe a formatting .Nice ?)
1488
                    if (!$resolutionMap[$parts[0]] || !($resolutionMap[$parts[0]] instanceof DataList)) {
1489
                        $field = $parts[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $field is dead and can be removed.
Loading history...
1490
                        continue;
1491
                    }
1492
                    $relatedObject = get_class($resolutionMap[$parts[0]]);
1493
                    $tableName = $schema->tableForField($relatedObject, $parts[1]);
1494
                    $baseIDColumn = $schema->sqlColumnForField($dataClass, 'ID');
1495
                    $tableAlias = $parts[0];
1496
                    $dataList = $dataList->leftJoin($tableName, "\"{$tableAlias}\".\"ID\" = {$baseIDColumn}", $tableAlias);
1497
                }
1498
1499
                $sortSql[] = $field . ' ' . $dir;
1500
            }
1501
        } else {
1502
            // If we have a sort column
1503
            if (isset($this->columns['ui_sort'])) {
1504
                $sortSql[] = $this->columns['ui_sort']['field'] . ' ASC';
1505
            }
1506
        }
1507
        if (!empty($sortSql)) {
1508
            $dataList = $dataList->sort(implode(", ", $sortSql));
1509
        }
1510
1511
        // Filtering is an array of field/type/value arrays
1512
        $where = [];
1513
        $anyWhere = [];
1514
        if ($filter) {
1515
            foreach ($filter as $filterValues) {
1516
                $cols = array_keys($this->columns);
1517
                $field = $filterValues['field'];
1518
                if (strpos($field, '__') !== 0 && !in_array($field, $cols)) {
1519
                    throw new Exception("Invalid filter field: $field");
1520
                }
1521
                $value = $filterValues['value'];
1522
                $type = $filterValues['type'];
1523
1524
                $rawValue = $value;
1525
1526
                // Strict value
1527
                if ($value === "true") {
1528
                    $value = true;
1529
                } elseif ($value === "false") {
1530
                    $value = false;
1531
                }
1532
1533
                switch ($type) {
1534
                    case "=":
1535
                        // It's a wildcard search
1536
                        if ($field === "__wildcard") {
1537
                            $anyWhere = $this->createWildcardFilters($rawValue);
1538
                        } elseif ($field === "__quickfilter") {
1539
                            $this->createQuickFilter($rawValue, $dataList);
1540
                        } else {
1541
                            $where["$field"] = $value;
1542
                        }
1543
                        break;
1544
                    case "!=":
1545
                        $where["$field:not"] = $value;
1546
                        break;
1547
                    case "like":
1548
                        $where["$field:PartialMatch:nocase"] = $value;
1549
                        break;
1550
                    case "keywords":
1551
                        $where["$field:PartialMatch:nocase"] = str_replace(" ", "%", $value);
1552
                        break;
1553
                    case "starts":
1554
                        $where["$field:StartsWith:nocase"] = $value;
1555
                        break;
1556
                    case "ends":
1557
                        $where["$field:EndsWith:nocase"] = $value;
1558
                        break;
1559
                    case "<":
1560
                        $where["$field:LessThan:nocase"] = $value;
1561
                        break;
1562
                    case "<=":
1563
                        $where["$field:LessThanOrEqual:nocase"] = $value;
1564
                        break;
1565
                    case ">":
1566
                        $where["$field:GreaterThan:nocase"] = $value;
1567
                        break;
1568
                    case ">=":
1569
                        $where["$field:GreaterThanOrEqual:nocase"] = $value;
1570
                        break;
1571
                    case "in":
1572
                        $where["$field"] = $value;
1573
                        break;
1574
                    case "regex":
1575
                        $dataList = $dataList->where('REGEXP ' . Convert::raw2sql($value));
1576
                        break;
1577
                    default:
1578
                        throw new Exception("Invalid sort dir: $dir");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dir does not seem to be defined for all execution paths leading up to this point.
Loading history...
1579
                }
1580
            }
1581
        }
1582
        if (!empty($where)) {
1583
            $dataList = $dataList->filter($where);
1584
        }
1585
        if (!empty($anyWhere)) {
1586
            $dataList = $dataList->filterAny($anyWhere);
1587
        }
1588
1589
        $lastRow = $dataList->count();
1590
        $lastPage = ceil($lastRow / $limit);
1591
1592
        $data = [];
1593
        /** @var DataObject $record */
1594
        foreach ($dataList->limit($limit, $offset) as $record) {
1595
            if ($record->hasMethod('canView') && !$record->canView()) {
1596
                continue;
1597
            }
1598
1599
            $item = [
1600
                'ID' => $record->ID,
1601
            ];
1602
1603
            // Add row class
1604
            if ($record->hasMethod('TabulatorRowClass')) {
1605
                $item['_class'] = $record->TabulatorRowClass();
1606
            } elseif ($record->hasMethod('getRowClass')) {
1607
                $item['_class'] = $record->getRowClass();
1608
            }
1609
            // Add row color
1610
            if ($record->hasMethod('TabulatorRowColor')) {
1611
                $item['_color'] = $record->TabulatorRowColor();
1612
            }
1613
1614
            $nested = [];
1615
            foreach ($this->columns as $col) {
1616
                if (empty($col['field'])) {
1617
                    continue;
1618
                }
1619
                $field = $col['field'];
1620
                if (strpos($field, '.') !== false) {
1621
                    $parts = explode('.', $field);
1622
                    $classOrField = $parts[0];
1623
                    $relationOrMethod = $parts[1];
1624
                    // For relations, like Users.count
1625
                    if ($singleton->getRelationClass($classOrField)) {
1626
                        $nested[$classOrField][] = $relationOrMethod;
1627
                        continue;
1628
                    } else {
1629
                        // For fields, like SomeValue.Nice
1630
                        $dbObject = $record->dbObject($classOrField);
1631
                        if ($dbObject) {
1632
                            $item[$classOrField] = [
1633
                                $relationOrMethod => $dbObject->$relationOrMethod()
1634
                            ];
1635
                            continue;
1636
                        }
1637
                    }
1638
                }
1639
                if (!isset($item[$field])) {
1640
                    if ($record->hasMethod($field)) {
1641
                        $item[$field] = $record->$field();
1642
                    } else {
1643
                        $item[$field] = $record->getField($field);
1644
                    }
1645
                }
1646
            }
1647
            // Fill in nested data, like Users.count
1648
            foreach ($nested as $nestedClass => $nestedColumns) {
1649
                /** @var DataObject $relObject */
1650
                $relObject = $record->relObject($nestedClass);
1651
                $nestedData = [];
1652
                foreach ($nestedColumns as $nestedColumn) {
1653
                    $nestedData[$nestedColumn] = $this->getDataFieldValue($relObject, $nestedColumn);
1654
                }
1655
                $item[$nestedClass] = $nestedData;
1656
            }
1657
            $data[] = $item;
1658
        }
1659
1660
        $result = [
1661
            'last_row' => $lastRow,
1662
            'last_page' => $lastPage,
1663
            'data' => $data,
1664
        ];
1665
1666
        if (Director::isDev()) {
1667
            $result['sql'] = $dataList->sql();
1668
        }
1669
1670
        return $result;
1671
    }
1672
1673
    public function QuickFiltersList()
1674
    {
1675
        $current = $this->StateValue('filter', '__quickfilter');
1676
        $list = new ArrayList();
1677
        foreach ($this->quickFilters as $k => $v) {
1678
            $list->push([
1679
                'Value' => $k,
1680
                'Label' => $v['label'],
1681
                'Selected' => $k == $current
1682
            ]);
1683
        }
1684
        return $list;
1685
    }
1686
1687
    protected function createQuickFilter($filter, &$list)
1688
    {
1689
        $qf = $this->quickFilters[$filter] ?? null;
1690
        if (!$qf) {
1691
            return;
1692
        }
1693
1694
        $callback = $qf['callback'] ?? null;
1695
        if (!$callback) {
1696
            return;
1697
        }
1698
1699
        $callback($list);
1700
    }
1701
1702
    protected function createWildcardFilters(string $value)
1703
    {
1704
        $wildcardFields = $this->wildcardFields;
1705
1706
        // Create from model
1707
        if (empty($wildcardFields)) {
1708
            /** @var DataObject $singl */
1709
            $singl = singleton($this->modelClass);
1710
            $searchableFields = $singl->searchableFields();
1711
1712
            foreach ($searchableFields as $k => $v) {
1713
                $general = $v['general'] ?? true;
1714
                if (!$general) {
1715
                    continue;
1716
                }
1717
                $wildcardFields[] = $k;
1718
            }
1719
        }
1720
1721
        // Queries can have the format s:... or e:... or =:.... or %:....
1722
        $filter = $this->defaultFilter;
1723
        if (strpos($value, ':') === 1) {
1724
            $parts = explode(":", $value);
1725
            $shortcut = array_shift($parts);
1726
            $value = implode(":", $parts);
1727
            switch ($shortcut) {
1728
                case 's':
1729
                    $filter = 'StartsWith';
1730
                    break;
1731
                case 'e':
1732
                    $filter = 'EndsWith';
1733
                    break;
1734
                case '=':
1735
                    $filter = 'ExactMatch';
1736
                    break;
1737
                case '%':
1738
                    $filter = 'PartialMatch';
1739
                    break;
1740
            }
1741
        }
1742
1743
        // Process value
1744
        $baseValue = $value;
1745
        $value = str_replace(" ", "%", $value);
1746
        $value = str_replace(['.', '_', '-'], ' ', $value);
1747
1748
        // Create filters
1749
        $anyWhere = [];
1750
        foreach ($wildcardFields as $f) {
1751
            if (!$value) {
1752
                continue;
1753
            }
1754
            $key = $f . ":" . $filter;
1755
            $anyWhere[$key] = $value;
1756
1757
            // also look on unfiltered data
1758
            if ($value != $baseValue) {
1759
                $anyWhere[$key] = $baseValue;
1760
            }
1761
        }
1762
1763
        return $anyWhere;
1764
    }
1765
1766
    public function getModelClass(): ?string
1767
    {
1768
        if ($this->modelClass) {
1769
            return $this->modelClass;
1770
        }
1771
        if ($this->list && $this->list instanceof DataList) {
1772
            return $this->list->dataClass();
1773
        }
1774
        return null;
1775
    }
1776
1777
    public function setModelClass(string $modelClass): self
1778
    {
1779
        $this->modelClass = $modelClass;
1780
        return $this;
1781
    }
1782
1783
1784
    public function getDataAttribute(string $k)
1785
    {
1786
        if (isset($this->dataAttributes[$k])) {
1787
            return $this->dataAttributes[$k];
1788
        }
1789
        return $this->getAttribute("data-$k");
1790
    }
1791
1792
    public function setDataAttribute(string $k, $v): self
1793
    {
1794
        $this->dataAttributes[$k] = $v;
1795
        return $this;
1796
    }
1797
1798
    public function dataAttributesHTML(): string
1799
    {
1800
        $parts = [];
1801
        foreach ($this->dataAttributes as $k => $v) {
1802
            if (!$v) {
1803
                continue;
1804
            }
1805
            if (is_array($v)) {
1806
                $v = json_encode($v);
1807
            }
1808
            $parts[] = "data-$k='$v'";
1809
        }
1810
        return implode(" ", $parts);
1811
    }
1812
1813
    protected function processLink(string $url): string
1814
    {
1815
        // It's not necessary to process
1816
        if ($url == '#') {
1817
            return $url;
1818
        }
1819
        // It's a temporary link on the form
1820
        if (strpos($url, 'form:') === 0) {
1821
            return $this->Link(preg_replace('/^form:/', '', $url));
1822
        }
1823
        // It's a temporary link on the controller
1824
        if (strpos($url, 'controller:') === 0) {
1825
            return $this->ControllerLink(preg_replace('/^controller:/', '', $url));
1826
        }
1827
        // It's a custom protocol (mailto: etc)
1828
        if (strpos($url, ':') !== false) {
1829
            return $url;
1830
        }
1831
        return $url;
1832
    }
1833
1834
    protected function processLinks(): void
1835
    {
1836
        // Process editor and formatter links
1837
        foreach ($this->columns as $name => $params) {
1838
            if (!empty($params['formatterParams']['url'])) {
1839
                $url = $this->processLink($params['formatterParams']['url']);
1840
                $this->columns[$name]['formatterParams']['url'] = $url;
1841
            }
1842
            if (!empty($params['editorParams']['url'])) {
1843
                $url = $this->processLink($params['editorParams']['url']);
1844
                $this->columns[$name]['editorParams']['url'] = $url;
1845
            }
1846
            // Set valuesURL automatically if not already set
1847
            if (!empty($params['editorParams']['autocomplete'])) {
1848
                if (empty($params['editorParams']['valuesURL'])) {
1849
                    $params = [
1850
                        'Column' => $name,
1851
                        'SecurityID' => SecurityToken::getSecurityID(),
1852
                    ];
1853
                    $url = $this->Link('autocomplete') . '?' . http_build_query($params);
1854
                    $this->columns[$name]['editorParams']['valuesURL'] = $url;
1855
                    $this->columns[$name]['editorParams']['filterRemote'] = true;
1856
                }
1857
            }
1858
        }
1859
1860
        // Other links
1861
        $url = $this->getOption('ajaxURL');
1862
        if ($url) {
1863
            $this->setOption('ajaxURL', $this->processLink($url));
1864
        }
1865
    }
1866
1867
    public function makeButton(string $urlOrAction, string $icon, string $title): array
1868
    {
1869
        $opts = [
1870
            "responsive" => 0,
1871
            "cssClass" => 'tabulator-cell-btn',
1872
            "tooltip" => $title,
1873
            "formatter" => "button",
1874
            "formatterParams" => [
1875
                "icon" => $icon,
1876
                "title" => $title,
1877
                "url" => $this->TempLink($urlOrAction), // On the controller by default
1878
            ],
1879
            "cellClick" => ["__fn" => "SSTabulator.buttonHandler"],
1880
            "width" => 70,
1881
            "hozAlign" => "center",
1882
            "headerSort" => false,
1883
        ];
1884
        return $opts;
1885
    }
1886
1887
    public function addButtonFromArray(string $action, array $opts = [], string $before = null): self
1888
    {
1889
        // Insert before given column
1890
        if ($before) {
1891
            if (array_key_exists($before, $this->columns)) {
1892
                $new = [];
1893
                foreach ($this->columns as $k => $value) {
1894
                    if ($k === $before) {
1895
                        $new["action_$action"] = $opts;
1896
                    }
1897
                    $new[$k] = $value;
1898
                }
1899
                $this->columns = $new;
1900
            }
1901
        } else {
1902
            $this->columns["action_$action"] = $opts;
1903
        }
1904
        return $this;
1905
    }
1906
1907
    /**
1908
     * @param string $action Action name
1909
     * @param string $url Parameters between {} will be interpolated by row values.
1910
     * @param string $icon
1911
     * @param string $title
1912
     * @param string|null $before
1913
     * @return self
1914
     */
1915
    public function addButton(string $action, string $url, string $icon, string $title, string $before = null): self
1916
    {
1917
        $opts = $this->makeButton($url, $icon, $title);
1918
        $this->addButtonFromArray($action, $opts, $before);
1919
        return $this;
1920
    }
1921
1922
    public function shiftButton(string $action, string $url, string $icon, string $title): self
1923
    {
1924
        // Find first action
1925
        foreach ($this->columns as $name => $options) {
1926
            if (strpos($name, 'action_') === 0) {
1927
                return $this->addButton($action, $url, $icon, $title, $name);
1928
            }
1929
        }
1930
        return $this->addButton($action, $url, $icon, $title);
1931
    }
1932
1933
    public function removeButton(string $action): self
1934
    {
1935
        if (isset($this->columns["action_$action"])) {
1936
            unset($this->columns["action_$action"]);
1937
        }
1938
        return $this;
1939
    }
1940
1941
    /**
1942
     * @link http://www.tabulator.info/docs/5.5/columns#definition
1943
     * @param string $field (Required) this is the key for this column in the data array
1944
     * @param string $title (Required) This is the title that will be displayed in the header for this column
1945
     * @param array $opts Other options to merge in
1946
     * @return $this
1947
     */
1948
    public function addColumn(string $field, string $title = null, array $opts = []): self
1949
    {
1950
        if ($title === null) {
1951
            $title = $field;
1952
        }
1953
1954
        $baseOpts = [
1955
            "field" => $field,
1956
            "title" => $title,
1957
        ];
1958
1959
        if (!empty($opts)) {
1960
            $baseOpts = array_merge($baseOpts, $opts);
1961
        }
1962
1963
        $this->columns[$field] = $baseOpts;
1964
        return $this;
1965
    }
1966
1967
    /**
1968
     * @link http://www.tabulator.info/docs/5.5/columns#definition
1969
     * @param array $opts Other options to merge in
1970
     * @return $this
1971
     */
1972
    public function addColumnFromArray(array $opts = [])
1973
    {
1974
        if (empty($opts['field']) || !isset($opts['title'])) {
1975
            throw new Exception("Missing field or title key");
1976
        }
1977
        $field = $opts['field'];
1978
        $this->columns[$field] = $opts;
1979
        return $this;
1980
    }
1981
1982
    public function makeColumnEditable(string $field, string $editor = "input", array $params = [])
1983
    {
1984
        $col = $this->getColumn($field);
1985
        if (!$col) {
1986
            throw new InvalidArgumentException("$field is not a valid column");
1987
        }
1988
1989
        switch ($editor) {
1990
            case 'date':
1991
                $editor = "input";
1992
                $params = [
1993
                    'mask' => "9999-99-99",
1994
                    'maskAutoFill' => 'true',
1995
                ];
1996
                break;
1997
            case 'datetime':
1998
                $editor = "input";
1999
                $params = [
2000
                    'mask' => "9999-99-99 99:99:99",
2001
                    'maskAutoFill' => 'true',
2002
                ];
2003
                break;
2004
        }
2005
2006
        if (empty($col['cssClass'])) {
2007
            $col['cssClass'] = 'no-change-track';
2008
        } else {
2009
            $col['cssClass'] .= ' no-change-track';
2010
        }
2011
2012
        $col['editor'] = $editor;
2013
        $col['editorParams'] = $params;
2014
        if ($editor == "list") {
2015
            if (!empty($params['autocomplete'])) {
2016
                $col['headerFilter'] = "input"; // force input
2017
            } else {
2018
                $col['headerFilterParams'] = $params; // editor is used as base filter editor
2019
            }
2020
        }
2021
2022
2023
        $this->setColumn($field, $col);
2024
    }
2025
2026
    /**
2027
     * Get column details
2028
2029
     * @param string $key
2030
     */
2031
    public function getColumn(string $key): ?array
2032
    {
2033
        if (isset($this->columns[$key])) {
2034
            return $this->columns[$key];
2035
        }
2036
        return null;
2037
    }
2038
2039
    /**
2040
     * Set column details
2041
     *
2042
     * @param string $key
2043
     * @param array $col
2044
     */
2045
    public function setColumn(string $key, array $col): self
2046
    {
2047
        $this->columns[$key] = $col;
2048
        return $this;
2049
    }
2050
2051
    /**
2052
     * Update column details
2053
     *
2054
     * @param string $key
2055
     * @param array $col
2056
     */
2057
    public function updateColumn(string $key, array $col): self
2058
    {
2059
        $data = $this->getColumn($key);
2060
        if ($data) {
2061
            $this->setColumn($key, array_merge($data, $col));
2062
        }
2063
        return $this;
2064
    }
2065
2066
    /**
2067
     * Remove a column
2068
     *
2069
     * @param string $key
2070
     */
2071
    public function removeColumn(string $key): void
2072
    {
2073
        unset($this->columns[$key]);
2074
    }
2075
2076
2077
    /**
2078
     * Get the value of columns
2079
     */
2080
    public function getColumns(): array
2081
    {
2082
        return $this->columns;
2083
    }
2084
2085
    /**
2086
     * Set the value of columns
2087
     */
2088
    public function setColumns(array $columns): self
2089
    {
2090
        $this->columns = $columns;
2091
        return $this;
2092
    }
2093
2094
    /**
2095
     * @param string|AbstractTabulatorTool $tool Pass name or class
2096
     * @return AbstractTabulatorTool|null
2097
     */
2098
    public function getTool($tool): ?AbstractTabulatorTool
2099
    {
2100
        if (is_object($tool)) {
2101
            $tool = get_class($tool);
2102
        }
2103
        if (!is_string($tool)) {
0 ignored issues
show
introduced by
The condition is_string($tool) is always true.
Loading history...
2104
            throw new InvalidArgumentException('Tool must be an object or a class name');
2105
        }
2106
        foreach ($this->tools as $t) {
2107
            if ($t['name'] === $tool) {
2108
                return $t['tool'];
2109
            }
2110
            if ($t['tool'] instanceof $tool) {
2111
                return $t['tool'];
2112
            }
2113
        }
2114
        return null;
2115
    }
2116
2117
    public function addTool(string $pos, AbstractTabulatorTool $tool, string $name = ''): self
2118
    {
2119
        $tool->setTabulatorGrid($this);
2120
        $tool->setName($name);
2121
2122
        $this->tools[] = [
2123
            'position' => $pos,
2124
            'tool' => $tool,
2125
            'name' => $name,
2126
        ];
2127
        return $this;
2128
    }
2129
2130
    public function removeTool($tool): self
2131
    {
2132
        if (is_object($tool)) {
2133
            $tool = get_class($tool);
2134
        }
2135
        if (!is_string($tool)) {
2136
            throw new InvalidArgumentException('Tool must be an object or a class name');
2137
        }
2138
        foreach ($this->tools as $idx => $tool) {
0 ignored issues
show
introduced by
$tool is overwriting one of the parameters of this function.
Loading history...
2139
            if ($tool['name'] === $tool) {
2140
                unset($this->tools[$idx]);
2141
            }
2142
            if ($tool['tool'] instanceof $tool) {
2143
                unset($this->tools[$idx]);
2144
            }
2145
        }
2146
        return $this;
2147
    }
2148
2149
    /**
2150
     * @param string|AbstractBulkAction $bulkAction Pass name or class
2151
     * @return AbstractBulkAction|null
2152
     */
2153
    public function getBulkAction($bulkAction): ?AbstractBulkAction
2154
    {
2155
        if (is_object($bulkAction)) {
2156
            $bulkAction = get_class($bulkAction);
2157
        }
2158
        if (!is_string($bulkAction)) {
0 ignored issues
show
introduced by
The condition is_string($bulkAction) is always true.
Loading history...
2159
            throw new InvalidArgumentException('BulkAction must be an object or a class name');
2160
        }
2161
        foreach ($this->bulkActions as $ba) {
2162
            if ($ba->getName() == $bulkAction) {
2163
                return $ba;
2164
            }
2165
            if ($ba instanceof $bulkAction) {
2166
                return $ba;
2167
            }
2168
        }
2169
        return null;
2170
    }
2171
2172
    public function getBulkActions(): array
2173
    {
2174
        return $this->bulkActions;
2175
    }
2176
2177
    /**
2178
     * @param AbstractBulkAction[] $bulkActions
2179
     * @return self
2180
     */
2181
    public function setBulkActions(array $bulkActions): self
2182
    {
2183
        foreach ($bulkActions as $bulkAction) {
2184
            $bulkAction->setTabulatorGrid($this);
2185
        }
2186
        $this->bulkActions = $bulkActions;
2187
        return $this;
2188
    }
2189
2190
    public function addBulkAction(AbstractBulkAction $handler): self
2191
    {
2192
        $handler->setTabulatorGrid($this);
2193
2194
        $this->bulkActions[] = $handler;
2195
        return $this;
2196
    }
2197
2198
    public function removeBulkAction($bulkAction): self
2199
    {
2200
        if (is_object($bulkAction)) {
2201
            $bulkAction = get_class($bulkAction);
2202
        }
2203
        if (!is_string($bulkAction)) {
2204
            throw new InvalidArgumentException('Bulk action must be an object or a class name');
2205
        }
2206
        foreach ($this->bulkActions as $idx => $ba) {
2207
            if ($ba->getName() == $bulkAction) {
2208
                unset($this->bulkAction[$idx]);
0 ignored issues
show
Bug Best Practice introduced by
The property bulkAction does not exist on LeKoala\Tabulator\TabulatorGrid. Since you implemented __get, consider adding a @property annotation.
Loading history...
2209
            }
2210
            if ($ba instanceof $bulkAction) {
2211
                unset($this->bulkAction[$idx]);
2212
            }
2213
        }
2214
        return $this;
2215
    }
2216
2217
    public function getColumnDefault(string $opt)
2218
    {
2219
        return $this->columnDefaults[$opt] ?? null;
2220
    }
2221
2222
    public function setColumnDefault(string $opt, $value)
2223
    {
2224
        $this->columnDefaults[$opt] = $value;
2225
    }
2226
2227
    public function getColumnDefaults(): array
2228
    {
2229
        return $this->columnDefaults;
2230
    }
2231
2232
    public function setColumnDefaults(array $columnDefaults): self
2233
    {
2234
        $this->columnDefaults = $columnDefaults;
2235
        return $this;
2236
    }
2237
2238
    public function getListeners(): array
2239
    {
2240
        return $this->listeners;
2241
    }
2242
2243
    public function setListeners(array $listeners): self
2244
    {
2245
        $this->listeners = $listeners;
2246
        return $this;
2247
    }
2248
2249
    public function addListener(string $event, string $functionName): self
2250
    {
2251
        $this->listeners[$event] = $functionName;
2252
        return $this;
2253
    }
2254
2255
    public function removeListener(string $event): self
2256
    {
2257
        if (isset($this->listeners[$event])) {
2258
            unset($this->listeners[$event]);
2259
        }
2260
        return $this;
2261
    }
2262
2263
    public function getLinksOptions(): array
2264
    {
2265
        return $this->linksOptions;
2266
    }
2267
2268
    public function setLinksOptions(array $linksOptions): self
2269
    {
2270
        $this->linksOptions = $linksOptions;
2271
        return $this;
2272
    }
2273
2274
    public function registerLinkOption(string $linksOption): self
2275
    {
2276
        $this->linksOptions[] = $linksOption;
2277
        return $this;
2278
    }
2279
2280
    public function unregisterLinkOption(string $linksOption): self
2281
    {
2282
        $this->linksOptions = array_diff($this->linksOptions, [$linksOption]);
2283
        return $this;
2284
    }
2285
2286
    /**
2287
     * Get the value of pageSize
2288
     */
2289
    public function getPageSize(): int
2290
    {
2291
        return $this->pageSize;
2292
    }
2293
2294
    /**
2295
     * Set the value of pageSize
2296
     *
2297
     * @param int $pageSize
2298
     */
2299
    public function setPageSize(int $pageSize): self
2300
    {
2301
        $this->pageSize = $pageSize;
2302
        return $this;
2303
    }
2304
2305
    /**
2306
     * Get the value of autoloadDataList
2307
     */
2308
    public function getAutoloadDataList(): bool
2309
    {
2310
        return $this->autoloadDataList;
2311
    }
2312
2313
    /**
2314
     * Set the value of autoloadDataList
2315
     *
2316
     * @param bool $autoloadDataList
2317
     */
2318
    public function setAutoloadDataList(bool $autoloadDataList): self
2319
    {
2320
        $this->autoloadDataList = $autoloadDataList;
2321
        return $this;
2322
    }
2323
2324
    /**
2325
     * Set the value of itemRequestClass
2326
     */
2327
    public function setItemRequestClass(string $itemRequestClass): self
2328
    {
2329
        $this->itemRequestClass = $itemRequestClass;
2330
        return $this;
2331
    }
2332
2333
    /**
2334
     * Get the value of lazyInit
2335
     */
2336
    public function getLazyInit(): bool
2337
    {
2338
        return $this->lazyInit;
2339
    }
2340
2341
    /**
2342
     * Set the value of lazyInit
2343
     */
2344
    public function setLazyInit(bool $lazyInit): self
2345
    {
2346
        $this->lazyInit = $lazyInit;
2347
        return $this;
2348
    }
2349
2350
    /**
2351
     * Get the value of rowClickTriggersAction
2352
     */
2353
    public function getRowClickTriggersAction(): bool
2354
    {
2355
        return $this->rowClickTriggersAction;
2356
    }
2357
2358
    /**
2359
     * Set the value of rowClickTriggersAction
2360
     */
2361
    public function setRowClickTriggersAction(bool $rowClickTriggersAction): self
2362
    {
2363
        $this->rowClickTriggersAction = $rowClickTriggersAction;
2364
        return $this;
2365
    }
2366
2367
    /**
2368
     * Get the value of controllerFunction
2369
     */
2370
    public function getControllerFunction(): string
2371
    {
2372
        if (!$this->controllerFunction) {
2373
            return $this->getName() ?? "TabulatorGrid";
2374
        }
2375
        return $this->controllerFunction;
2376
    }
2377
2378
    /**
2379
     * Set the value of controllerFunction
2380
     */
2381
    public function setControllerFunction(string $controllerFunction): self
2382
    {
2383
        $this->controllerFunction = $controllerFunction;
2384
        return $this;
2385
    }
2386
2387
    /**
2388
     * Get the value of editUrl
2389
     */
2390
    public function getEditUrl(): string
2391
    {
2392
        return $this->editUrl;
2393
    }
2394
2395
    /**
2396
     * Set the value of editUrl
2397
     */
2398
    public function setEditUrl(string $editUrl): self
2399
    {
2400
        $this->editUrl = $editUrl;
2401
        return $this;
2402
    }
2403
2404
    /**
2405
     * Get the value of moveUrl
2406
     */
2407
    public function getMoveUrl(): string
2408
    {
2409
        return $this->moveUrl;
2410
    }
2411
2412
    /**
2413
     * Set the value of moveUrl
2414
     */
2415
    public function setMoveUrl(string $moveUrl): self
2416
    {
2417
        $this->moveUrl = $moveUrl;
2418
        return $this;
2419
    }
2420
2421
    /**
2422
     * Get the value of bulkUrl
2423
     */
2424
    public function getBulkUrl(): string
2425
    {
2426
        return $this->bulkUrl;
2427
    }
2428
2429
    /**
2430
     * Set the value of bulkUrl
2431
     */
2432
    public function setBulkUrl(string $bulkUrl): self
2433
    {
2434
        $this->bulkUrl = $bulkUrl;
2435
        return $this;
2436
    }
2437
2438
    /**
2439
     * Get the value of globalSearch
2440
     */
2441
    public function getGlobalSearch(): bool
2442
    {
2443
        return $this->globalSearch;
2444
    }
2445
2446
    /**
2447
     * Set the value of globalSearch
2448
     *
2449
     * @param bool $globalSearch
2450
     */
2451
    public function setGlobalSearch($globalSearch): self
2452
    {
2453
        $this->globalSearch = $globalSearch;
2454
        return $this;
2455
    }
2456
2457
    /**
2458
     * Get the value of wildcardFields
2459
     */
2460
    public function getWildcardFields(): array
2461
    {
2462
        return $this->wildcardFields;
2463
    }
2464
2465
    /**
2466
     * Set the value of wildcardFields
2467
     *
2468
     * @param array $wildcardFields
2469
     */
2470
    public function setWildcardFields($wildcardFields): self
2471
    {
2472
        $this->wildcardFields = $wildcardFields;
2473
        return $this;
2474
    }
2475
2476
    /**
2477
     * Get the value of quickFilters
2478
     */
2479
    public function getQuickFilters(): array
2480
    {
2481
        return $this->quickFilters;
2482
    }
2483
2484
    /**
2485
     * Set the value of quickFilters
2486
     *
2487
     * @param array $quickFilters
2488
     */
2489
    public function setQuickFilters($quickFilters): self
2490
    {
2491
        $this->quickFilters = $quickFilters;
2492
        return $this;
2493
    }
2494
2495
    /**
2496
     * Get the value of groupLayout
2497
     */
2498
    public function getGroupLayout(): bool
2499
    {
2500
        return $this->groupLayout;
2501
    }
2502
2503
    /**
2504
     * Set the value of groupLayout
2505
     *
2506
     * @param bool $groupLayout
2507
     */
2508
    public function setGroupLayout($groupLayout): self
2509
    {
2510
        $this->groupLayout = $groupLayout;
2511
        return $this;
2512
    }
2513
2514
    /**
2515
     * Get the value of enableGridManipulation
2516
     */
2517
    public function getEnableGridManipulation(): bool
2518
    {
2519
        return $this->enableGridManipulation;
2520
    }
2521
2522
    /**
2523
     * Set the value of enableGridManipulation
2524
     *
2525
     * @param bool $enableGridManipulation
2526
     */
2527
    public function setEnableGridManipulation($enableGridManipulation): self
2528
    {
2529
        $this->enableGridManipulation = $enableGridManipulation;
2530
        return $this;
2531
    }
2532
2533
    /**
2534
     * Get the value of defaultFilter
2535
     */
2536
    public function getDefaultFilter(): string
2537
    {
2538
        return $this->defaultFilter;
2539
    }
2540
2541
    /**
2542
     * Set the value of defaultFilter
2543
     *
2544
     * @param string $defaultFilter
2545
     */
2546
    public function setDefaultFilter($defaultFilter): self
2547
    {
2548
        $this->defaultFilter = $defaultFilter;
2549
        return $this;
2550
    }
2551
}
2552