EmbedButtonForm::form()   B
last analyzed

Complexity

Conditions 5
Paths 16

Size

Total Lines 80
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 56
nc 16
nop 2
dl 0
loc 80
rs 8.4041
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Drupal\embed\Form;
4
5
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
6
use Drupal\Core\Ajax\AjaxResponse;
7
use Drupal\Core\Ajax\ReplaceCommand;
8
use Drupal\Core\Config\ConfigFactoryInterface;
9
use Drupal\Core\Entity\EntityForm;
10
use Drupal\Core\Entity\EntityTypeManagerInterface;
11
use Drupal\Core\Entity\EntityTypeInterface;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\embed\EmbedType\EmbedTypeManager;
14
use Symfony\Component\DependencyInjection\ContainerInterface;
15
16
/**
17
 * Form controller for embed button forms.
18
 */
19
class EmbedButtonForm extends EntityForm {
20
21
  /**
22
   * The entity type manager service.
23
   *
24
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
25
   */
26
  protected $entityTypeManager;
27
28
  /**
29
   * The embed type plugin manager.
30
   *
31
   * @var \Drupal\embed\EmbedType\EmbedTypeManager
32
   */
33
  protected $embedTypeManager;
34
35
  /**
36
   * Constructs a new EmbedButtonForm.
37
   *
38
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
39
   *   The entity type manager service.
40
   * @param \Drupal\embed\EmbedType\EmbedTypeManager $embed_type_manager
41
   *   The embed type plugin manager.
42
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
43
   *   The config factory.
44
   */
45
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EmbedTypeManager $embed_type_manager, ConfigFactoryInterface $config_factory) {
46
    $this->entityTypeManager = $entity_type_manager;
47
    $this->embedTypeManager = $embed_type_manager;
48
    $this->configFactory = $config_factory;
49
  }
50
51
  /**
52
   * {@inheritdoc}
53
   */
54
  public static function create(ContainerInterface $container) {
55
    return new static(
56
      $container->get('entity_type.manager'),
57
      $container->get('plugin.manager.embed.type'),
58
      $container->get('config.factory')
59
    );
60
  }
61
62
  /**
63
   * {@inheritdoc}
64
   */
65
  public function form(array $form, FormStateInterface $form_state) {
66
    $form = parent::form($form, $form_state);
67
68
    /** @var \Drupal\embed\EmbedButtonInterface $button */
69
    $button = $this->entity;
70
    $form_state->setTemporaryValue('embed_button', $button);
71
72
    $form['label'] = [
73
      '#title' => $this->t('Label'),
74
      '#type' => 'textfield',
75
      '#default_value' => $button->label(),
76
      '#description' => $this->t('The human-readable name of this embed button. This text will be displayed when the user hovers over the CKEditor button. This name must be unique.'),
77
      '#required' => TRUE,
78
      '#size' => 30,
79
    ];
80
81
    $form['id'] = [
82
      '#type' => 'machine_name',
83
      '#default_value' => $button->id(),
84
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
85
      '#disabled' => !$button->isNew(),
86
      '#machine_name' => [
87
        'exists' => ['Drupal\embed\Entity\EmbedButton', 'load'],
88
      ],
89
      '#description' => $this->t('A unique machine-readable name for this embed button. It must only contain lowercase letters, numbers, and underscores.'),
90
    ];
91
92
    $form['type_id'] = [
93
      '#type' => 'select',
94
      '#title' => $this->t('Embed type'),
95
      '#options' => $this->embedTypeManager->getDefinitionOptions(),
96
      '#default_value' => $button->getTypeId(),
97
      '#required' => TRUE,
98
      '#ajax' => [
99
        'callback' => '::updateTypeSettings',
100
        'effect' => 'fade',
101
      ],
102
      '#disabled' => !$button->isNew(),
103
    ];
104
    if (count($form['type_id']['#options']) == 0) {
105
      drupal_set_message($this->t('No embed types found.'), 'warning');
106
    }
107
108
    // Add the embed type plugin settings.
109
    $form['type_settings'] = [
110
      '#type' => 'container',
111
      '#tree' => TRUE,
112
      '#prefix' => '<div id="embed-type-settings-wrapper">',
113
      '#suffix' => '</div>',
114
    ];
115
116
    try {
117
      if ($plugin = $button->getTypePlugin()) {
118
        $form['type_settings'] = $plugin->buildConfigurationForm($form['type_settings'], $form_state);
119
      }
120
    }
121
    catch (PluginNotFoundException $exception) {
0 ignored issues
show
Bug introduced by
The class Drupal\Component\Plugin\...PluginNotFoundException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
122
      drupal_set_message($exception->getMessage(), 'error');
123
      watchdog_exception('embed', $exception);
124
      $form['type_id']['#disabled'] = FALSE;
125
    }
126
127
    $config = $this->config('embed.settings');
128
    $upload_location = $config->get('file_scheme') . '://' . $config->get('upload_directory') . '/';
129
    $form['icon_file'] = [
130
      '#title' => $this->t('Button icon'),
131
      '#type' => 'managed_file',
132
      '#description' => $this->t('Icon for the button to be shown in CKEditor toolbar. Leave empty to use the default Entity icon.'),
133
      '#upload_location' => $upload_location,
134
      '#upload_validators' => [
135
        'file_validate_extensions' => ['gif png jpg jpeg'],
136
        'file_validate_image_resolution' => ['32x32', '16x16'],
137
      ],
138
    ];
139
    if ($file = $button->getIconFile()) {
140
      $form['icon_file']['#default_value'] = ['target_id' => $file->id()];
141
    }
142
143
    return $form;
144
  }
