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

3
namespace Drupal\simple_sitemap\Form;
4

5
use Drupal\Core\StringTranslation\StringTranslationTrait;
6
use Drupal\simple_sitemap\EntityHelper;
Pawel G's avatar
Pawel G committed
7 8
use Drupal\simple_sitemap\Simplesitemap;
use Drupal\Core\Session\AccountProxyInterface;
9
use Drupal\Core\Form\FormState;
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 bool
   */
45
  protected $alteringForm = TRUE;
Pawel G's avatar
Pawel G committed
46 47 48 49

  /**
   * @var string|null
   */
50
  protected $entityCategory = NULL;
Pawel G's avatar
Pawel G committed
51 52 53 54

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

  /**
   * @var string
   */
60
  protected $bundleName;
Pawel G's avatar
Pawel G committed
61 62 63 64

  /**
   * @var string
   */
65
  protected $instanceId;
66

67
  protected static $allowedFormOperations = [
68 69 70
    'default',
    'edit',
    'add',
Pawel G's avatar
Pawel G committed
71
    'register',
72 73
  ];

74
  protected static $valuesToCheck = [
75 76
    'simple_sitemap_index_content',
    'simple_sitemap_priority',
Pawel G's avatar
Pawel G committed
77
    'simple_sitemap_regenerate_now',
78
  ];
79

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

96
  /**
Pawel G's avatar
Pawel G committed
97
   * @param \Drupal\Core\Form\FormState $form_state
98 99
   * @return $this
   */
100
  public function processForm(FormState $form_state) {
Pawel G's avatar
Pawel G committed
101
    $this->formState = $form_state;
102 103
    $this->getEntityDataFromFormEntity();
    $this->assertAlteringForm();
104
    return $this;
105 106
  }

107 108 109 110 111 112 113
  /**
   * @return bool
   */
  public function alteringForm() {
    return $this->alteringForm;
  }

114
  /**
Pawel G's avatar
Pawel G committed
115
   * @param string $entity_category
116 117
   * @return $this
   */
118 119
  public function setEntityCategory($entity_category) {
    $this->entityCategory = $entity_category;
120
    return $this;
121 122
  }

123
  /**
124
   * @return null|string
125
   */
126 127 128 129 130 131 132 133
  public function getEntityCategory() {
    return $this->entityCategory;
  }

  /**
 * @param string $entity_type_id
 * @return $this
 */
134 135
  public function setEntityTypeId($entity_type_id) {
    $this->entityTypeId = $entity_type_id;
136
    return $this;
137 138
  }

139 140 141 142 143 144 145
  /**
   * @return string
   */
  public function getEntityTypeId() {
    return $this->entityTypeId;
  }

146
  /**
Pawel G's avatar
Pawel G committed
147
   * @param string $bundle_name
148 149
   * @return $this
   */
150 151
  public function setBundleName($bundle_name) {
    $this->bundleName = $bundle_name;
152
    return $this;
153 154
  }

155 156 157 158 159 160 161
  /**
   * @return string
   */
  public function getBundleName() {
    return $this->bundleName;
  }

162
  /**
Pawel G's avatar
Pawel G committed
163
   * @param string $instance_id
164 165
   * @return $this
   */
166 167
  public function setInstanceId($instance_id) {
    $this->instanceId = $instance_id;
168
    return $this;
169 170
  }

171 172 173 174 175 176 177
  /**
   * @return string
   */
  public function getInstanceId() {
    return $this->instanceId;
  }

Pawel G's avatar
Pawel G committed
178 179 180
  /**
   *
   */
