Passed
Push — master ( c42799...aec283 )
by Thomas
02:47
created

TabulatorGrid::getEditUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
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\Forms\FieldList;
17
use SilverStripe\Forms\FormField;
18
use SilverStripe\Control\Director;
19
use SilverStripe\View\Requirements;
20
use SilverStripe\Control\Controller;
21
use SilverStripe\Control\HTTPRequest;
22
use SilverStripe\Control\HTTPResponse;
23
use SilverStripe\ORM\FieldType\DBEnum;
24
use SilverStripe\Control\RequestHandler;
25
use SilverStripe\Core\Injector\Injector;
26
use SilverStripe\Security\SecurityToken;
27
use SilverStripe\ORM\FieldType\DBBoolean;
28
use LeKoala\ModularBehaviour\ModularFormField;
29
use SilverStripe\Forms\GridField\GridFieldConfig;
30
use SilverStripe\Core\Manifest\ModuleResourceLoader;
31
32
/**
33
 * This is a replacement for most GridField usages in SilverStripe
34
 * It can easily work in the frontend too
35
 *
36
 * @link http://www.tabulator.info/
37
 */
38
class TabulatorGrid extends ModularFormField
39
{
40
    const POS_START = 'start';
41
    const POS_END = 'end';
42
43
    // @link http://www.tabulator.info/examples/5.4?#fittodata
44
    const LAYOUT_FIT_DATA = "fitData";
45
    const LAYOUT_FIT_DATA_FILL = "fitDataFill";
46
    const LAYOUT_FIT_DATA_STRETCH = "fitDataStretch";
47
    const LAYOUT_FIT_DATA_TABLE = "fitDataTable";
48
    const LAYOUT_FIT_COLUMNS = "fitColumns";
49
50
    const RESPONSIVE_LAYOUT_HIDE = "hide";
51
    const RESPONSIVE_LAYOUT_COLLAPSE = "collapse";
52
53
    // @link http://www.tabulator.info/docs/5.4/format
54
    const FORMATTER_PLAINTEXT = 'plaintext';
55
    const FORMATTER_TEXTAREA = 'textarea';
56
    const FORMATTER_HTML = 'html';
57
    const FORMATTER_MONEY = 'money';
58
    const FORMATTER_IMAGE = 'image';
59
    const FORMATTER_LINK = 'link';
60
    const FORMATTER_DATETIME = 'datetime';
61
    const FORMATTER_DATETIME_DIFF = 'datetimediff';
62
    const FORMATTER_TICKCROSS = 'tickCross';
63
    const FORMATTER_COLOR = 'color';
64
    const FORMATTER_STAR = 'star';
65
    const FORMATTER_TRAFFIC = 'traffic';
66
    const FORMATTER_PROGRESS = 'progress';
67
    const FORMATTER_LOOKUP = 'lookup';
68
    const FORMATTER_BUTTON_TICK = 'buttonTick';
69
    const FORMATTER_BUTTON_CROSS = 'buttonCross';
70
    const FORMATTER_ROWNUM = 'rownum';
71
    const FORMATTER_HANDLE = 'handle';
72
    // @link http://www.tabulator.info/docs/5.4/format#format-module
73
    const FORMATTER_ROW_SELECTION = 'rowSelection';
74
    const FORMATTER_RESPONSIVE_COLLAPSE = 'responsiveCollapse';
75
76
    // our built in functions
77
    const JS_FLAG_FORMATTER = 'SSTabulator.flagFormatter';
78
    const JS_BUTTON_FORMATTER = 'SSTabulator.buttonFormatter';
79
    const JS_CUSTOM_TICK_CROSS_FORMATTER = 'SSTabulator.customTickCrossFormatter';
80
    const JS_BOOL_GROUP_HEADER = 'SSTabulator.boolGroupHeader';
81
    const JS_SIMPLE_ROW_FORMATTER = 'SSTabulator.simpleRowFormatter';
82
    const JS_EXPAND_TOOLTIP = 'SSTabulator.expandTooltip';
83
    const JS_DATA_AJAX_RESPONSE = 'SSTabulator.dataAjaxResponse';
84
85
    /**
86
     * @config
87
     */
88
    private static array $allowed_actions = [
89
        'load',
90
        'handleItem',
91
        'handleTool',
92
        'configProvider',
93
        'autocomplete',
94
        'handleBulkAction',
95
    ];
96
97
    private static $url_handlers = [
98
        'item/$ID' => 'handleItem',
99
        'tool/$ID' => 'handleTool',
100
        'bulkAction/$ID' => 'handleBulkAction',
101
    ];
102
103
    private static array $casting = [
104
        'JsonOptions' => 'HTMLFragment',
105
        'ShowTools' => 'HTMLFragment',
106
        'dataAttributesHTML' => 'HTMLFragment',
107
    ];
108
109
    /**
110
     * @config
111
     */
112
    private static string $theme = 'bootstrap5';
113
114
    /**
115
     * @config
116
     */
117
    private static string $version = '5.4';
118
119
    /**
120
     * @config
121
     */
122
    private static string $luxon_version = '3';
123
124
    /**
125
     * @config
126
     */
127
    private static string $last_icon_version = '2';
128
129
    /**
130
     * @config
131
     */
132
    private static bool $use_cdn = false;
133
134
    /**
135
     * @config
136
     */
137
    private static bool $use_custom_build = true;
138
139
    /**
140
     * @config
141
     */
142
    private static bool $enable_luxon = false;
143
144
    /**
145
     * @config
146
     */
147
    private static bool $enable_last_icon = false;
148
149
    /**
150
     * @config
151
     */
152
    private static bool $enable_requirements = true;
153
154
    /**
155
     * @config
156
     */
157
    private static bool $enable_js_modules = true;
158
159
    /**
160
     * @link http://www.tabulator.info/docs/5.4/options
161
     * @config
162
     */
163
    private static array $default_options = [
164
        'index' => "ID", // http://tabulator.info/docs/5.4/data#row-index
165
        'layout' => 'fitColumns', // http://www.tabulator.info/docs/5.4/layout#layout
166
        'height' => '100%', // http://www.tabulator.info/docs/5.4/layout#height-fixed
167
        'responsiveLayout' => "hide", // http://www.tabulator.info/docs/5.4/layout#responsive
168
        'rowFormatter' => "SSTabulator.simpleRowFormatter", // http://tabulator.info/docs/5.4/format#row
169
    ];
170
171
    /**
172
     * @link http://tabulator.info/docs/5.4/columns#defaults
173
     * @config
174
     */
175
    private static array $default_column_options = [
176
        'resizable' => false,
177
        'tooltip' => 'SSTabulator.expandTooltip',
178
    ];
179
180
    private static bool $enable_ajax_init = true;
181
182
    /**
183
     * @config
184
     */
185
    private static array $custom_pagination_icons = [];
186
187
    /**
188
     * @config
189
     */
190
    private static bool $default_lazy_init = false;
191
192
    /**
193
     * Data source.
194
     */
195
    protected ?SS_List $list;
196
197
    /**
198
     * @link http://www.tabulator.info/docs/5.4/columns
199
     */
200
    protected array $columns = [];
201
202
    /**
203
     * @link http://tabulator.info/docs/5.4/columns#defaults
204
     */
205
    protected array $columnDefaults = [];
206
207
    /**
208
     * @link http://www.tabulator.info/docs/5.4/options
209
     */
210
    protected array $options = [];
211
212
    protected bool $autoloadDataList = true;
213
214
    protected bool $rowClickTriggersAction = false;
215
216
    protected int $pageSize = 10;
217
218
    protected string $itemRequestClass = '';
219
220
    protected string $modelClass = '';
221
222
    protected bool $lazyInit = false;
223
224
    protected array $tools = [];
225
226
    /**
227
     * @var AbstractBulkAction[]
228
     */
229
    protected array $bulkActions = [];
230
231
    protected array $listeners = [];
232
233
    protected array $jsNamespaces = [
234
        'SSTabulator'
235
    ];
236
237
    protected array $linksOptions = [
238
        'ajaxURL'
239
    ];
240
241
    protected array $dataAttributes = [];
242
243
    protected string $controllerFunction = "";
244
245
    protected bool $useConfigProvider = false;
246
247
    protected bool $useInitScript = false;
248
249
    protected string $editUrl = "";
250
251
    protected string $moveUrl = "";
252
253
    protected string $bulkUrl = "";
254
255
    /**
256
     * @param string $fieldName
257
     * @param string|null|bool $title
258
     * @param SS_List $value
259
     */
260
    public function __construct($name, $title = null, $value = null)
261
    {
262
        parent::__construct($name, $title, $value);
263
        $this->options = self::config()->default_options ?? [];
264
        $this->columnDefaults = self::config()->default_column_options ?? [];
265
        $this->setLazyInit(self::config()->default_lazy_init);
266
267
        // We don't want regular setValue for this since it would break with loadFrom logic
268
        if ($value) {
269
            $this->setList($value);
270
        }
271
    }
272
273
    /**
274
     * This helps if some third party code expects the TabulatorGrid to be a GridField
275
     * Only works to a really basic extent
276
     */
277
    public function getConfig(): GridFieldConfig
278
    {
279
        return new GridFieldConfig;
280
    }
281
282
    /**
283
     * Temporary link that will be replaced by a real link by processLinks
284
     *
285
     * @param string $action
286
     * @return string
287
     */
288
    public function TempLink(string $action, bool $controller = true): string
289
    {
290
        // It's an absolute link
291
        if (strpos($action, '/') === 0 || strpos($action, 'http') === 0) {
292
            return $action;
293
        }
294
        // Already temp
295
        if (strpos($action, ':') !== false) {
296
            return $action;
297
        }
298
        $prefix = $controller ? "controller" : "form";
299
        return "$prefix:$action";
300
    }
301
302
    public function ControllerLink(string $action): string
303
    {
304
        return $this->getForm()->getController()->Link($action);
305
    }
306
307
    public function getCreateLink(): string
308
    {
309
        return Controller::join_links($this->Link('item'), 'new');
310
    }
311
312
    /**
313
     * @param FieldList $fields
314
     * @param string $name
315
     * @return TabulatorGrid|null
316
     */
317
    public static function replaceGridField(FieldList $fields, string $name)
318
    {
319
        /** @var \SilverStripe\Forms\GridField\GridField $gridField */
320
        $gridField = $fields->dataFieldByName($name);
321
        if (!$gridField) {
0 ignored issues
show
introduced by
$gridField is of type SilverStripe\Forms\GridField\GridField, thus it always evaluated to true.
Loading history...
322
            return;
323
        }
324
        $tabulatorGrid = new TabulatorGrid($name, $gridField->Title(), $gridField->getList());
325
        // In the cms, this is mostly never happening
326
        if ($gridField->getForm()) {
327
            $tabulatorGrid->setForm($gridField->getForm());
328
        }
329
        $tabulatorGrid->configureFromDataObject($gridField->getModelClass());
330
        $tabulatorGrid->setLazyInit(true);
331
        $fields->replaceField($name, $tabulatorGrid);
332
333
        return $tabulatorGrid;
334
    }
335
336
    public function configureFromDataObject($className = null, bool $clear = true): void
0 ignored issues
show
Unused Code introduced by
The parameter $clear is not used and could be removed. ( Ignorable by Annotation )

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

336
    public function configureFromDataObject($className = null, /** @scrutinizer ignore-unused */ bool $clear = true): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
337
    {
338
        $this->columns = [];
339
340
        if (!$className) {
341
            $className = $this->getModelClass();
342
        }
343
        if (!$className) {
344
            throw new RuntimeException("Could not find the model class");
345
        }
346
        $this->modelClass = $className;
347
348
        /** @var DataObject $singl */
349
        $singl = singleton($className);
350
351
        // Mock some base columns using SilverStripe built-in methods
352
        $columns = [];
353
        foreach ($singl->summaryFields() as $field => $title) {
354
            $title = str_replace(".", " ", $title);
355
            $columns[$field] = [
356
                'field' => $field,
357
                'title' => $title,
358
            ];
359
360
            $dbObject = $singl->dbObject($field);
361
            if ($dbObject) {
362
                if ($dbObject instanceof DBBoolean) {
363
                    $columns[$field]['formatter'] = "SSTabulator.customTickCrossFormatter";
364
                }
365
            }
366
        }
367
        foreach ($singl->searchableFields() as $key => $searchOptions) {
368
            /*
369
            "filter" => "NameOfTheFilter"
370
            "field" => "SilverStripe\Forms\FormField"
371
            "title" => "Title of the field"
372
            */
373
            if (!isset($columns[$key])) {
374
                continue;
375
            }
376
            $columns[$key]['headerFilter'] = true;
377
            // $columns[$key]['headerFilterPlaceholder'] = $searchOptions['title'];
378
            //TODO: implement filter mapping
379
            switch ($searchOptions['filter']) {
380
                default:
381
                    $columns[$key]['headerFilterFunc'] =  "like";
382
                    break;
383
            }
384
385
            // Restrict based on data type
386
            $dbObject = $singl->dbObject($key);
387
            if ($dbObject) {
388
                if ($dbObject instanceof DBBoolean) {
389
                    $columns[$key]['headerFilter'] = 'tickCross';
390
                    $columns[$key]['headerFilterFunc'] =  "=";
391
                    $columns[$key]['headerFilterParams'] =  [
392
                        'tristate' => true
393
                    ];
394
                }
395
                if ($dbObject instanceof DBEnum) {
396
                    $columns[$key]['headerFilter'] = 'list';
397
                    $columns[$key]['headerFilterFunc'] =  "=";
398
                    $columns[$key]['headerFilterParams'] =  [
399
                        'values' => $dbObject->enumValues()
400
                    ];
401
                }
402
            }
403
        }
404
405
        // Allow customizing our columns based on record
406
        if ($singl->hasMethod('tabulatorColumns')) {
407
            $fields = $singl->tabulatorColumns();
408
            if (!is_array($fields)) {
409
                throw new RuntimeException("tabulatorColumns must return an array");
410
            }
411
            foreach ($fields as $key => $columnOptions) {
412
                $baseOptions = $columns[$key] ?? [];
413
                $columns[$key] = array_merge($baseOptions, $columnOptions);
414
            }
415
        }
416
417
        $this->extend('updateConfiguredColumns', $columns);
418
419
        foreach ($columns as $col) {
420
            $this->addColumn($col['field'], $col['title'], $col);
421
        }
422
423
        // Sortable ?
424
        if ($singl->hasField('Sort')) {
425
            $this->wizardMoveable();
426
        }
427
428
        // Actions
429
        // We use a pseudo link, because maybe we cannot call Link() yet if it's not linked to a form
430
431
        $this->bulkUrl = $this->TempLink("bulkAction/", false);
432
433
        // - Core actions, handled by TabulatorGrid
434
        $itemUrl = $this->TempLink('item/{ID}', false);
435
        if ($singl->canEdit()) {
436
            $this->addButton("ui_edit", $itemUrl, "edit", "Edit");
437
            $this->editUrl = $this->TempLink("item/{ID}/ajaxEdit", false);
438
        } elseif ($singl->canView()) {
439
            $this->addButton("ui_view", $itemUrl, "visibility", "View");
440
        }
441
442
        // - Tools
443
        $this->tools = [];
444
        if ($singl->canCreate()) {
445
            $this->addTool(self::POS_START, new TabulatorAddNewButton($this));
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

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

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...
446
        }
447
448
        // - Custom actions are forwarded to the model itself
449
        if ($singl->hasMethod('tabulatorRowActions')) {
450
            $rowActions = $singl->tabulatorRowActions();
451
            if (!is_array($rowActions)) {
452
                throw new RuntimeException("tabulatorRowActions must return an array");
453
            }
454
            foreach ($rowActions as $key => $actionConfig) {
455
                $action = $actionConfig['action'] ?? $key;
456
                $url = $this->TempLink("item/{ID}/customAction/$action", false);
457
                $icon = $actionConfig['icon'] ?? "cog";
458
                $title = $actionConfig['title'] ?? "";
459
460
                $button = $this->makeButton($url, $icon, $title);
461
                if (!empty($actionConfig['ajax'])) {
462
                    $button['formatterParams']['ajax'] = true;
463
                }
464
                $this->addButtonFromArray("ui_customaction_$action", $button);
465
            }
466
        }
467
468
        $this->setRowClickTriggersAction(true);
469
    }
470
471
    public static function requirements(): void
472
    {
473
        $use_cdn = self::config()->use_cdn;
474
        $use_custom_build = self::config()->use_custom_build;
475
        $theme = self::config()->theme; // simple, midnight, modern or framework
476
        $version = self::config()->version;
477
        $luxon_version = self::config()->luxon_version;
478
        $enable_luxon = self::config()->enable_luxon;
479
        $last_icon_version = self::config()->last_icon_version;
480
        $enable_last_icon = self::config()->enable_last_icon;
481
        $enable_js_modules = self::config()->enable_js_modules;
482
483
        $jsOpts = [];
484
        if ($enable_js_modules) {
485
            $jsOpts['type'] = 'module';
486
        }
487
488
        if ($use_cdn) {
489
            $baseDir = "https://cdn.jsdelivr.net/npm/tabulator-tables@$version/dist";
490
        } else {
491
            $asset = ModuleResourceLoader::resourceURL('lekoala/silverstripe-tabulator:client/cdn/js/tabulator.min.js');
492
            $baseDir = dirname(dirname($asset));
493
        }
494
495
        if ($luxon_version && $enable_luxon) {
496
            // Do not load as module or we would get undefined luxon global var
497
            Requirements::javascript("https://cdn.jsdelivr.net/npm/luxon@$luxon_version/build/global/luxon.min.js");
498
        }
499
        if ($last_icon_version && $enable_last_icon) {
500
            Requirements::css("https://cdn.jsdelivr.net/npm/last-icon@$last_icon_version/last-icon.min.css");
501
            // Do not load as module even if asked to ensure load speed
502
            Requirements::javascript("https://cdn.jsdelivr.net/npm/last-icon@$last_icon_version/last-icon.min.js");
503
        }
504
        if ($use_custom_build) {
505
            // if (Director::isDev() && !Director::is_ajax()) {
506
            //     Requirements::javascript("lekoala/silverstripe-tabulator:client/custom-tabulator.js");
507
            // } else {
508
            Requirements::javascript("lekoala/silverstripe-tabulator:client/custom-tabulator.min.js", $jsOpts);
509
            // }
510
            Requirements::javascript('lekoala/silverstripe-tabulator:client/TabulatorField.js', $jsOpts);
511
        } else {
512
            Requirements::javascript("$baseDir/js/tabulator.min.js", $jsOpts);
513
            Requirements::javascript('lekoala/silverstripe-tabulator:client/TabulatorField.js', $jsOpts);
514
        }
515
516
        if ($theme) {
517
            Requirements::css("$baseDir/css/tabulator_$theme.min.css");
518
        } else {
519
            Requirements::css("$baseDir/css/tabulator.min.css");
520
        }
521
522
        if ($theme && $theme == "bootstrap5") {
523
            Requirements::css('lekoala/silverstripe-tabulator:client/custom-tabulator.min.css');
524
        }
525
    }
526
527
    public function setValue($value, $data = null)
528
    {
529
        if ($value instanceof DataList) {
530
            $this->configureFromDataObject($value->dataClass());
531
        }
532
        return parent::setValue($value, $data);
533
    }
534
535
    public function getModularName()
536
    {
537
        return 'SSTabulator.createTabulator';
538
    }
539
540
    public function getModularSelector()
541
    {
542
        return '.tabulatorgrid';
543
    }
544
545
    public function getModularConfigName()
546
    {
547
        return str_replace('-', '_', $this->ID()) . '_config';
548
    }
549
550
    public function getModularConfig()
551
    {
552
        $JsonOptions = $this->JsonOptions();
553
        $configName = $this->getModularConfigName();
554
        $script = "var $configName = $JsonOptions";
555
        return $script;
556
    }
557
558
    public function Field($properties = [])
559
    {
560
        $this->addExtraClass(self::config()->theme);
561
        if ($this->lazyInit) {
562
            $this->setModularLazy($this->lazyInit);
563
        }
564
        if (self::config()->enable_requirements) {
565
            self::requirements();
566
        }
567
568
        // Make sure we can use a standalone version of the field without a form
569
        // Function should match the name
570
        if (!$this->form) {
571
            $this->form = new Form(Controller::curr(), $this->getControllerFunction());
572
        }
573
574
        // Data attributes for our custom behaviour
575
        $this->setDataAttribute("row-click-triggers-action", $this->rowClickTriggersAction);
576
        $customIcons = self::config()->custom_pagination_icons;
577
        $this->setDataAttribute("use-custom-pagination-icons", empty($customIcons));
578
579
        $this->setDataAttribute("listeners", $this->listeners);
580
        if ($this->editUrl) {
581
            $url = $this->processLink($this->editUrl);
582
            $this->setDataAttribute("edit-url", $url);
583
        }
584
        if ($this->moveUrl) {
585
            $url = $this->processLink($this->moveUrl);
586
            $this->setDataAttribute("move-url", $url);
587
        }
588
        if (!empty($this->bulkActions)) {
589
            $url = $this->processLink($this->bulkUrl);
590
            $this->setDataAttribute("bulk-url", $url);
591
        }
592
593
        if ($this->useConfigProvider) {
594
            $configLink = "/" . ltrim($this->Link("configProvider"), "/");
595
            $configLink .= "?t=" . time();
596
            // This cannot be loaded as a js module
597
            Requirements::javascript($configLink, ['type' => 'application/javascript', 'defer' => 'true']);
598
        } elseif ($this->useInitScript) {
599
            Requirements::customScript($this->getInitScript());
0 ignored issues
show
Deprecated Code introduced by
The function LeKoala\Tabulator\TabulatorGrid::getInitScript() has been deprecated. ( Ignorable by Annotation )

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

599
            Requirements::customScript(/** @scrutinizer ignore-deprecated */ $this->getInitScript());
Loading history...
600
        }
601
602
        // Skip modular behaviour
603
        if ($this->useConfigProvider || $this->useInitScript) {
604
            return FormField::Field($properties);
605
        }
606
        return parent::Field($properties);
607
    }
608
609
    public function ShowTools(): string
610
    {
611
        if (empty($this->tools)) {
612
            return '';
613
        }
614
        $html = '';
615
        $html .= '<div class="tabulator-tools">';
616
        $html .= '<div class="tabulator-tools-start">';
617
        foreach ($this->tools as $tool) {
618
            if ($tool['position'] != self::POS_START) {
619
                continue;
620
            }
621
            $html .= ($tool['tool'])->forTemplate();
622
        }
623
        $html .= '</div>';
624
        $html .= '<div class="tabulator-tools-end">';
625
        foreach ($this->tools as $tool) {
626
            if ($tool['position'] != self::POS_END) {
627
                continue;
628
            }
629
            $html .= ($tool['tool'])->forTemplate();
630
        }
631
        // Show bulk actions at the end
632
        if (!empty($this->bulkActions)) {
633
            $selectLabel = _t(__CLASS__ . ".BULKSELECT", "Select a bulk action");
634
            $confirmLabel = _t(__CLASS__ . ".BULKCONFIRM", "Go");
635
            $html .= "<select class=\"tabulator-bulk-select\">";
636
            $html .= "<option>" . $selectLabel . "</option>";
637
            foreach ($this->bulkActions as $bulkAction) {
638
                $v = $bulkAction->getName();
639
                $xhr = $bulkAction->getXhr();
640
                $destructive = $bulkAction->getDestructive();
641
                $html .= "<option value=\"$v\" data-xhr=\"$xhr\" data-destructive=\"$destructive\">" . $bulkAction->getLabel() . "</option>";
642
            }
643
            $html .= "</select>";
644
            $html .= "<button class=\"tabulator-bulk-confirm btn\">" . $confirmLabel . "</button>";
645
        }
646
        $html .= '</div>';
647
        $html .= '</div>';
648
        return $html;
649
    }
650
651
    public function JsonOptions(): string
652
    {
653
        $this->processLinks();
654
655
        $data = $this->list ?? [];
656
        if ($this->autoloadDataList && $data instanceof DataList) {
657
            $data = null;
658
        }
659
        $opts = $this->options;
660
        $opts['columnDefaults'] = $this->columnDefaults;
661
662
        if (empty($this->columns)) {
663
            $opts['autoColumns'] = true;
664
        } else {
665
            $opts['columns'] = array_values($this->columns);
666
        }
667
668
        if ($data && is_iterable($data)) {
669
            if ($data instanceof ArrayList) {
670
                $data = $data->toArray();
671
            } else {
672
                if (is_iterable($data) && !is_array($data)) {
673
                    $data = iterator_to_array($data);
674
                }
675
            }
676
            $opts['data'] = $data;
677
        }
678
679
        // i18n
680
        $locale = strtolower(str_replace('_', '-', i18n::get_locale()));
681
        $paginationTranslations = [
682
            "first" => _t("TabulatorPagination.first", "First"),
683
            "first_title" =>  _t("TabulatorPagination.first_title", "First Page"),
684
            "last" =>  _t("TabulatorPagination.last", "Last"),
685
            "last_title" => _t("TabulatorPagination.last_title", "Last Page"),
686
            "prev" => _t("TabulatorPagination.prev", "Previous"),
687
            "prev_title" =>  _t("TabulatorPagination.prev_title", "Previous Page"),
688
            "next" => _t("TabulatorPagination.next", "Next"),
689
            "next_title" =>  _t("TabulatorPagination.next_title", "Next Page"),
690
            "all" =>  _t("TabulatorPagination.all", "All"),
691
        ];
692
        // This will always default to last icon if present
693
        $customIcons = self::config()->custom_pagination_icons;
694
        if (!empty($customIcons)) {
695
            $paginationTranslations['first'] = $customIcons['first'] ?? "<<";
696
            $paginationTranslations['last'] = $customIcons['last'] ?? ">>";
697
            $paginationTranslations['prev'] = $customIcons['prev'] ?? "<";
698
            $paginationTranslations['next'] = $customIcons['next'] ?? ">";
699
        }
700
        $dataTranslations = [
701
            "loading" => _t("TabulatorData.loading", "Loading"),
702
            "error" => _t("TabulatorData.error", "Error"),
703
        ];
704
        $groupsTranslations = [
705
            "item" => _t("TabulatorGroups.item", "Item"),
706
            "items" => _t("TabulatorGroups.items", "Items"),
707
        ];
708
        $headerFiltersTranslations = [
709
            "default" => _t("TabulatorHeaderFilters.default", "filter column..."),
710
        ];
711
        $bulkActionsTranslations = [
712
            "no_action" => _t("TabulatorBulkActions.no_action", "Please select an action"),
713
            "no_records" => _t("TabulatorBulkActions.no_records", "Please select a record"),
714
            "destructive" => _t("TabulatorBulkActions.destructive", "Confirm destructive action ?"),
715
        ];
716
        $translations = [
717
            'data' => $dataTranslations,
718
            'groups' => $groupsTranslations,
719
            'pagination' => $paginationTranslations,
720
            'headerFilters' => $headerFiltersTranslations,
721
            'bulkActions' => $bulkActionsTranslations,
722
        ];
723
        $opts['locale'] = $locale;
724
        $opts['langs'] = [
725
            $locale => $translations
726
        ];
727
728
        $format = Director::isDev() ? JSON_PRETTY_PRINT : 0;
729
        $json = json_encode($opts, $format);
730
731
        // Escape functions by namespace (see TabulatorField.js)
732
        foreach ($this->jsNamespaces as $ns) {
733
            $json = preg_replace('/"(' . $ns . '\.[a-zA-Z]*)"/', "$1", $json);
734
            // Keep static namespaces
735
            $json = str_replace("*" . $ns, $ns, $json);
736
        }
737
738
        return $json;
739
    }
740
741
    /**
742
     * @param Controller $controller
743
     * @return CompatLayerInterface
744
     */
745
    public function getCompatLayer(Controller $controller)
746
    {
747
        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...
748
            return new SilverstripeAdminCompat();
749
        }
750
        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...
751
            return new AdminiCompat();
752
        }