145
146
  /**
147
   * {@inheritdoc}
148
   */
149
  public function validateForm(array &$form, FormStateInterface $form_state) {
150
    parent::validateForm($form, $form_state);
151
152
    /** @var \Drupal\embed\EmbedButtonInterface $button */
153
    $button = $this->entity;
154
155
    // Run embed type plugin validation.
156
    if ($plugin = $button->getTypePlugin()) {
157
      $plugin_form_state = clone $form_state;
158
      $plugin_form_state->setValues($button->getTypeSettings());
159
      $plugin->validateConfigurationForm($form['type_settings'], $plugin_form_state);
160
      if ($errors = $plugin_form_state->getErrors()) {
161
        foreach ($errors as $name => $error) {
162
          $form_state->setErrorByName($name, $error);
163
        }
164
      }
165
      $form_state->setValue('type_settings', $plugin_form_state->getValues());
166
    }
167
  }
168
169
  /**
170
   * {@inheritdoc}
171
   */
172
  public function save(array $form, FormStateInterface $form_state) {
173
    /** @var \Drupal\embed\EmbedButtonInterface $button */
174
    $button = $this->entity;
175
176
    // Run embed type plugin submission.
177
    $plugin = $button->getTypePlugin();
178
    $plugin_form_state = clone $form_state;
179
    $plugin_form_state->setValues($button->getTypeSettings());
180
    $plugin->submitConfigurationForm($form['type_settings'], $plugin_form_state);
181
    $form_state->setValue('type_settings', $plugin->getConfiguration());
182
    $button->set('type_settings', $plugin->getConfiguration());
183
184
    $icon_fid = $form_state->getValue(['icon_file', '0']);
185
    // If a file was uploaded to be used as the icon, get its UUID to be stored
186
    // in the config entity.
187
    if (!empty($icon_fid) && $file = $this->entityTypeManager->getStorage('file')->load($icon_fid)) {
188
      $button->set('icon_uuid', $file->uuid());
189
    }
190
    else {
191
      $button->set('icon_uuid', NULL);
192
    }
193
194
    $status = $button->save();
195
196
    $t_args = ['%label' => $button->label()];
197
198
    if ($status == SAVED_UPDATED) {
199
      drupal_set_message($this->t('The embed button %label has been updated.', $t_args));
200
    }
201
    elseif ($status == SAVED_NEW) {
202
      drupal_set_message($this->t('The embed button %label has been added.', $t_args));
203
      $context = array_merge($t_args, ['link' => $button->link($this->t('View'), 'collection')]);
204
      $this->logger('embed')->notice('Added embed button %label.', $context);
205
    }
206
207
    $form_state->setRedirectUrl($button->urlInfo('collection'));
208
  }
209
210
  /**
211
   * Ajax callback to update the form fields which depend on embed type.
212
   *
213
   * @param array $form
214
   *   The build form.
215
   * @param \Drupal\Core\Form\FormStateInterface $form_state
216
   *   The form state.
217
   *
218
   * @return \Drupal\Core\Ajax\AjaxResponse
219
   *   Ajax response with updated options for the embed type.
220
   */
221
  public function updateTypeSettings(array &$form, FormStateInterface $form_state) {
222
    $response = new AjaxResponse();
223
224
    // Update options for entity type bundles.
225
    $response->addCommand(new ReplaceCommand(
226
      '#embed-type-settings-wrapper',
227
      $form['type_settings']
228
    ));
229
230
    return $response;
231
  }
232
233
}
234