181
  protected function assertAlteringForm() {
Pawel G's avatar
Pawel G committed
182 183

    // Do not alter the form if user lacks certain permissions.
Pawel G's avatar
Pawel G committed
184
    if (!$this->currentUser->hasPermission('administer sitemap settings')) {
Pawel G's avatar
Pawel G committed
185
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
186
    }
Pawel G's avatar
Pawel G committed
187 188

    // Do not alter the form if it is irrelevant to sitemap generation.
189
    elseif (empty($this->getEntityCategory())) {
Pawel G's avatar
Pawel G committed
190
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
191
    }
Pawel G's avatar
Pawel G committed
192 193

    // Do not alter the form if entity is not enabled in sitemap settings.
194
    elseif (!$this->generator->entityTypeIsEnabled($this->getEntityTypeId())) {
Pawel G's avatar
Pawel G committed
195
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
196
    }
Pawel G's avatar
Pawel G committed
197 198 199

    // Do not alter the form, if sitemap is disabled for the entity type of this
    // entity instance.
200 201
    elseif ($this->getEntityCategory() == 'instance'
      && !$this->generator->bundleIsIndexed($this->getEntityTypeId(), $this->getBundleName())) {
Pawel G's avatar
Pawel G committed
202
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
203
    }
Pawel G's avatar
Pawel G committed
204 205
  }

206
  /**
Pawel G's avatar
Pawel G committed
207
   * @param array $form_fragment
208
   */
Pawel G's avatar
Pawel G committed
209
  public function displayRegenerateNow(&$form_fragment) {
Pawel G's avatar
Pawel G committed
210
    $form_fragment['simple_sitemap_regenerate_now'] = [
211
      '#type' => 'checkbox',
212 213
      '#title' => $this->t('Regenerate sitemap after hitting <em>Save</em>'),
      '#description' => $this->t('This setting will regenerate the whole sitemap including the above changes.'),
214
      '#default_value' => FALSE,
Pawel G's avatar
Pawel G committed
215
    ];
Pawel G's avatar
Pawel G committed
216
    if ($this->generator->getSetting('cron_generate')) {
217
      $form_fragment['simple_sitemap_regenerate_now']['#description'] .= '</br>' . $this->t('Otherwise the sitemap will be regenerated on the next cron run.');
218 219
    }
  }
220 221

  /**
222
   * @param array $form_fragment
223 224 225
   * @param bool $multiple
   * @return $this
   */
226
  public function displayEntitySettings(&$form_fragment, $multiple = FALSE) {
227
    $prefix = $multiple ? $this->getEntityTypeId() . '_' : '';
228

229 230 231
    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;
232
    }
233
    else {
234
      $settings = $this->generator->getBundleSettings($this->getEntityTypeId(), $this->getBundleName());
235 236 237
    }
    $index = isset($settings['index']) ? $settings['index'] : 0;
    $priority = isset($settings['priority']) ? $settings['priority'] : self::PRIORITY_DEFAULT;
238
    $bundle_name = !empty($this->getBundleName()) ? $this->getBundleName() : $this->t('undefined');
239 240 241 242 243 244

    if (!$multiple) {
      $form_fragment[$prefix . 'simple_sitemap_index_content'] = [
        '#type' => 'radios',
        '#default_value' => $index,
        '#options' => [
245 246
          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
247
        ],
248
      ];
249
      if ($this->getEntityCategory() == 'instance' && isset($bundle_settings['index'])) {
250
        $form_fragment[$prefix . 'simple_sitemap_index_content']['#options'][$bundle_settings['index']] .= ' <em>(' . $this->t('Default') . ')</em>';
251 252 253
      }
    }

254
    if ($this->getEntityCategory() == 'instance') {
255
      $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
256 257
    }
    else {
258
      $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
259
    }
260 261
    $form_fragment[$prefix . 'simple_sitemap_priority'] = [
      '#type' => 'select',
262
      '#title' => $this->t('Priority'),
263 264
      '#description' => $priority_description,
      '#default_value' => $priority,
265
      '#options' => $this->getPrioritySelectValues(),
266
    ];
267
    if ($this->getEntityCategory() == 'instance' && isset($bundle_settings['priority'])) {
268
      $form_fragment[$prefix . 'simple_sitemap_priority']['#options'][$this->formatPriority($bundle_settings['priority'])] .= ' (' . $this->t('Default') . ')';
269
    }
