FormHelper.php 11.5 KB
Newer Older
1 2
<?php

3
namespace Drupal\simple_sitemap\Form;
4

Pawel G's avatar
Pawel G committed
5
use Drupal\Core\Form\FormStateInterface;
6
use Drupal\Core\StringTranslation\StringTranslationTrait;
7
use Drupal\simple_sitemap\EntityHelper;
Pawel G's avatar
Pawel G committed
8 9
use Drupal\simple_sitemap\Simplesitemap;
use Drupal\Core\Session\AccountProxyInterface;
10

11
/**
Pawel G's avatar
Pawel G committed
12
 * Class FormHelper
13
 * @package Drupal\simple_sitemap\Form
14
 */
15
class FormHelper {
16
  use StringTranslationTrait;
17

Pawel G's avatar
Pawel G committed
18 19 20 21
  const PRIORITY_DEFAULT = 0.5;
  const PRIORITY_HIGHEST = 10;
  const PRIORITY_DIVIDER = 10;

Pawel G's avatar
Pawel G committed
22 23 24
  /**
   * @var \Drupal\simple_sitemap\Simplesitemap
   */
25
  protected $generator;
Pawel G's avatar
Pawel G committed
26 27 28 29

  /**
   * @var \Drupal\simple_sitemap\EntityHelper
   */
30
  protected $entityHelper;
Pawel G's avatar
Pawel G committed
31 32 33 34

  /**
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
35
  protected $currentUser;
Pawel G's avatar
Pawel G committed
36 37 38 39

  /**
   * @var \Drupal\Core\Form\FormState
   */
40
  protected $formState;
41

Pawel G's avatar
Pawel G committed
42 43 44
  /**
   * @var string|null
   */
Pawel G's avatar
Pawel G committed
45
  protected $entityCategory;
Pawel G's avatar
Pawel G committed
46 47 48 49

  /**
   * @var string
   */
50
  protected $entityTypeId;
Pawel G's avatar
Pawel G committed
51 52 53 54

  /**
   * @var string
   */
55
  protected $bundleName;
Pawel G's avatar
Pawel G committed
56 57 58 59

  /**
   * @var string
   */
60
  protected $instanceId;
61

62
  protected static $allowedFormOperations = [
63 64 65
    'default',
    'edit',
    'add',
Pawel G's avatar
Pawel G committed
66
    'register',
67 68
  ];

69
  protected static $valuesToCheck = [
70 71
    'simple_sitemap_index_content',
    'simple_sitemap_priority',
Pawel G's avatar
Pawel G committed
72
    'simple_sitemap_regenerate_now',
73
  ];
74

75
  /**
76 77 78 79
   * FormHelper constructor.
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
80
   */
Pawel G's avatar
Pawel G committed
81 82
  public function __construct(
    Simplesitemap $generator,
83
    EntityHelper $entityHelper,
Pawel G's avatar
Pawel G committed
84 85
    AccountProxyInterface $current_user
  ) {
86
    $this->generator = $generator;
87
    $this->entityHelper = $entityHelper;
88
    $this->currentUser = $current_user;
89
  }
Pawel G's avatar
Pawel G committed
90

91
  /**
Pawel G's avatar
Pawel G committed
92 93
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @return bool
94
   */
Pawel G's avatar
Pawel G committed
95
  public function processForm(FormStateInterface $form_state) {
Pawel G's avatar
Pawel G committed
96
    $this->formState = $form_state;
97
    $this->cleanUpFormInfo();
98
    $this->getEntityDataFromFormEntity();
Pawel G's avatar
Pawel G committed
99
    return $this->supports();
100 101
  }

102
  /**
Pawel G's avatar
Pawel G committed
103
   * @param string $entity_category
104 105
   * @return $this
   */
106 107
  public function setEntityCategory($entity_category) {
    $this->entityCategory = $entity_category;
108
    return $this;
109 110
  }

111
  /**
112
   * @return null|string
113
   */
114 115 116 117 118 119 120 121
  public function getEntityCategory() {
    return $this->entityCategory;
  }

