GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — integration ( a3ab80...7a98f7 )
by Brendan
06:22
created

FieldSelect::getExampleFormMarkup()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 22
rs 8.9197
1
<?php
2
3
    /**
4
     * @package toolkit
5
     */
6
7
    /**
8
     * A simple Select field that essentially maps to HTML's `<select/>`. The
9
     * options for this field can be static, or feed from another field.
10
     */
11
    class FieldSelect extends FieldTagList implements ExportableField, ImportableField
12
    {
13 View Code Duplication
        public function __construct()
14
        {
15
            parent::__construct();
16
            $this->_name = __('Select Box');
0 ignored issues
show
Bug introduced by
The property _name does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
17
            $this->_required = true;
18
            $this->_showassociation = true;
19
20
            // Set default
21
            $this->set('show_column', 'yes');
22
            $this->set('location', 'sidebar');
23
            $this->set('required', 'no');
24
        }
25
26
        /*-------------------------------------------------------------------------
27
            Definition:
28
        -------------------------------------------------------------------------*/
29
30
        public function toggleFieldData(array $data, $newState, $entry_id = null)
31
        {
32
            $data['value'] = $newState;
33
            $data['handle'] = Lang::createHandle($newState);
34
35
            return $data;
36
        }
37
38
        public function canFilter()
39
        {
40
            return true;
41
        }
42
43
        public function canPrePopulate()
44
        {
45
            return true;
46
        }
47
48
        public function isSortable()
49
        {
50
            return true;
51
        }
52
53
        public function allowDatasourceOutputGrouping()
54
        {
55
            // Grouping follows the same rule as toggling.
56
            return $this->canToggle();
57
        }
58
59
        public function canToggle()
60
        {
61
            return ($this->get('allow_multiple_selection') === 'yes' ? false : true);
62
        }
63
64
        public function allowDatasourceParamOutput()
65
        {
66
            return true;
67
        }
68
69
        public function requiresSQLGrouping()
70
        {
71
            // SQL grouping follows the opposite rule as toggling.
72
            return !$this->canToggle();
73
        }
74
75
        public function fetchSuggestionTypes()
76
        {
77
            return array('association', 'static');
78
        }
79
80
        public function createTable()
81
        {
82
            return Symphony::Database()->query(
83
                "CREATE TABLE IF NOT EXISTS `tbl_entries_data_" . $this->get('id') . "` (
84
              `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
85
              `entry_id` INT(11) UNSIGNED NOT NULL,
86
              `handle` VARCHAR(255) DEFAULT NULL,
87
              `value` VARCHAR(255) DEFAULT NULL,
88
              PRIMARY KEY  (`id`),
89
              KEY `entry_id` (`entry_id`),
90
              KEY `handle` (`handle`),
91
              KEY `value` (`value`)
92
            )"
93
            );
94
        }
95
96
        /*-------------------------------------------------------------------------
97
            Setup:
98
        -------------------------------------------------------------------------*/
99
100
        public function findDefaults(array &$settings)
101
        {
102
            if (!isset($settings['allow_multiple_selection'])) {
103
                $settings['allow_multiple_selection'] = 'no';
104
            }
105
106
            if (!isset($settings['show_association'])) {
107
                $settings['show_association'] = 'no';
108
            }
109
110
            if (!isset($settings['sort_options'])) {
111
                $settings['sort_options'] = 'no';
112
            }
113
        }
114
115
        /*-------------------------------------------------------------------------
116
            Utilities:
117
        -------------------------------------------------------------------------*/
118
119
        public function displaySettingsPanel(XMLElement &$wrapper, $errors = null)
120
        {
121
            Field::displaySettingsPanel($wrapper, $errors);
122
123
            $div = new XMLElement('div', null, array('class' => 'two columns'));
124
125
            // Predefined Values
126
            $label = Widget::Label(__('Static Values'));
127
            $label->setAttribute('class', 'column');
128
            $label->appendChild(new XMLElement('i', __('Optional')));
129
            $input = Widget::Input('fields[' . $this->get('sortorder') . '][static_options]',
130
                General::sanitize($this->get('static_options')));
131
            $label->appendChild($input);
132
            $div->appendChild($label);
133
134
            // Dynamic Values
135
            // Only append selected ids, load full section information asynchronously
136
            $label = Widget::Label(__('Dynamic Values'));
137
            $label->setAttribute('class', 'column');
138
            $label->appendChild(new XMLElement('i', __('Optional')));
139
140
            $options = array(
141
                array('', false, __('None'))
142
            );
143
144
            if ($this->get('dynamic_options')) {
145
                $options[] = array($this->get('dynamic_options'));
146
            }
147
148
            $label->appendChild(
149
                Widget::Select('fields[' . $this->get('sortorder') . '][dynamic_options]', $options, array(
150
                    'class' => 'js-fetch-sections'
151
                ))
152
            );
153
154 View Code Duplication
            if (isset($errors['dynamic_options'])) {
155
                $div->appendChild(Widget::Error($label, $errors['dynamic_options']));
156
            } else {
157
                $div->appendChild($label);
158
            }
159
160
            $wrapper->appendChild($div);
161
162
            // Other settings
163
            $div = new XMLElement('div', null, array('class' => 'two columns'));
164
165
            // Allow selection of multiple items
166
            $this->createCheckboxSetting($div, 'allow_multiple_selection', __('Allow selection of multiple options'));
167
168
            // Sort options?
169
            $this->createCheckboxSetting($div, 'sort_options', __('Sort all options alphabetically'));
170
171
            $wrapper->appendChild($div);
172
173
            // Associations
174
            $fieldset = new XMLElement('fieldset');
175
            $this->appendAssociationInterfaceSelect($fieldset);
176
            $this->appendShowAssociationCheckbox($fieldset);
177
            $wrapper->appendChild($fieldset);
178
179
            // Requirements and table display
180
            $this->appendStatusFooter($wrapper);
181
        }
182
183
        /*-------------------------------------------------------------------------
184
            Settings:
185
        -------------------------------------------------------------------------*/
186
187
        public function checkFields(array &$errors, $checkForDuplicates = true)
188
        {
189
            if (!is_array($errors)) {
190
                $errors = array();
191
            }
192
193
            if ($this->get('static_options') === '' && ($this->get('dynamic_options') === '' || $this->get('dynamic_options') === 'none')) {
194
                $errors['dynamic_options'] = __('At least one source must be specified, dynamic or static.');
195
            }
196
197
            Field::checkFields($errors, $checkForDuplicates);
198
        }
199
200
        public function commit()
201
        {
202
            if (!Field::commit()) {
203
                return false;
204
            }
205
206
            $id = $this->get('id');
207
208
            if ($id === false) {
209
                return false;
210
            }
211
212
            $fields = array();
213
214
            if ($this->get('static_options') !== '') {
215
                $fields['static_options'] = $this->get('static_options');
216
            }
217
218
            if ($this->get('dynamic_options') !== '') {
219
                $fields['dynamic_options'] = $this->get('dynamic_options');
220
            }
221
222
            $fields['allow_multiple_selection'] = ($this->get('allow_multiple_selection') ? $this->get('allow_multiple_selection') : 'no');
223
            $fields['sort_options'] = $this->get('sort_options') === 'yes' ? 'yes' : 'no';
224
225
            if (!FieldManager::saveSettings($id, $fields)) {
226
                return false;
227
            }
228
229
            SectionManager::removeSectionAssociation($id);
230
231
            // Dynamic Options isn't an array like in Select Box Link
232
            $field_id = $this->get('dynamic_options');
233
234 View Code Duplication
            if (!is_null($field_id) && is_numeric($field_id)) {
235
                SectionManager::createSectionAssociation(null, $id, (int)$field_id,
236
                    $this->get('show_association') === 'yes' ? true : false, $this->get('association_ui'),
237
                    $this->get('association_editor'));
238
            }
239
240
            return true;
241
        }
242
243
        public function displayPublishPanel(
244
            XMLElement &$wrapper,
245
            $data = null,
246
            $flagWithError = null,
247
            $fieldnamePrefix = null,
248
            $fieldnamePostfix = null,
249
            $entry_id = null
250
        ) {
251
            $states = $this->getToggleStates();
252
            $value = isset($data['value']) ? $data['value'] : null;
253
254
            if (!is_array($value)) {
255
                $value = array($value);
256
            }
257
258
            $options = array(
259
                array(null, false, null)
260
            );
261
262
            foreach ($states as $handle => $v) {
263
                $options[] = array(General::sanitize($v), in_array($v, $value), General::sanitize($v));
264
            }
265
266
            $fieldname = 'fields' . $fieldnamePrefix . '[' . $this->get('element_name') . ']' . $fieldnamePostfix;
267
268
            if ($this->get('allow_multiple_selection') === 'yes') {
269
                $fieldname .= '[]';
270
            }
271
272
            $label = Widget::Label($this->get('label'));
273
274
            if ($this->get('required') !== 'yes') {
275
                $label->appendChild(new XMLElement('i', __('Optional')));
276
            }
277
278
            $label->appendChild(Widget::Select($fieldname, $options,
279
                ($this->get('allow_multiple_selection') === 'yes' ? array(
280
                    'multiple' => 'multiple',
281
                    'size' => count($options)
282
                ) : null)));
283
284
            if ($flagWithError !== null) {
285
                $wrapper->appendChild(Widget::Error($label, $flagWithError));
286
            } else {
287
                $wrapper->appendChild($label);
288
            }
289
        }
290
291
        public function getToggleStates()
292
        {
293
            $values = preg_split('/,\s*/i', $this->get('static_options'), -1, PREG_SPLIT_NO_EMPTY);
294
295
            if ($this->get('dynamic_options') !== '') {
296
                $this->findAndAddDynamicOptions($values);
297
            }
298
299
            $values = array_map('trim', $values);
300
            // Fixes issues on PHP5.3. RE: #1773 ^BA
301
            if (empty($values)) {
302
                return $values;
303
            }
304
305
            $states = array_combine($values, $values);
306
307
            if ($this->get('sort_options') === 'yes') {
308
                natsort($states);
309
            }
310
311
            return $states;
312
        }
313
314
        /*-------------------------------------------------------------------------
315
            Publish:
316
        -------------------------------------------------------------------------*/
317
318
        public function findAndAddDynamicOptions(&$values)
319
        {
320
            if (!is_array($values)) {
321
                $values = array();
322
            }
323
324
            $results = false;
325
326
            // Fixes #1802
327
            if (!Symphony::Database()->tableExists('tbl_entries_data_' . $this->get('dynamic_options'))) {
328
                return;
329
            }
330
331
            // Ensure that the table has a 'value' column
332 View Code Duplication
            if ((boolean)Symphony::Database()->fetchVar('Field', 0, sprintf(
333
                "SHOW COLUMNS FROM `tbl_entries_data_%d` LIKE '%s'",
334
                $this->get('dynamic_options'),
335
                'value'
336
            ))
337
            ) {
338
                $results = Symphony::Database()->fetchCol('value', sprintf(
339
                    "SELECT DISTINCT `value`
340
                FROM `tbl_entries_data_%d`
341
                ORDER BY `value` ASC",
342
                    $this->get('dynamic_options')
343
                ));
344
            }
345
346
            // In the case of a Upload field, use 'file' instead of 'value'
347 View Code Duplication
            if (($results === false) && (boolean)Symphony::Database()->fetchVar('Field', 0, sprintf(
348
                    "SHOW COLUMNS FROM `tbl_entries_data_%d` LIKE '%s'",
349
                    $this->get('dynamic_options'),
350
                    'file'
351
                ))
352
            ) {
353
                $results = Symphony::Database()->fetchCol('file', sprintf(
354
                    "SELECT DISTINCT `file`
355
                FROM `tbl_entries_data_%d`
356
                ORDER BY `file` ASC",
357
                    $this->get('dynamic_options')
358
                ));
359
            }
360
361
            if ($results) {
362
                if ($this->get('sort_options') === 'no') {
363
                    natsort($results);
364
                }
365
366
                $values = array_merge($values, $results);
367
            }
368
        }
369
370
        public function checkPostFieldData($data, &$message, $entry_id = null)
371
        {
372
            return Field::checkPostFieldData($data, $message, $entry_id);
373
        }
374
375
        public function prepareTextValue($data, $entry_id = null)
376
        {
377
            $value = $this->prepareExportValue($data, ExportableField::LIST_OF + ExportableField::VALUE, $entry_id);
378
379
            return implode(', ', $value);
380
        }
381
382
        /*-------------------------------------------------------------------------
383
            Output:
384
        -------------------------------------------------------------------------*/
385
386
        /**
387
         * Give the field some data and ask it to return a value using one of many
388
         * possible modes.
389
         *
390
         * @param mixed $data
391
         * @param integer $mode
392
         * @param integer $entry_id
393
         * @return array
394
         */
395
        public function prepareExportValue($data, $mode, $entry_id = null)
396
        {
397
            $modes = (object)$this->getExportModes();
398
399
            if (isset($data['handle']) && is_array($data['handle']) === false) {
400
                $data['handle'] = array(
401
                    $data['handle']
402
                );
403
            }
404
405 View Code Duplication
            if (isset($data['value']) && is_array($data['value']) === false) {
406
                $data['value'] = array(
407
                    $data['value']
408
                );
409
            }
410
411
            // Handle => Value pairs:
412
            if ($mode === $modes->listHandleToValue) {
413
                return isset($data['handle'], $data['value'])
414
                    ? array_combine($data['handle'], $data['value'])
415
                    : array();
416
417
                // Array of handles:
418
            } elseif ($mode === $modes->listHandle) {
419
                return isset($data['handle'])
420
                    ? $data['handle']
421
                    : array();
422
423
                // Array of values:
424 View Code Duplication
            } elseif ($mode === $modes->listValue || $mode === $modes->getPostdata) {
425
                return isset($data['value'])
426
                    ? $data['value']
427
                    : array();
428
            }
429
        }
430
431
        /*-------------------------------------------------------------------------
432
            Import:
433
        -------------------------------------------------------------------------*/
434
435
        /**
436
         * Return a list of supported export modes for use with `prepareExportValue`.
437
         *
438
         * @return array
439
         */
440 View Code Duplication
        public function getExportModes()
441
        {
442
            return array(
443
                'listHandle' => ExportableField::LIST_OF
444
                    + ExportableField::HANDLE,
445
                'listValue' => ExportableField::LIST_OF
446
                    + ExportableField::VALUE,
447
                'listHandleToValue' => ExportableField::LIST_OF
448
                    + ExportableField::HANDLE
449
                    + ExportableField::VALUE,
450
                'getPostdata' => ExportableField::POSTDATA
451
            );
452
        }
453
454
        /*-------------------------------------------------------------------------
455
            Export:
456
        -------------------------------------------------------------------------*/
457
458
        public function prepareImportValue($data, $mode, $entry_id = null)
459
        {
460
            $message = $status = null;
461
            $modes = (object)$this->getImportModes();
462
463
            if (!is_array($data)) {
464
                $data = array($data);
465
            }
466
467
            if ($mode === $modes->getValue) {
468
                if ($this->get('allow_multiple_selection') === 'no') {
469
                    $data = array(implode('', $data));
470
                }
471
472
                return $data;
473
            } elseif ($mode === $modes->getPostdata) {
474
                return $this->processRawFieldData($data, $status, $message, true, $entry_id);
475
            }
476
477
            return null;
478
        }
479
480
        public function processRawFieldData($data, &$status, &$message = null, $simulate = false, $entry_id = null)
481
        {
482
            $status = self::__OK__;
483
484
            if (!is_array($data)) {
485
                return array(
486
                    'value' => $data,
487
                    'handle' => Lang::createHandle($data)
488
                );
489
            }
490
491
            if (empty($data)) {
492
                return null;
493
            }
494
495
            $result = array(
496
                'value' => array(),
497
                'handle' => array()
498
            );
499
500 View Code Duplication
            foreach ($data as $value) {
501
                $result['value'][] = $value;
502
                $result['handle'][] = Lang::createHandle($value);
503
            }
504
505
            return $result;
506
        }
507
508
        /*-------------------------------------------------------------------------
509
            Filtering:
510
        -------------------------------------------------------------------------*/
511
512 View Code Duplication
        public function displayFilteringOptions(XMLElement &$wrapper)
513
        {
514
            $existing_options = $this->getToggleStates();
515
516
            if (is_array($existing_options) && !empty($existing_options)) {
517
                $optionlist = new XMLElement('ul');
518
                $optionlist->setAttribute('class', 'tags');
519
                $optionlist->setAttribute('data-interactive', 'data-interactive');
520
521
                foreach ($existing_options as $option) {
522
                    $optionlist->appendChild(
523
                        new XMLElement('li', General::sanitize($option))
524
                    );
525
                };
526
527
                $wrapper->appendChild($optionlist);
528
            }
529
        }
530
531
        /*-------------------------------------------------------------------------
532
            Grouping:
533
        -------------------------------------------------------------------------*/
534
535 View Code Duplication
        public function groupRecords($records)
536
        {
537
            if (!is_array($records) || empty($records)) {
538
                return;
539
            }
540
541
            $groups = array($this->get('element_name') => array());
542
543
            foreach ($records as $r) {
544
                $data = $r->getData($this->get('id'));
545
                $value = General::sanitize($data['value']);
546
547
                if (!isset($groups[$this->get('element_name')][$data['handle']])) {
548
                    $groups[$this->get('element_name')][$data['handle']] = array(
549
                        'attr' => array('handle' => $data['handle'], 'value' => $value),
550
                        'records' => array(),
551
                        'groups' => array()
552
                    );
553
                }
554
555
                $groups[$this->get('element_name')][$data['handle']]['records'][] = $r;
556
            }
557
558
            return $groups;
559
        }
560
561
        /*-------------------------------------------------------------------------
562
            Events:
563
        -------------------------------------------------------------------------*/
564
565
        public function getExampleFormMarkup()
566
        {
567
            $states = $this->getToggleStates();
568
569
            $options = array();
570
571
            foreach ($states as $handle => $v) {
572
                $options[] = array($v, null, $v);
573
            }
574
575
            $fieldname = 'fields[' . $this->get('element_name') . ']';
576
577
            if ($this->get('allow_multiple_selection') === 'yes') {
578
                $fieldname .= '[]';
579
            }
580
581
            $label = Widget::Label($this->get('label'));
582
            $label->appendChild(Widget::Select($fieldname, $options,
583
                ($this->get('allow_multiple_selection') === 'yes' ? array('multiple' => 'multiple') : null)));
584
585
            return $label;
586
        }
587
    }
588