753
    }
754
755
    public function getAttributes()
756
    {
757
        $attrs = parent::getAttributes();
758
        unset($attrs['type']);
759
        unset($attrs['name']);
760
        return $attrs;
761
    }
762
763
    public function getOption(string $k)
764
    {
765
        return $this->options[$k] ?? null;
766
    }
767
768
    public function setOption(string $k, $v): self
769
    {
770
        $this->options[$k] = $v;
771
        return $this;
772
    }
773
774
    public function makeHeadersSticky(): self
775
    {
776
        $this->addExtraClass("tabulator-sticky");
777
        return $this;
778
    }
779
780
    public function setRemoteSource(string $url, array $extraParams = [], bool $dataResponse = false): self
781
    {
782
        $this->setOption("ajaxURL", $url); //set url for ajax request
783
        $params = array_merge([
784
            'SecurityID' => SecurityToken::getSecurityID()
785
        ], $extraParams);
786
        $this->setOption("ajaxParams", $params);
787
        // Accept response where data is nested under the data key
788
        if ($dataResponse) {
789
            $this->setOption("ajaxResponse", self::JS_DATA_AJAX_RESPONSE);
790
        }
791
        return $this;
792
    }
793
794
    /**
795
     * @link http://www.tabulator.info/docs/5.4/page#remote
796
     * @param string $url
797
     * @param array $params
798
     * @param integer $pageSize
799
     * @param integer $initialPage
800
     */