  /**
 * @param string $entity_type_id
 * @return $this
 */
122 123
  public function setEntityTypeId($entity_type_id) {
    $this->entityTypeId = $entity_type_id;
124
    return $this;
125 126
  }

127 128 129 130 131 132 133
  /**
   * @return string
   */
  public function getEntityTypeId() {
    return $this->entityTypeId;
  }

134
  /**
Pawel G's avatar
Pawel G committed
135
   * @param string $bundle_name
136 137
   * @return $this
   */
138 139
  public function setBundleName($bundle_name) {
    $this->bundleName = $bundle_name;
140
    return $this;
141 142
  }

143 144 145 146 147 148 149
  /**
   * @return string
   */
  public function getBundleName() {
    return $this->bundleName;
  }

150
  /**
Pawel G's avatar
Pawel G committed
151
   * @param string $instance_id
152 153
   * @return $this
   */
154 155
  public function setInstanceId($instance_id) {
    $this->instanceId = $instance_id;
156
    return $this;
157 158
  }

159 160 161 162 163 164 165
  /**
   * @return string
   */
  public function getInstanceId() {
    return $this->instanceId;
  }

Pawel G's avatar
Pawel G committed
166
  /**
Pawel G's avatar
Pawel G committed
167
   * @return bool
Pawel G's avatar
Pawel G committed
168
   */
Pawel G's avatar
Pawel G committed
169
  protected function supports() {
Pawel G's avatar
Pawel G committed
170 171

    // Do not alter the form if user lacks certain permissions.
Pawel G's avatar
Pawel G committed
172
    if (!$this->currentUser->hasPermission('administer sitemap settings')) {
Pawel G's avatar
Pawel G committed
173
      return FALSE;
Pawel G's avatar
Pawel G committed
174
    }
Pawel G's avatar
Pawel G committed
175 176

    // Do not alter the form if it is irrelevant to sitemap generation.
177
    elseif (empty($this->getEntityCategory())) {
Pawel G's avatar
Pawel G committed
178
      return FALSE;
Pawel G's avatar
Pawel G committed
179
    }
Pawel G's avatar
Pawel G committed
180 181

    // Do not alter the form if entity is not enabled in sitemap settings.
182
    elseif (!$this->generator->entityTypeIsEnabled($this->getEntityTypeId())) {
Pawel G's avatar
Pawel G committed
183
      return FALSE;
Pawel G's avatar
Pawel G committed
184
    }
Pawel G's avatar
Pawel G committed
185 186 187

    // Do not alter the form, if sitemap is disabled for the entity type of this
    // entity instance.
188 189
    elseif ($this->getEntityCategory() == 'instance'
      && !$this->generator->bundleIsIndexed($this->getEntityTypeId(), $this->getBundleName())) {
Pawel G's avatar
Pawel G committed
190
      return FALSE;
Pawel G's avatar
Pawel G committed
191
    }
Pawel G's avatar
Pawel G committed
192 193

    return TRUE;
Pawel G's avatar
Pawel G committed
194 195
  }

196
  /**
Pawel G's avatar
Pawel G committed
197
   * @param array $form_fragment
198
   */
Pawel G's avatar
Pawel G committed
199
  public function displayRegenerateNow(&$form_fragment) {
Pawel G's avatar
Pawel G committed
200
    $form_fragment['simple_sitemap_regenerate_now'] = [
201
      '#type' => 'checkbox',
202 203
      '#title' => $this->t('Regenerate sitemap after hitting <em>Save</em>'),
      '#description' => $this->t('This setting will regenerate the whole sitemap including the above changes.'),
204
      '#default_value' => FALSE,
Pawel G's avatar
Pawel G committed
205
    ];
Pawel G's avatar
Pawel G committed
206
    if ($this->generator->getSetting('cron_generate')) {
207
      $form_fragment['simple_sitemap_regenerate_now']['#description'] .= '</br>' . $this->t('Otherwise the sitemap will be regenerated during a future cron run.');
208 209
    }
  }
210 211