Pawel G's avatar
Pawel G committed
270
    return $this;
271 272 273 274 275 276 277
  }

  /**
   * 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
278
   *   TRUE if this is a bundle or bundle instance form, FALSE otherwise.
279
   */
280
  protected function getEntityDataFromFormEntity() {
281 282
    $form_entity = $this->getFormEntity();
    if ($form_entity !== FALSE) {
283
      $entity_type_id = $form_entity->getEntityTypeId();
284
      $sitemap_entity_types = $this->entityHelper->getSitemapEntityTypes();
285
      if (isset($sitemap_entity_types[$entity_type_id])) {
286
        $this->setEntityCategory('instance');
287 288
      }
      else {
Pawel G's avatar
Pawel G committed
289
        foreach ($sitemap_entity_types as $sitemap_entity) {
290
          if ($sitemap_entity->getBundleEntityType() == $entity_type_id) {
291
            $this->setEntityCategory('bundle');
292
            break;
293 294 295
          }
        }
      }
296

297
      // Menu fix.
298
      $this->setEntityCategory(NULL === $this->getEntityCategory() && $entity_type_id == 'menu' ? 'bundle' : $this->getEntityCategory());
299

300
      switch ($this->getEntityCategory()) {
301
        case 'bundle':
302 303 304
          $this->setEntityTypeId($this->entityHelper->getBundleEntityTypeId($form_entity));
          $this->setBundleName($form_entity->id());
          $this->setInstanceId(NULL);
305 306 307
          break;

        case 'instance':
308 309
          $this->setEntityTypeId($entity_type_id);
          $this->setBundleName($this->entityHelper->getEntityInstanceBundleName($form_entity));
Pawel G's avatar
Pawel G committed
310
          // New menu link's id is '' instead of NULL, hence checking for empty.
311
          $this->setInstanceId(!empty($form_entity->id()) ? $form_entity->id() : NULL);
312 313 314 315 316 317
          break;

        default:
          return FALSE;
      }
      return TRUE;
318 319 320 321 322 323 324
    }
    return FALSE;
  }

  /**
   * Gets the object entity of the form if available.
   *
Pawel G's avatar
Pawel G committed
325
   * @return object|false
Pawel G's avatar
Pawel G committed
326 327
   *   Entity or FALSE if non-existent or if form operation is
   *   'delete'.
328
   */
329
  protected function getFormEntity() {
330
    $form_object = $this->formState->getFormObject();
331
    if (NULL !== $form_object
332
      && method_exists($form_object, 'getEntity')
333
      && in_array($form_object->getOperation(), self::$allowedFormOperations)) {
334 335 336 337 338 339 340 341 342
      return $form_object->getEntity();
    }
    return FALSE;
  }

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

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

  /**
   * Gets the values needed to display the priority dropdown setting.
   *
372
   * @return array
Pawel G's avatar
Pawel G committed
373
   */
374
  public function getPrioritySelectValues() {
Pawel G's avatar
Pawel G committed
375
    $options = [];
Pawel G's avatar
Pawel G committed
376
    foreach (range(0, self::PRIORITY_HIGHEST) as $value) {
377
      $value = $this->formatPriority($value / self::PRIORITY_DIVIDER);
378
      $options[$value] = $value;
Pawel G's avatar
Pawel G committed
379 380 381
    }
    return $options;
  }
382

383
  /**
384
   * @param string $priority
385 386 387
   * @return string
   */
  public function formatPriority($priority) {
Pawel G's avatar
Pawel G committed
388
    return number_format((float) $priority, 1, '.', '');
389 390
  }

391
  /**
392
   * @param string|int $priority
393 394
   * @return bool
   */
395
  public static function isValidPriority($priority) {
396
    return is_numeric($priority) && $priority >= 0 && $priority <= 1;
397
  }
398
}