801
    public function setRemotePagination(string $url, array $params = [], int $pageSize = 0, int $initialPage = 1): self
802
    {
803
        $this->setOption("pagination", true); //enable pagination
804
        $this->setOption("paginationMode", 'remote'); //enable remote pagination
805
        $this->setRemoteSource($url, $params);
806
        if (!$pageSize) {
807
            $pageSize = $this->pageSize;
808
        }
809
        $this->setOption("paginationSize", $pageSize);
810
        $this->setOption("paginationInitialPage", $initialPage);
811
        $this->setOption("paginationCounter", 'rows'); // http://www.tabulator.info/docs/5.4/page#counter
812
        return $this;
813
    }
814
815
    public function wizardRemotePagination(int $pageSize = 0, int $initialPage = 1, array $params = []): self
816
    {
817
        $this->setRemotePagination($this->TempLink('load', false), $params, $pageSize, $initialPage);
818
        $this->setOption("sortMode", "remote"); // http://www.tabulator.info/docs/5.4/sort#ajax-sort
819
        $this->setOption("filterMode", "remote"); // http://www.tabulator.info/docs/5.4/filter#ajax-filter
820
        return $this;
821
    }
822
823
    public function setProgressiveLoad(string $url, array $params = [], int $pageSize = 0, int $initialPage = 1, string $mode = 'scroll', int $scrollMargin = 0): self