  /**
212
   * @param array $form_fragment
213 214 215
   * @param bool $multiple
   * @return $this
   */
216
  public function displayEntitySettings(&$form_fragment, $multiple = FALSE) {
217
    $prefix = $multiple ? $this->getEntityTypeId() . '_' : '';
218

219 220 221
    if ($this->getEntityCategory() == 'instance') {
      $bundle_settings = $this->generator->getBundleSettings($this->getEntityTypeId(), $this->getBundleName());
      $settings = NULL !== $this->getInstanceId() ? $this->generator->getEntityInstanceSettings($this->getEntityTypeId(), $this->getInstanceId()) : $bundle_settings;
222
    }
223
    else {
224
      $settings = $this->generator->getBundleSettings($this->getEntityTypeId(), $this->getBundleName());
225 226 227
    }
    $index = isset($settings['index']) ? $settings['index'] : 0;
    $priority = isset($settings['priority']) ? $settings['priority'] : self::PRIORITY_DEFAULT;
228
    $bundle_name = !empty($this->getBundleName()) ? $this->getBundleName() : $this->t('undefined');
229 230 231 232 233 234

    if (!$multiple) {
      $form_fragment[$prefix . 'simple_sitemap_index_content'] = [
        '#type' => 'radios',
        '#default_value' => $index,
        '#options' => [
235 236
          0 => $this->getEntityCategory() == 'instance' ? $this->t('Do not index this @bundle entity', ['@bundle' => $bundle_name]) : $this->t('Do not index entities of this type'),
          1 => $this->getEntityCategory() == 'instance' ? $this->t('Index this @bundle entity', ['@bundle' => $bundle_name]) : $this->t('Index entities of this type'),
Pawel G's avatar
Pawel G committed
237
        ],
238
      ];
239
      if ($this->getEntityCategory() == 'instance' && isset($bundle_settings['index'])) {
240
        $form_fragment[$prefix . 'simple_sitemap_index_content']['#options'][$bundle_settings['index']] .= ' <em>(' . $this->t('Default') . ')</em>';
241 242 243
      }
    }

244
    if ($this->getEntityCategory() == 'instance') {
245
      $priority_description = $this->t('The priority this @bundle entity will have in the eyes of search engine bots.', ['@bundle' => $bundle_name]);
Pawel G's avatar
Pawel G committed
246 247
    }
    else {
248
      $priority_description = $this->t('The priority entities of this type will have in the eyes of search engine bots.');
Pawel G's avatar
Pawel G committed
249
    }
250 251
    $form_fragment[$prefix . 'simple_sitemap_priority'] = [
      '#type' => 'select',
252
      '#title' => $this->t('Priority'),
253 254
      '#description' => $priority_description,
      '#default_value' => $priority,
255
      '#options' => $this->getPrioritySelectValues(),
256
    ];
257
    if ($this->getEntityCategory() == 'instance' && isset($bundle_settings['priority'])) {
258
      $form_fragment[$prefix . 'simple_sitemap_priority']['#options'][$this->formatPriority($bundle_settings['priority'])] .= ' (' . $this->t('Default') . ')';
259
    }
Pawel G's avatar
Pawel G committed
260
    return $this;
261 262 263 264 265 266 267
  }

  /**
   * Checks if this particular form is a bundle form, or a bundle instance form
   * and gathers sitemap settings from the database.
   *
   * @return bool
Pawel G's avatar
Pawel G committed
268
   *   TRUE if this is a bundle or bundle instance form, FALSE otherwise.
269
   */
270
  protected function getEntityDataFromFormEntity() {
271 272
    $form_entity = $this->getFormEntity();
    if ($form_entity !== FALSE) {
273
      $entity_type_id = $form_entity->getEntityTypeId();
Pawel G's avatar
Pawel G committed
274
      $sitemap_entity_types = $this->entityHelper->getSupportedEntityTypes();
275
      if (isset($sitemap_entity_types[$entity_type_id])) {
276
        $this->setEntityCategory('instance');
277 278
      }
      else {
Pawel G's avatar
Pawel G committed
279 280 281 282 283
        /**
         * @var \Drupal\Core\Entity\EntityType $sitemap_entity_type
         */
        foreach ($sitemap_entity_types as $sitemap_entity_type) {
          if ($sitemap_entity_type->getBundleEntityType() == $entity_type_id) {
284
            $this->setEntityCategory('bundle');
285
            break;
286 287 288
          }
        }
      }
289

290
      // Menu fix.
291
      $this->setEntityCategory(NULL === $this->getEntityCategory() && $entity_type_id == 'menu' ? 'bundle' : $this->getEntityCategory());
292

293
      switch ($this->getEntityCategory()) {
294
        case 'bundle':
295 296 297
          $this->setEntityTypeId($this->entityHelper->getBundleEntityTypeId($form_entity));
          $this->setBundleName($form_entity->id());
          $this->setInstanceId(NULL);
298 299 300
          break;

        case 'instance':
301 302
          $this->setEntityTypeId($entity_type_id);
          $this->setBundleName($this->entityHelper->getEntityInstanceBundleName($form_entity));
Pawel G's avatar
Pawel G committed
303
          // New menu link's id is '' instead of NULL, hence checking for empty.
304
          $this->setInstanceId(!empty($form_entity->id()) ? $form_entity->id() : NULL);
305 306 307 308 309 310
          break;

        default:
          return FALSE;
      }
      return TRUE;
311 312 313 314 315 316 317
    }
    return FALSE;
  }

