Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / views / src / Plugin / views / field / Serialized.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\field;
4
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
7
8 /**
9  * Field handler to show data of serialized fields.
10  *
11  * @ingroup views_field_handlers
12  *
13  * @ViewsField("serialized")
14  */
15 class Serialized extends FieldPluginBase {
16
17   /**
18    * {@inheritdoc}
19    */
20   protected function defineOptions() {
21     $options = parent::defineOptions();
22     $options['format'] = ['default' => 'unserialized'];
23     $options['key'] = ['default' => ''];
24     return $options;
25   }
26
27   /**
28    * {@inheritdoc}
29    */
30   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
31     parent::buildOptionsForm($form, $form_state);
32
33     $form['format'] = [
34       '#type' => 'select',
35       '#title' => $this->t('Display format'),
36       '#description' => $this->t('How should the serialized data be displayed. You can choose a custom array/object key or a print_r on the full output.'),
37       '#options' => [
38         'unserialized' => $this->t('Full data (unserialized)'),
39         'serialized' => $this->t('Full data (serialized)'),
40         'key' => $this->t('A certain key'),
41       ],
42       '#default_value' => $this->options['format'],
43     ];
44     $form['key'] = [
45       '#type' => 'textfield',
46       '#title' => $this->t('Which key should be displayed'),
47       '#default_value' => $this->options['key'],
48       '#states' => [
49         'visible' => [
50           ':input[name="options[format]"]' => ['value' => 'key'],
51         ],
52       ],
53     ];
54   }
55
56   /**
57    * {@inheritdoc}
58    */
59   public function validateOptionsForm(&$form, FormStateInterface $form_state) {
60     // Require a key if the format is key.
61     if ($form_state->getValue(['options', 'format']) == 'key' && $form_state->getValue(['options', 'key']) == '') {
62       $form_state->setError($form['key'], $this->t('You have to enter a key if you want to display a key of the data.'));
63     }
64   }
65
66   /**
67    * {@inheritdoc}
68    */
69   public function render(ResultRow $values) {
70     $value = $values->{$this->field_alias};
71
72     if ($this->options['format'] == 'unserialized') {
73       return $this->sanitizeValue(print_r(unserialize($value), TRUE));
74     }
75     elseif ($this->options['format'] == 'key' && !empty($this->options['key'])) {
76       $value = (array) unserialize($value);
77       return $this->sanitizeValue($value[$this->options['key']]);
78     }
79
80     return $value;
81   }
82
83 }