824
    {
825
        $this->setOption("ajaxURL", $url);
826
        if (!empty($params)) {
827
            $this->setOption("ajaxParams", $params);
828
        }
829
        $this->setOption("progressiveLoad", $mode);
830
        if ($scrollMargin > 0) {
831
            $this->setOption("progressiveLoadScrollMargin", $scrollMargin);
832
        }
833
        if (!$pageSize) {
834
            $pageSize = $this->pageSize;
835
        }
836
        $this->setOption("paginationSize", $pageSize);
837
        $this->setOption("paginationInitialPage", $initialPage);
838
        $this->setOption("paginationCounter", 'rows'); // http://www.tabulator.info/docs/5.4/page#counter
839
        return $this;
840
    }
841
842
    public function wizardProgressiveLoad(int $pageSize = 0, int $initialPage = 1, string $mode = 'scroll', int $scrollMargin = 0, array $extraParams = []): self
843
    {
844
        $params = array_merge([
845
            'SecurityID' => SecurityToken::getSecurityID()
846
        ], $extraParams);
847
        $this->setProgressiveLoad($this->TempLink('load', false), $params, $pageSize, $initialPage, $mode, $scrollMargin);
848
        $this->setOption("sortMode", "remote"); // http://www.tabulator.info/docs/5.4/sort#ajax-sort
849
        $this->setOption("filterMode", "remote"); // http://www.tabulator.info/docs/5.4/filter#ajax-filter
850
        return $this;
851
    }
852
853
    public function wizardResponsiveCollapse(bool $startOpen = false, string $mode = "collapse"): self
854
    {
855
        $this->setOption("responsiveLayout", $mode);
856
        $this->setOption("responsiveLayoutCollapseStartOpen", $startOpen);
857
        $this->columns = array_merge([
858
            'ui_responsive_collapse' => [
859
                "cssClass" => 'tabulator-cell-btn',
860
                'formatter' => 'responsiveCollapse',
861
                'headerSort' => false,
862
                'width' => 40,
863
            ]
864
        ], $this->columns);
865
        return $this;
866
    }
867
868
    public function wizardDataTree(bool $startExpanded = false, bool $filter = false, bool $sort = false, string $el = null): self
869
    {
870
        $this->setOption("dataTree", true);
871
        $this->setOption("dataTreeStartExpanded", $startExpanded);
872
        $this->setOption("dataTreeFilter", $filter);
873
        $this->setOption("dataTreeSort", $sort);
874
        if ($el) {
875
            $this->setOption("dataTreeElementColumn", $el);
876
        }
877
        return $this;
878
    }
879
880
    public function wizardSelectable(array $actions = []): self
881
    {
882
        $this->columns = array_merge([
883
            'ui_selectable' => [
884
                "hozAlign" => 'center',
885
                "cssClass" => 'tabulator-cell-btn tabulator-cell-selector',
886
                'formatter' => 'rowSelection',
887
                'titleFormatter' => 'rowSelection',
888
                'headerSort' => false,
889
                'width' => 40,
890
                'cellClick' => 'SSTabulator.forwardClick',
891
            ]
892
        ], $this->columns);
893
        $this->setBulkActions($actions);
894
        return $this;
895
    }
896
897
    public function wizardMoveable(string $callback = "SSTabulator.rowMoved"): self
898
    {
899
        $this->moveUrl = $this->TempLink("item/{ID}/ajaxMove", false);
900
        $this->setOption("movableRows", true);
901
        $this->addListener("rowMoved", $callback);
902
        $this->columns = array_merge([
903
            'ui_move' => [
904
                "hozAlign" => 'center',
905
                "cssClass" => 'tabulator-cell-btn tabulator-cell-selector',
906
                'rowHandle' => true,
907
                'formatter' => 'handle',
908
                'headerSort' => false,
909
                'frozen' => true,
910
                'width' => 40,
911
            ]
912
        ], $this->columns);
913
        return $this;
914
    }
915
916
    /**
917
     * @param string $field
918
     * @param string $toggleElement arrow|header|false (header by default)
919
     * @param boolean $isBool
920
     * @return void
921
     */
922
    public function wizardGroupBy(string $field, string $toggleElement = 'header', bool $isBool = false)
923
    {
924
        $this->setOption("groupBy", $field);
925
        $this->setOption("groupToggleElement", $toggleElement);
926
        if ($isBool) {
927
            $this->setOption("groupHeader", self::JS_BOOL_GROUP_HEADER);
928
        }
929
    }
930
931
    /**
932
     * @param HTTPRequest $request
933
     * @return HTTPResponse
934
     */
935
    public function handleItem($request)
936
    {
937
        // Our getController could either give us a true Controller, if this is the top-level GridField.
938
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
939
        $requestHandler = $this->getForm()->getController();
940
        $record = $this->getRecordFromRequest($request);
941
        if (!$record) {
942
            return $requestHandler->httpError(404, 'That record was not found');
943
        }
944
        $handler = $this->getItemRequestHandler($record, $requestHandler);
945
        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...
946
    }
947
948
    /**
949
     * @param HTTPRequest $request
950
     * @return HTTPResponse
951
     */
952
    public function handleTool($request)
953
    {
954
        // Our getController could either give us a true Controller, if this is the top-level GridField.
955
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
956
        $requestHandler = $this->getForm()->getController();
957
        $tool = $this->getToolFromRequest($request);
958
        if (!$tool) {
959
            return $requestHandler->httpError(404, 'That tool was not found');
960
        }
961
        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...
962
    }
963
964
    /**
965
     * @param HTTPRequest $request
966
     * @return HTTPResponse
967
     */
968
    public function handleBulkAction($request)
969
    {
970
        // Our getController could either give us a true Controller, if this is the top-level GridField.
971
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
972
        $requestHandler = $this->getForm()->getController();
973
        $bulkAction = $this->getBulkActionFromRequest($request);
974
        if (!$bulkAction) {
975
            return $requestHandler->httpError(404, 'That bulk action was not found');
976
        }
977
        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...
978
    }
979
980
    /**
981
     * @return string name of {@see TabulatorGrid_ItemRequest} subclass
982
     */
983
    public function getItemRequestClass(): string
984
    {
985
        if ($this->itemRequestClass) {
986
            return $this->itemRequestClass;
987
        } elseif (ClassInfo::exists(static::class . '_ItemRequest')) {
988
            return static::class . '_ItemRequest';
989
        }
990
        return TabulatorGrid_ItemRequest::class;
991
    }
992
993
    /**
994
     * Build a request handler for the given record
995
     *
996
     * @param DataObject $record
997
     * @param RequestHandler $requestHandler
998
     * @return TabulatorGrid_ItemRequest
999
     */
1000
    protected function getItemRequestHandler($record, $requestHandler)
1001
    {
1002
        $class = $this->getItemRequestClass();
1003
        $assignedClass = $this->itemRequestClass;
1004
        $this->extend('updateItemRequestClass', $class, $record, $requestHandler, $assignedClass);
1005
        /** @var TabulatorGrid_ItemRequest $handler */
1006
        $handler = Injector::inst()->createWithArgs(
1007
            $class,
1008
            [$this, $record, $requestHandler]
1009
        );
1010
        if ($template = $this->getTemplate()) {
1011
            $handler->setTemplate($template);
1012
        }
1013
        $this->extend('updateItemRequestHandler', $handler);
1014
        return $handler;
1015
    }
1016
1017
    public function getStateKey()
1018
    {
1019
        return $this->getName();
1020
    }
1021
1022
    public function getState(HTTPRequest $request)
1023
    {
1024
        $stateKey = $this->getName();
1025
        $state = $request->getSession()->get("TabulatorState[$stateKey]");
1026
        return $state ?? [
1027
            'page' => 1,
1028
            'limit' => $this->pageSize,
1029
            'sort' => [],
1030
            'filter' => [],
1031
        ];
1032
    }
1033
1034
    public function setState(HTTPRequest $request, $state)