  /**
   * Gets the object entity of the form if available.
   *
Pawel G's avatar
Pawel G committed
318
   * @return \Drupal\Core\Entity\Entity|false
Pawel G's avatar
Pawel G committed
319 320
   *   Entity or FALSE if non-existent or if form operation is
   *   'delete'.
321
   */
322
  protected function getFormEntity() {
323
    $form_object = $this->formState->getFormObject();
324
    if (NULL !== $form_object
325
      && method_exists($form_object, 'getOperation')
326
      && method_exists($form_object, 'getEntity')
327
      && in_array($form_object->getOperation(), self::$allowedFormOperations)) {
328 329 330 331 332
      return $form_object->getEntity();
    }
    return FALSE;
  }

333 334 335 336 337 338 339 340 341 342 343 344 345
  /**
   * Removes gathered form information from service object.
   *
   * Needed because this service may contain form info from the previous
   * operation when revived from the container.
   */
  protected function cleanUpFormInfo() {
    $this->entityCategory = NULL;
    $this->entityTypeId = NULL;
    $this->bundleName = NULL;
    $this->instanceId = NULL;
  }

346 347 348 349
  /**
   * Gets new entity Id after entity creation.
   * To be used in an entity form submit.
   *
Pawel G's avatar
Pawel G committed
350
   * @return int
Pawel G's avatar
Pawel G committed
351
   *   Entity ID.
352
   */
Pawel G's avatar
Pawel G committed
353 354
  public function getFormEntityId() {
    return $this->formState->getFormObject()->getEntity()->id();
355 356 357 358 359 360
  }

  /**
   * Checks if simple_sitemap values have been changed after submitting the form.
   * To be used in an entity form submit.
   *
361
   * @param $form
362
   * @param array $values
Pawel G's avatar
Pawel G committed
363
   *
364
   * @return bool
Pawel G's avatar
Pawel G committed
365
   *   TRUE if simple_sitemap form values have been altered by the user.
366
   */
367
  public function valuesChanged($form, array $values) {
Pawel G's avatar
Pawel G committed
368
    foreach (self::$valuesToCheck as $field_name) {
369
      if (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value']) {
370 371 372 373 374
        return TRUE;
      }
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
375 376 377 378

  /**
   * Gets the values needed to display the priority dropdown setting.
   *
379
   * @return array
Pawel G's avatar
Pawel G committed
380
   */
381
  public function getPrioritySelectValues() {
Pawel G's avatar
Pawel G committed
382
    $options = [];
Pawel G's avatar
Pawel G committed
383
    foreach (range(0, self::PRIORITY_HIGHEST) as $value) {
384
      $value = $this->formatPriority($value / self::PRIORITY_DIVIDER);
385
      $options[$value] = $value;
Pawel G's avatar
Pawel G committed
386 387 388
    }
    return $options;
  }
389

390
  /**
391
   * @param string $priority
392 393 394
   * @return string
   */
  public function formatPriority($priority) {
Pawel G's avatar
Pawel G committed
395
    return number_format((float) $priority, 1, '.', '');
396 397
  }

398
  /**
399
   * @param string|int $priority
400 401
   * @return bool
   */
402
  public static function isValidPriority($priority) {
403
    return is_numeric($priority) && $priority >= 0 && $priority <= 1;
404
  }
405
}