1035
    {
1036
        $stateKey = $this->getName();
1037
        $request->getSession()->set("TabulatorState[$stateKey]", $state);
1038
    }
1039
1040
    /**
1041
     * Deprecated in favor of modular behaviour
1042
     * @deprecated
1043
     * @return string
1044
     */
1045
    public function getInitScript(): string
1046
    {
1047
        $JsonOptions = $this->JsonOptions();
1048
        $ID = $this->ID();
1049
        $script = "SSTabulator.init(\"#$ID\", $JsonOptions);";
1050
        return $script;
1051
    }
1052
1053
    /**
1054
     * Provides the configuration for this instance
1055
     *
1056
     * This is really useful in the context of the admin as it will be served over
1057
     * ajax
1058
     *
1059
     * Deprecated in favor of modular behaviour
1060
     * @deprecated
1061
     * @param HTTPRequest $request
1062
     * @return HTTPResponse
1063
     */
1064
    public function configProvider(HTTPRequest $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

1064
    public function configProvider(/** @scrutinizer ignore-unused */ HTTPRequest $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1065
    {
1066
        if (!$this->useConfigProvider) {
1067
            return $this->httpError(404);
1068
        }
1069
        $response = new HTTPResponse($this->getInitScript());
0 ignored issues
show
Deprecated Code introduced by
The function LeKoala\Tabulator\TabulatorGrid::getInitScript() has been deprecated. ( Ignorable by Annotation )

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

1069
        $response = new HTTPResponse(/** @scrutinizer ignore-deprecated */ $this->getInitScript());
Loading history...
1070
        $response->addHeader('Content-Type', 'application/script');
1071
        return $response;
1072
    }
1073
1074
    /**
1075
     * Provides autocomplete lists
1076
     *
1077
     * @param HTTPRequest $request
1078
     * @return HTTPResponse
1079
     */
1080
    public function autocomplete(HTTPRequest $request)
1081
    {
1082
        if ($this->isDisabled() || $this->isReadonly()) {
1083
            return $this->httpError(403);
1084
        }
1085
        $SecurityID = $request->getVar('SecurityID');
1086
        if (!SecurityToken::inst()->check($SecurityID)) {
1087
            return $this->httpError(404, "Invalid SecurityID");
1088
        }
1089
1090
        $name = $request->getVar("Column");
1091
        $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

1091
        $col = $this->getColumn(/** @scrutinizer ignore-type */ $name);
Loading history...
1092
        if (!$col) {
1093
            return $this->httpError(403, "Invalid column");
1094
        }
1095
1096
        // Don't use % term as it prevents use of indexes
1097
        $term = $request->getVar('term') . '%';
1098
        $term = str_replace(' ', '%', $term);
1099
1100
        $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

1100
        $parts = explode(".", /** @scrutinizer ignore-type */ $name);
Loading history...
1101
        if (count($parts) > 2) {
1102
            array_pop($parts);
1103
        }
1104
        if (count($parts) == 2) {
1105
            $class = $parts[0];
1106
            $field = $parts[1];
1107
        } elseif (count($parts) == 1) {
1108
            $class = preg_replace("/ID$/", "", $parts[0]);
1109
            $field = 'Title';
1110
        } else {
1111
            return $this->httpError(403, "Invalid field");
1112
        }
1113
1114
        /** @var DataObject $sng */
1115
        $sng = $class::singleton();
1116
        $baseTable = $sng->baseTable();
1117
1118
        $searchField = null;
1119
        $searchCandidates = [
1120
            $field, 'Name', 'Surname', 'Email', 'ID'
1121
        ];
1122
1123
        // Ensure field exists, this is really rudimentary
1124
        $db = $class::config()->db;
1125
        foreach ($searchCandidates as $searchCandidate) {
1126
            if ($searchField) {
1127
                continue;
1128
            }
1129
            if (isset($db[$searchCandidate])) {
1130
                $searchField = $searchCandidate;
1131
            }
1132
        }
1133
        $searchCols = [$searchField];
1134
1135
        // For members, do something better
1136
        if ($baseTable == 'Member') {
1137
            $searchField = ['FirstName', 'Surname'];
1138
            $searchCols = ['FirstName', 'Surname', 'Email'];
1139
        }
1140
1141
        if (!empty($col['editorParams']['customSearchField'])) {
1142
            $searchField = $col['editorParams']['customSearchField'];
1143
        }
1144
        if (!empty($col['editorParams']['customSearchCols'])) {
1145
            $searchCols = $col['editorParams']['customSearchCols'];
1146
        }
1147
1148
1149
        /** @var DataList $list */
1150
        $list = $sng::get();
1151
1152
        // Make sure at least one field is not null...
1153
        $where = [];
1154
        foreach ($searchCols as $searchCol) {
1155
            $where[] = $searchCol . ' IS NOT NULL';
1156
        }
1157
        $list = $list->where($where);
1158
        // ... and matches search term ...
1159
        $where = [];
1160
        foreach ($searchCols as $searchCol) {
1161
            $where[$searchCol . ' LIKE ?'] = $term;
1162
        }
1163
        $list = $list->whereAny($where);
1164
1165
        // ... and any user set requirements
1166
        if (!empty($col['editorParams']['where'])) {
1167
            // Deal with in clause
1168
            $customWhere = [];
1169
            foreach ($col['editorParams']['where'] as $col => $param) {
1170
                // For array, we need a IN statement with a ? for each value
1171
                if (is_array($param)) {
1172
                    $prepValue = [];
1173
                    $params = [];
1174
                    foreach ($param as $paramValue) {
1175
                        $params[] = $paramValue;
1176
                        $prepValue[] = "?";
1177
                    }
1178
                    $customWhere["$col IN (" . implode(',', $prepValue) . ")"] = $params;
1179
                } else {
1180
                    $customWhere["$col = ?"] = $param;
1181
                }
1182
            }
1183
            $list = $list->where($customWhere);
1184
        }
1185
1186
        $results = iterator_to_array($list);
1187
        $data = [];
1188
        foreach ($results as $record) {
1189
            if (is_array($searchField)) {
1190
                $labelParts = [];
1191
                foreach ($searchField as $sf) {
1192
                    $labelParts[] = $record->$sf;
1193
                }
1194
                $label = implode(" ", $labelParts);
1195
            } else {
1196
                $label = $record->$searchField;
1197
            }
1198
            $data[] = [
1199
                'value' => $record->ID,
1200
                'label' => $label,
1201
            ];
1202
        }
1203
1204
        $json = json_encode($data);
1205
        $response = new HTTPResponse($json);
1206
        $response->addHeader('Content-Type', 'application/script');
1207
        return $response;
1208
    }
1209
1210
    /**
1211
     * @link http://www.tabulator.info/docs/5.4/page#remote-response
1212
     * @param HTTPRequest $request
1213
     * @return HTTPResponse
1214
     */
1215
    public function load(HTTPRequest $request)
1216
    {
1217
        if ($this->isDisabled() || $this->isReadonly()) {
1218
            return $this->httpError(403);
1219
        }
1220
        $SecurityID = $request->getVar('SecurityID');
1221
        if (!SecurityToken::inst()->check($SecurityID)) {
1222
            return $this->httpError(404, "Invalid SecurityID");
1223
        }
1224
1225
        $page = (int) $request->getVar('page');
1226
        $limit = (int) $request->getVar('size');
1227
1228
        $sort = $request->getVar('sort');
1229
        $filter = $request->getVar('filter');
1230
1231
        // Persist state to allow the ItemEditForm to display navigation
1232
        $state = [
1233
            'page' => $page,
1234
            'limit' => $limit,
1235
            'sort' => $sort,
1236
            'filter' => $filter,
1237
        ];
1238
        $this->setState($request, $state);
1239
1240
        $offset = ($page - 1) * $limit;
1241
        $data = $this->getManipulatedData($limit, $offset, $sort, $filter);
1242
1243
        $response = new HTTPResponse(json_encode($data));
1244
        $response->addHeader('Content-Type', 'application/json');
1245
        return $response;
1246
    }
1247
1248
    /**
1249
     * @param HTTPRequest $request
1250
     * @return DataObject|null
1251
     */
1252
    protected function getRecordFromRequest(HTTPRequest $request): ?DataObject
1253
    {
1254
        /** @var DataObject $record */
1255
        if (is_numeric($request->param('ID'))) {
1256
            /** @var Filterable $dataList */
1257
            $dataList = $this->getList();
1258
            $record = $dataList->byID($request->param('ID'));
1259
        } else {
1260
            $record = Injector::inst()->create($this->getModelClass());
1261
        }
1262
        return $record;
1263
    }
1264
1265
    /**
1266
     * @param HTTPRequest $request
1267
     * @return AbstractTabulatorTool|null
1268
     */
1269
    protected function getToolFromRequest(HTTPRequest $request): ?AbstractTabulatorTool
1270
    {
1271
        $toolID = $request->param('ID');
1272
        $tool = $this->getTool($toolID);
1273
        return $tool;
1274
    }
1275
1276
    /**
1277
     * @param HTTPRequest $request
1278
     * @return AbstractBulkAction|null
1279
     */
1280
    protected function getBulkActionFromRequest(HTTPRequest $request): ?AbstractBulkAction
1281
    {
1282
        $toolID = $request->param('ID');
1283
        $tool = $this->getBulkAction($toolID);
1284
        return $tool;
1285
    }
1286
1287
    public function getList(): SS_List
1288
    {
1289
        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...
1290
    }
1291
1292
    public function setList(SS_List $list): self
1293
    {
1294
        if ($this->autoloadDataList && $list instanceof DataList) {
1295
            $this->wizardRemotePagination();
1296
        }
1297
        $this->list = $list;
1298
        return $this;
1299
    }
1300
1301
    public function hasArrayList(): bool
1302
    {
1303
        return $this->list instanceof ArrayList;
1304
    }
1305
1306
    public function getArrayList(): ArrayList
1307
    {
1308
        if (!$this->list instanceof ArrayList) {
1309
            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

1309
            throw new RuntimeException("Value is not a ArrayList, it is a: " . get_class(/** @scrutinizer ignore-type */ $this->list));
Loading history...
1310
        }
1311
        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...
1312
    }
1313
1314
    public function hasDataList(): bool
1315
    {
1316
        return $this->list instanceof DataList;
1317
    }
1318
1319
    /**
1320
     * A properly typed on which you can call byID
1321
     * @return ArrayList|DataList
1322
     */
1323
    public function getByIDList()
1324
    {
1325
        return $this->list;
1326
    }
1327
1328
    public function hasByIDList(): bool
1329
    {
1330
        return $this->hasDataList() || $this->hasArrayList();
1331
    }
1332
1333
    public function getDataList(): DataList
1334
    {
1335
        if (!$this->list instanceof DataList) {
1336
            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

1336
            throw new RuntimeException("Value is not a DataList, it is a: " . get_class(/** @scrutinizer ignore-type */ $this->list));
Loading history...
1337
        }
1338
        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...
1339
    }
1340
1341
    public function getManipulatedData(int $limit, int $offset, array $sort = null, array $filter = null): array
1342
    {
1343
        if (!$this->hasDataList()) {
1344
            $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

1344
            /** @scrutinizer ignore-call */ 
1345
            $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...
1345
1346
            $lastRow = $this->list->count();
1347
            $lastPage = ceil($lastRow / $limit);
1348
1349
            $result = [
1350
                'last_row' => $lastRow,
1351
                'last_page' => $lastPage,
1352
                'data' => $data,
1353
            ];
1354
1355
            return $result;
1356
        }
1357
1358
        $dataList = $this->getDataList();
1359
1360
        $schema = DataObject::getSchema();
1361
        $dataClass = $dataList->dataClass();
1362
        /** @var DataObject $singleton */
1363
        $singleton = singleton($dataClass);
1364
        $resolutionMap = [];
1365
1366
        $sortSql = [];
1367
        if ($sort) {
1368
            foreach ($sort as $sortValues) {
1369
                $cols = array_keys($this->columns);
1370
                $field = $sortValues['field'];
1371
                if (!in_array($field, $cols)) {
1372
                    throw new Exception("Invalid sort field: $field");
1373
                }
1374
                $dir = $sortValues['dir'];
1375
                if (!in_array($dir, ['asc', 'desc'])) {
1376
                    throw new Exception("Invalid sort dir: $dir");
1377
                }
1378
1379
                // Nested sort
1380
                if (strpos($field, '.') !== false) {
1381
                    $parts = explode(".", $field);
1382
                    if (!isset($resolutionMap[$parts[0]])) {
1383
                        $resolutionMap[$parts[0]] = singleton($dataClass)->relObject($parts[0]);
1384
                    }
1385
                    $relatedObject = get_class($resolutionMap[$parts[0]]);
1386
                    $tableName = $schema->tableForField($relatedObject, $parts[1]);
1387
                    $baseIDColumn = $schema->sqlColumnForField($dataClass, 'ID');
1388
                    $tableAlias = $parts[0];
1389
                    $dataList = $dataList->leftJoin($tableName, "\"{$tableAlias}\".\"ID\" = {$baseIDColumn}", $tableAlias);
1390
                }
1391
1392
                $sortSql[] = $field . ' ' . $dir;
1393
            }
1394
        }
1395
        if (!empty($sortSql)) {
1396
            $dataList = $dataList->sort(implode(", ", $sortSql));
1397
        }
1398
1399
        // Filtering is an array of field/type/value arrays
1400
        $where = [];
1401
        if ($filter) {
1402
            foreach ($filter as $filterValues) {
1403
                $cols = array_keys($this->columns);
1404
                $field = $filterValues['field'];
1405
                if (!in_array($field, $cols)) {
1406
                    throw new Exception("Invalid sort field: $field");
1407
                }
1408
                $value = $filterValues['value'];
1409
                $type = $filterValues['type'];
1410
1411
                // Strict value
1412
                if ($value === "true") {
1413
                    $value = true;
1414
                } elseif ($value === "false") {
1415
                    $value = false;
1416
                }
1417
1418
                switch ($type) {
1419
                    case "=":
1420
                        $where["$field"] = $value;
1421
                        break;
1422
                    case "!=":
1423
                        $where["$field:not"] = $value;
1424
                        break;
1425
                    case "like":
1426
                        $where["$field:PartialMatch:nocase"] = $value;
1427
                        break;
1428
                    case "keywords":
1429
                        $where["$field:PartialMatch:nocase"] = str_replace(" ", "%", $value);
1430
                        break;
1431
                    case "starts":
1432
                        $where["$field:StartsWith:nocase"] = $value;
1433
                        break;
1434
                    case "ends":
1435
                        $where["$field:EndsWith:nocase"] = $value;
1436
                        break;
1437
                    case "<":
1438
                        $where["$field:LessThan:nocase"] = $value;
1439
                        break;
1440
                    case "<=":
1441
                        $where["$field:LessThanOrEqual:nocase"] = $value;
1442
                        break;
1443
                    case ">":
1444
                        $where["$field:GreaterThan:nocase"] = $value;
1445
                        break;
1446
                    case ">=":
1447
                        $where["$field:GreaterThanOrEqual:nocase"] = $value;
1448
                        break;
1449
                    case "in":
1450
                        $where["$field"] = $value;
1451
                        break;
1452
                    case "regex":
1453
                        $dataList = $dataList->where('REGEXP ' . Convert::raw2sql($value));
1454
                        break;
1455
                    default:
1456
                        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...
1457
                }
1458
            }
1459
        }
1460
        if (!empty($where)) {
1461
            $dataList = $dataList->filter($where);
1462
        }
1463
1464
        $lastRow = $dataList->count();
1465
        $lastPage = ceil($lastRow / $limit);
1466
1467
        $data = [];
1468
        /** @var DataObject $record */
1469
        foreach ($dataList->limit($limit, $offset) as $record) {
1470
            if ($record->hasMethod('canView') && !$record->canView()) {
1471
                continue;
1472
            }
1473
1474
            $item = [
1475
                'ID' => $record->ID,
1476
            ];
1477
            $nested = [];
1478
            foreach ($this->columns as $col) {
1479
                $field = $col['field'] ?? ''; // actions don't have field
1480
                if (strpos($field, '.') !== false) {
1481
                    $parts = explode('.', $field);
1482
                    if ($singleton->getRelationClass($parts[0])) {
1483
                        $nested[$parts[0]][] = $parts[1];
1484
                        continue;
1485
                    }
1486
                }
1487
                $item[$field] = $record->getField($field);
1488
            }
1489
            foreach ($nested as $nestedClass => $nestedColumns) {
1490
                $relObject = $record->relObject($nestedClass);
1491
                $nestedData = [];
1492
                foreach ($nestedColumns as $nestedColumn) {
1493
                    $nestedData[$nestedColumn] = $relObject->getField($nestedColumn);
1494
                }
1495
                $item[$nestedClass] = $nestedData;
1496
            }
1497
            $data[] = $item;
1498
        }
1499
1500
        $result = [
1501
            'last_row' => $lastRow,
1502
            'last_page' => $lastPage,
1503
            'data' => $data,
1504
        ];
1505
1506
        return $result;
1507
    }
1508
1509
    public function getModelClass(): ?string
1510
    {
1511
        if ($this->modelClass) {
1512
            return $this->modelClass;
1513
        }
1514
        if ($this->list && $this->list instanceof DataList) {
1515
            return $this->list->dataClass();
1516
        }
1517
        return null;
1518
    }
1519
1520
    public function setModelClass(string $modelClass): self
1521
    {
1522
        $this->modelClass = $modelClass;
1523
        return $this;
1524
    }
1525
1526
1527
    public function getDataAttribute(string $k)
1528
    {
1529
        if (isset($this->dataAttributes[$k])) {
1530
            return $this->dataAttributes[$k];
1531
        }
1532
        return $this->getAttribute("data-$k");
1533
    }
1534
1535
    public function setDataAttribute(string $k, $v): self
1536
    {
1537
        $this->dataAttributes[$k] = $v;
1538
        return $this;
1539
    }
1540
1541
    public function dataAttributesHTML(): string
1542
    {
1543
        $parts = [];
1544
        foreach ($this->dataAttributes as $k => $v) {
1545
            if (!$v) {
1546
                continue;
1547
            }
1548
            if (is_array($v)) {
1549
                $v = json_encode($v);
1550
            }
1551
            $parts[] = "data-$k='$v'";
1552
        }
1553
        return implode(" ", $parts);
1554
    }
1555
1556
    protected function processLink(string $url): string
1557
    {
1558
        // It's not necessary to process
1559
        if ($url == '#') {
1560
            return $url;
1561
        }
1562
        // It's a temporary link on the form
1563
        if (strpos($url, 'form:') === 0) {
1564
            return $this->Link(preg_replace('/^form:/', '', $url));
1565
        }
1566
        // It's a temporary link on the controller
1567
        if (strpos($url, 'controller:') === 0) {
1568
            return $this->ControllerLink(preg_replace('/^controller:/', '', $url));
1569
        }
1570
        // It's a custom protocol (mailto: etc)
1571
        if (strpos($url, ':') !== false) {
1572
            return $url;
1573
        }
1574
        return $url;
1575
    }
1576
1577
    protected function processLinks(): void
1578
    {
1579
        // Process editor and formatter links
1580
        foreach ($this->columns as $name => $params) {
1581
            if (!empty($params['formatterParams']['url'])) {
1582
                $url = $this->processLink($params['formatterParams']['url']);
1583
                $this->columns[$name]['formatterParams']['url'] = $url;
1584
            }
1585
            if (!empty($params['editorParams']['url'])) {
1586
                $url = $this->processLink($params['editorParams']['url']);
1587
                $this->columns[$name]['editorParams']['url'] = $url;
1588
            }
1589
            // Set valuesURL automatically if not already set
1590
            if (!empty($params['editorParams']['autocomplete'])) {
1591
                if (empty($params['editorParams']['valuesURL'])) {
1592
                    $params = [
1593
                        'Column' => $name,
1594
                        'SecurityID' => SecurityToken::getSecurityID(),
1595
                    ];
1596
                    $url = $this->Link('autocomplete') . '?' . http_build_query($params);
1597
                    $this->columns[$name]['editorParams']['valuesURL'] = $url;
1598
                    $this->columns[$name]['editorParams']['filterRemote'] = true;
1599
                }
1600
            }
1601
        }
1602
1603
        // Other links
1604
        $url = $this->getOption('ajaxURL');
1605
        if ($url) {
1606
            $this->setOption('ajaxURL', $this->processLink($url));
1607
        }
1608
    }
1609
1610
    public function makeButton(string $urlOrAction, string $icon, string $title): array
1611
    {
1612
        $opts = [
1613
            "responsive" => 0,
1614
            "cssClass" => 'tabulator-cell-btn',
1615
            "tooltip" => $title,
1616
            "formatter" => "SSTabulator.buttonFormatter",
1617
            "formatterParams" => [
1618
                "icon" => $icon,
1619
                "title" => $title,
1620
                "url" => $this->TempLink($urlOrAction), // On the controller by default
1621
            ],
1622
            "cellClick" => "SSTabulator.buttonHandler",
1623
            "width" => 70,
1624
            "hozAlign" => "center",
1625
            "headerSort" => false,
1626
1627
        ];
1628
        return $opts;
1629
    }
1630
1631
    public function addButtonFromArray(string $action, array $opts = [], string $before = null): self
1632
    {
1633
        // Insert before given column
1634
        if ($before) {
1635
            if (array_key_exists($before, $this->columns)) {
1636
                $new = [];
1637
                foreach ($this->columns as $k => $value) {
1638
                    if ($k === $before) {
1639
                        $new["action_$action"] = $opts;
1640
                    }
1641
                    $new[$k] = $value;
1642
                }
1643
                $this->columns = $new;
1644
            }
1645
        } else {
1646
            $this->columns["action_$action"] = $opts;
1647
        }
1648
        return $this;
1649
    }
1650
1651
    /**
1652
     * @param string $action Action name
1653
     * @param string $url Parameters between {} will be interpolated by row values.
1654
     * @param string $icon
1655
     * @param string $title
1656
     * @param string|null $before
1657
     * @return self
1658
     */
1659
    public function addButton(string $action, string $url, string $icon, string $title, string $before = null): self
1660
    {
1661
        $opts = $this->makeButton($url, $icon, $title);
1662
        $this->addButtonFromArray($action, $opts, $before);
1663
        return $this;
1664
    }
1665
1666
    public function shiftButton(string $action, string $url, string $icon, string $title): self
1667
    {
1668
        // Find first action
1669
        foreach ($this->columns as $name => $options) {
1670
            if (strpos($name, 'action_') === 0) {
1671
                return $this->addButton($action, $url, $icon, $title, $name);
1672
            }
1673
        }
1674
        return $this->addButton($action, $url, $icon, $title);
1675
    }
1676
1677
    public function removeButton(string $action): self
1678
    {
1679
        if (isset($this->columns["action_$action"])) {
1680
            unset($this->columns["action_$action"]);
1681
        }
1682
        return $this;
1683
    }
1684
1685
    /**
1686
     * @link http://www.tabulator.info/docs/5.4/columns#definition
1687
     * @param string $field (Required) this is the key for this column in the data array
1688
     * @param string $title (Required) This is the title that will be displayed in the header for this column
1689
     * @param array $opts Other options to merge in
1690
     * @return $this
1691
     */
1692
    public function addColumn(string $field, string $title = null, array $opts = []): self
1693
    {
1694
        if ($title === null) {
1695
            $title = $field;
1696
        }
1697
1698
        $baseOpts = [
1699
            "field" => $field,
1700
            "title" => $title,
1701
        ];
1702
1703
        if (!empty($opts)) {
1704
            $baseOpts = array_merge($baseOpts, $opts);
1705
        }
1706
1707
        $this->columns[$field] = $baseOpts;
1708
        return $this;
1709
    }
1710
1711
    /**
1712
     * @link http://www.tabulator.info/docs/5.4/columns#definition
1713
     * @param array $opts Other options to merge in
1714
     * @return $this
1715
     */
1716
    public function addColumnFromArray(array $opts = [])
1717
    {
1718
        if (empty($opts['field']) || !isset($opts['title'])) {
1719
            throw new Exception("Missing field or title key");
1720
        }
1721
        $field = $opts['field'];
1722
        $this->columns[$field] = $opts;
1723
        return $this;
1724
    }
1725
1726
    public function makeColumnEditable(string $field, string $editor = "input", array $params = [])
1727
    {
1728
        $col = $this->getColumn($field);
1729
        if (!$col) {
1730
            throw new InvalidArgumentException("$field is not a valid column");
1731
        }
1732
1733
        switch ($editor) {
1734
            case 'date':
1735
                $editor = "input";
1736
                $params = [
1737
                    'mask' => "9999-99-99",
1738
                    'maskAutoFill' => 'true',
1739
                ];
1740
                break;
1741
            case 'datetime':
1742
                $editor = "input";
1743
                $params = [
1744
                    'mask' => "9999-99-99 99:99:99",
1745
                    'maskAutoFill' => 'true',
1746
                ];
1747
                break;
1748
        }
1749
1750
        if (empty($col['cssClass'])) {
1751
            $col['cssClass'] = 'no-change-track';
1752
        } else {
1753
            $col['cssClass'] .= ' no-change-track';
1754
        }
1755
1756
        $col['editor'] = $editor;
1757
        $col['editorParams'] = $params;
1758
        if ($editor == "list") {
1759
            if (!empty($params['autocomplete'])) {
1760
                $col['headerFilter'] = "input"; // force input
1761
            } else {
1762
                $col['headerFilterParams'] = $params; // editor is used as base filter editor
1763
            }
1764
        }
1765
1766
1767
        $this->setColumn($field, $col);
1768
    }
1769
1770
    /**
1771
     * Get column details
1772
1773
     * @param string $key
1774
     */
1775
    public function getColumn(string $key): ?array
1776
    {
1777
        if (isset($this->columns[$key])) {
1778
            return $this->columns[$key];
1779
        }
1780
        return null;
1781
    }
1782
1783
    /**
1784
     * Set column details
1785
     *
1786
     * @param string $key
1787
     * @param array $col
1788
     */
1789
    public function setColumn(string $key, array $col): self
1790
    {
1791
        $this->columns[$key] = $col;
1792
        return $this;
1793
    }
1794
1795
    /**
1796
     * Remove a column
1797
     *
1798
     * @param string $key
1799
     */
1800
    public function removeColumn(string $key): void
1801
    {
1802
        unset($this->columns[$key]);
1803
    }
1804
1805
1806
    /**
1807
     * Get the value of columns
1808
     */
1809
    public function getColumns(): array
1810
    {
1811
        return $this->columns;
1812
    }
1813
1814
    /**
1815
     * Set the value of columns
1816
     */
1817
    public function setColumns(array $columns): self
1818
    {
1819
        $this->columns = $columns;
1820
        return $this;
1821
    }
1822
1823
    /**
1824
     * @param string|AbstractTabulatorTool $tool Pass name or class
1825
     * @return AbstractTabulatorTool|null
1826
     */
1827
    public function getTool($tool): ?AbstractTabulatorTool
1828
    {
1829
        if (is_object($tool)) {
1830
            $tool = get_class($tool);
1831
        }
1832
        if (!is_string($tool)) {
0 ignored issues
show
introduced by
The condition is_string($tool) is always true.
Loading history...
1833
            throw new InvalidArgumentException('Tool must be an object or a class name');
1834
        }
1835
        foreach ($this->tools as $t) {
1836
            if ($t['name'] === $tool) {
1837
                return $t['tool'];
1838
            }
1839
            if ($t['tool'] instanceof $tool) {
1840
                return $t['tool'];
1841
            }
1842
        }
1843
        return null;
1844
    }
1845
1846
    public function addTool(string $pos, AbstractTabulatorTool $tool, string $name = ''): self
1847
    {
1848
        $tool->setTabulatorGrid($this);
1849
1850
        $this->tools[] = [
1851
            'position' => $pos,
1852
            'tool' => $tool,
1853
            'name' => $name,
1854
        ];
1855
        return $this;
1856
    }
1857
1858
    public function removeTool($tool): self
1859
    {
1860
        if (is_object($tool)) {
1861
            $tool = get_class($tool);
1862
        }
1863
        if (!is_string($tool)) {
1864
            throw new InvalidArgumentException('Tool must be an object or a class name');
1865
        }
1866
        foreach ($this->tools as $idx => $tool) {
0 ignored issues
show
introduced by
$tool is overwriting one of the parameters of this function.
Loading history...
1867
            if ($tool['name'] === $tool) {
1868
                unset($this->tools[$idx]);
1869
            }
1870
            if ($tool['tool'] instanceof $tool) {
1871
                unset($this->tools[$idx]);
1872
            }
1873
        }
1874
        return $this;
1875
    }
1876
1877
    /**
1878
     * @param string|AbstractBulkAction $bulkAction Pass name or class
1879
     * @return AbstractBulkAction|null
1880
     */
1881
    public function getBulkAction($bulkAction): ?AbstractBulkAction
1882
    {
1883
        if (is_object($bulkAction)) {
1884
            $bulkAction = get_class($bulkAction);
1885
        }
1886
        if (!is_string($bulkAction)) {
0 ignored issues
show
introduced by
The condition is_string($bulkAction) is always true.
Loading history...
1887
            throw new InvalidArgumentException('BulkAction must be an object or a class name');
1888
        }
1889
        foreach ($this->bulkActions as $ba) {
1890
            if ($ba->getName() == $bulkAction) {
1891
                return $ba;
1892
            }
1893
            if ($ba instanceof $bulkAction) {
1894
                return $ba;
1895
            }
1896
        }
1897
        return null;
1898
    }
1899
1900
    public function getBulkActions(): array
1901
    {
1902
        return $this->bulkActions;
1903
    }
1904
1905
    /**
1906
     * @param AbstractBulkAction[] $bulkActions
1907
     * @return self
1908
     */
1909
    public function setBulkActions(array $bulkActions): self
1910
    {
1911
        foreach ($bulkActions as $bulkAction) {
1912
            $bulkAction->setTabulatorGrid($this);
1913
        }
1914
        $this->bulkActions = $bulkActions;
1915
        return $this;
1916
    }
1917
1918
    public function addBulkAction(AbstractBulkAction $handler): self
1919
    {
1920
        $handler->setTabulatorGrid($this);
1921
1922
        $this->bulkActions[] = $handler;
1923
        return $this;
1924
    }
1925
1926
    public function removeBulkAction($bulkAction): self
1927
    {
1928
        if (is_object($bulkAction)) {
1929
            $bulkAction = get_class($bulkAction);
1930
        }
1931
        if (!is_string($bulkAction)) {
1932
            throw new InvalidArgumentException('Bulk action must be an object or a class name');
1933
        }
1934
        foreach ($this->bulkActions as $idx => $ba) {
1935
            if ($ba->getName() == $bulkAction) {
1936
                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...
1937
            }
1938
            if ($ba instanceof $bulkAction) {
1939
                unset($this->bulkAction[$idx]);
1940
            }
1941
        }
1942
        return $this;
1943
    }
1944
1945
    public function getColumnDefault(string $opt)
1946
    {
1947
        return $this->columnDefaults[$opt] ?? null;
1948
    }
1949
1950
    public function setColumnDefault(string $opt, $value)
1951
    {
1952
        $this->columnDefaults[$opt] = $value;
1953
    }
1954
1955
    public function getColumnDefaults(): array
1956
    {
1957
        return $this->columnDefaults;
1958
    }
1959
1960
    public function setColumnDefaults(array $columnDefaults): self
1961
    {
1962
        $this->columnDefaults = $columnDefaults;
1963
        return $this;
1964
    }
1965
1966
    public function getListeners(): array
1967
    {
1968
        return $this->listeners;
1969
    }
1970
1971
    public function setListeners(array $listeners): self
1972
    {
1973
        $this->listeners = $listeners;
1974
        return $this;
1975
    }
1976
1977
    public function addListener(string $event, string $functionName): self
1978
    {
1979
        $this->listeners[$event] = $functionName;
1980
        return $this;
1981
    }
1982
1983
    public function removeListener(string $event): self
1984
    {
1985
        if (isset($this->listeners[$event])) {
1986
            unset($this->listeners[$event]);
1987
        }
1988
        return $this;
1989
    }
1990
1991
    public function getJsNamespaces(): array
1992
    {
1993
        return $this->jsNamespaces;
1994
    }
1995
1996
    public function setJsNamespaces(array $jsNamespaces): self
1997
    {
1998
        $this->jsNamespaces = $jsNamespaces;
1999
        return $this;
2000
    }
2001
2002
    public function registerJsNamespace(string $ns): self
2003
    {
2004
        $this->jsNamespaces[] = $ns;
2005
        return $this;
2006
    }
2007
2008
    public function unregisterJsNamespace(string $ns): self
2009
    {
2010
        $this->jsNamespaces = array_diff($this->jsNamespaces, [$ns]);
2011
        return $this;
2012
    }
2013
2014
    public function getLinksOptions(): array
2015
    {
2016
        return $this->linksOptions;
2017
    }
2018
2019
    public function setLinksOptions(array $linksOptions): self
2020
    {
2021
        $this->linksOptions = $linksOptions;
2022
        return $this;
2023
    }
2024
2025
    public function registerLinkOption(string $linksOption): self
2026
    {
2027
        $this->linksOptions[] = $linksOption;
2028
        return $this;
2029
    }
2030
2031
    public function unregisterLinkOption(string $linksOption): self
2032
    {
2033
        $this->linksOptions = array_diff($this->linksOptions, [$linksOption]);
2034
        return $this;
2035
    }
2036
2037
    /**
2038
     * Get the value of pageSize
2039
     */
2040
    public function getPageSize(): int
2041
    {
2042
        return $this->pageSize;
2043
    }
2044
2045
    /**
2046
     * Set the value of pageSize
2047
     *
2048
     * @param int $pageSize
2049
     */
2050
    public function setPageSize(int $pageSize): self
2051
    {
2052
        $this->pageSize = $pageSize;
2053
        return $this;
2054
    }
2055
2056
    /**
2057
     * Get the value of autoloadDataList
2058
     */
2059
    public function getAutoloadDataList(): bool
2060
    {
2061
        return $this->autoloadDataList;
2062
    }
2063
2064
    /**
2065
     * Set the value of autoloadDataList
2066
     *
2067
     * @param bool $autoloadDataList
2068
     */
2069
    public function setAutoloadDataList(bool $autoloadDataList): self
2070
    {
2071
        $this->autoloadDataList = $autoloadDataList;
2072
        return $this;
2073
    }
2074
2075
    /**
2076
     * Set the value of itemRequestClass
2077
     */
2078
    public function setItemRequestClass(string $itemRequestClass): self
2079
    {
2080
        $this->itemRequestClass = $itemRequestClass;
2081
        return $this;
2082
    }
2083
2084
    /**
2085
     * Get the value of lazyInit
2086
     */
2087
    public function getLazyInit(): bool
2088
    {
2089
        return $this->lazyInit;
2090
    }
2091
2092
    /**
2093
     * Set the value of lazyInit
2094
     */
2095
    public function setLazyInit(bool $lazyInit): self
2096
    {
2097
        $this->lazyInit = $lazyInit;
2098
        return $this;
2099
    }
2100
2101
    /**
2102
     * Get the value of rowClickTriggersAction
2103
     */
2104
    public function getRowClickTriggersAction(): bool
2105
    {
2106
        return $this->rowClickTriggersAction;
2107
    }
2108
2109
    /**
2110
     * Set the value of rowClickTriggersAction
2111
     */
2112
    public function setRowClickTriggersAction(bool $rowClickTriggersAction): self
2113
    {
2114
        $this->rowClickTriggersAction = $rowClickTriggersAction;
2115
        return $this;
2116
    }
2117
2118
    /**
2119
     * Get the value of controllerFunction
2120
     */
2121
    public function getControllerFunction(): string
2122
    {
2123
        if (!$this->controllerFunction) {
2124
            return $this->getName() ?? "TabulatorGrid";
2125
        }
2126
        return $this->controllerFunction;
2127
    }
2128
2129
    /**
2130
     * Set the value of controllerFunction
2131
     */
2132
    public function setControllerFunction(string $controllerFunction): self
2133
    {
2134
        $this->controllerFunction = $controllerFunction;
2135
        return $this;
2136
    }
2137
2138
    /**
2139
     * Get the value of useConfigProvider
2140
     */
2141
    public function getUseConfigProvider(): bool
2142
    {
2143
        return $this->useConfigProvider;
2144
    }
2145
2146
    /**
2147
     * Set the value of useConfigProvider
2148
     */
2149
    public function setUseConfigProvider(bool $useConfigProvider): self
2150
    {
2151
        $this->useConfigProvider = $useConfigProvider;
2152
        return $this;
2153
    }
2154
2155
    /**
2156
     * Get the value of useInitScript
2157
     */
2158
    public function getUseInitScript(): bool
2159
    {
2160
        return $this->useConfigProvider;
2161
    }
2162
2163
    /**
2164
     * Set the value of useInitScript
2165
     */
2166
    public function setUseInitScript(bool $useInitScript): self
2167
    {
2168
        $this->useInitScript = $useInitScript;
2169
        return $this;
2170
    }
2171
2172
    /**
2173
     * Get the value of editUrl
2174
     */
2175
    public function getEditUrl(): string
2176
    {
2177
        return $this->editUrl;
2178
    }
2179
2180
    /**
2181
     * Set the value of editUrl
2182
     */
2183
    public function setEditUrl(string $editUrl): self
2184
    {
2185
        $this->editUrl = $editUrl;
2186
        return $this;
2187
    }
2188
2189
    /**
2190
     * Get the value of moveUrl
2191
     */
2192
    public function getMoveUrl(): string
2193
    {
2194
        return $this->moveUrl;
2195
    }
2196
2197
    /**
2198
     * Set the value of moveUrl
2199
     */
2200
    public function setMoveUrl(string $moveUrl): self
2201
    {
2202
        $this->moveUrl = $moveUrl;
2203
        return $this;
2204
    }
2205
2206
    /**
2207
     * Get the value of bulkUrl
2208
     */
2209
    public function getBulkUrl(): string
2210
    {
2211
        return $this->bulkUrl;
2212
    }
2213
2214
    /**
2215
     * Set the value of bulkUrl
2216
     */
2217
    public function setBulkUrl(string $bulkUrl): self
2218
    {
2219
        $this->bulkUrl = $bulkUrl;
2220
        return $this;
2221
    }
2222
}
2223