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

3
namespace Drupal\simple_sitemap\Form;
4

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

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

gbyte.co's avatar
gbyte.co committed
18 19 20 21
  const PRIORITY_DEFAULT = 0.5;
  const PRIORITY_HIGHEST = 10;
  const PRIORITY_DIVIDER = 10;

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

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

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

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

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

  /**
   * @var string
   */
50
  protected $entityTypeId;
gbyte.co's avatar
gbyte.co committed
51 52 53 54

  /**
   * @var string
   */
55
  protected $bundleName;
gbyte.co's avatar
gbyte.co committed
56 57 58 59

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

62 63 64 65 66 67 68 69 70 71
  /**
   * @var string
   */
  protected $variant;

  /**
   * @var array
   */
  protected $bundleSettings;

72
  protected static $allowedFormOperations = [
73 74 75
    'default',
    'edit',
    'add',
gbyte.co's avatar
gbyte.co committed
76
    'register',
77 78
  ];

79
  protected static $changefreqValues = [
80 81 82 83 84 85 86 87 88
    'always',
    'hourly',
    'daily',
    'weekly',
    'monthly',
    'yearly',
    'never',
  ];

89
  protected static $valuesToCheck = [
90
    'simple_sitemap_variant',
91 92
    'simple_sitemap_index_content',
    'simple_sitemap_priority',
93
    'simple_sitemap_changefreq',
94
    'simple_sitemap_include_images',
gbyte.co's avatar
gbyte.co committed
95
    'simple_sitemap_regenerate_now',
96
  ];
97

98
  /**
99 100 101 102
   * FormHelper constructor.
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
103
   */
gbyte.co's avatar
gbyte.co committed
104 105
  public function __construct(
    Simplesitemap $generator,
106
    EntityHelper $entityHelper,
gbyte.co's avatar
gbyte.co committed
107 108
    AccountProxyInterface $current_user
  ) {
109
    $this->generator = $generator;
110
    $this->entityHelper = $entityHelper;
111
    $this->currentUser = $current_user;
112
  }
113

114
  /**
gbyte.co's avatar
gbyte.co committed
115 116
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @return bool
117
   */
gbyte.co's avatar
gbyte.co committed
118
  public function processForm(FormStateInterface $form_state) {
119
    $this->formState = $form_state;
120
    $this->cleanUpFormInfo();
121
    $this->getEntityDataFromFormEntity();
122
    $this->negotiateVariant();
gbyte.co's avatar
gbyte.co committed
123
    return $this->supports();
124 125
  }

126
  /**
gbyte.co's avatar
gbyte.co committed
127
   * @param string $entity_category
128 129
   * @return $this
   */
130 131
  public function setEntityCategory($entity_category) {
    $this->entityCategory = $entity_category;
132
    return $this;
133 134
  }

135
  /**
136
   * @return null|string
137
   */
138 139 140 141 142 143 144 145
  public function getEntityCategory() {
    return $this->entityCategory;
  }

  /**
 * @param string $entity_type_id
 * @return $this
 */
146 147
  public function setEntityTypeId($entity_type_id) {
    $this->entityTypeId = $entity_type_id;
148
    return $this;
149 150
  }

151 152 153 154 155 156 157
  /**
   * @return string
   */
  public function getEntityTypeId() {
    return $this->entityTypeId;
  }

158
  /**
gbyte.co's avatar
gbyte.co committed
159
   * @param string $bundle_name
160 161
   * @return $this
   */
162 163
  public function setBundleName($bundle_name) {
    $this->bundleName = $bundle_name;
164
    return $this;
165 166
  }

167 168 169 170 171 172 173
  /**
   * @return string
   */
  public function getBundleName() {
    return $this->bundleName;
  }

174
  /**
gbyte.co's avatar
gbyte.co committed
175
   * @param string $instance_id
176 177
   * @return $this
   */
178 179
  public function setInstanceId($instance_id) {
    $this->instanceId = $instance_id;
180
    return $this;
181 182
  }

183 184 185 186 187 188 189
  /**
   * @return string
   */
  public function getInstanceId() {
    return $this->instanceId;
  }

gbyte.co's avatar
gbyte.co committed
190
  /**
gbyte.co's avatar
gbyte.co committed
191
   * @return bool
gbyte.co's avatar
gbyte.co committed
192
   */
gbyte.co's avatar
gbyte.co committed
193
  protected function supports() {
gbyte.co's avatar
gbyte.co committed
194 195

    // Do not alter the form if user lacks certain permissions.
gbyte.co's avatar
gbyte.co committed
196
    if (!$this->currentUser->hasPermission('administer sitemap settings')) {
gbyte.co's avatar
gbyte.co committed
197
      return FALSE;
gbyte.co's avatar
gbyte.co committed
198
    }
gbyte.co's avatar
gbyte.co committed
199 200

    // Do not alter the form if it is irrelevant to sitemap generation.
201
    elseif (empty($this->getEntityCategory())) {
gbyte.co's avatar
gbyte.co committed
202
      return FALSE;
gbyte.co's avatar
gbyte.co committed
203
    }
gbyte.co's avatar
gbyte.co committed
204 205

    // Do not alter the form if entity is not enabled in sitemap settings.
206
    elseif (!$this->generator->entityTypeIsEnabled($this->getEntityTypeId())) {
gbyte.co's avatar
gbyte.co committed
207
      return FALSE;
gbyte.co's avatar
gbyte.co committed
208
    }
gbyte.co's avatar
gbyte.co committed
209 210 211

    // Do not alter the form, if sitemap is disabled for the entity type of this
    // entity instance.
212 213 214 215 216 217
    elseif ($this->getEntityCategory() === 'instance') {
      if (NULL === $this->variant || !$this->generator
          ->setVariants($this->variant)
          ->bundleIsIndexed($this->getEntityTypeId(), $this->getBundleName())) {
        return FALSE;
      }
gbyte.co's avatar
gbyte.co committed
218
    }
gbyte.co's avatar
gbyte.co committed
219 220

    return TRUE;
gbyte.co's avatar
gbyte.co committed
221 222
  }

223
  /**
gbyte.co's avatar
gbyte.co committed
224
   * @param array $form_fragment
225
   */
gbyte.co's avatar
gbyte.co committed
226
  public function displayRegenerateNow(&$form_fragment) {
227
    $form_fragment['simple_sitemap_regenerate_now'] = [
228
      '#type' => 'checkbox',
229
      '#title' => $this->t('Regenerate sitemap after hitting <em>Save</em>'),
gbyte.co's avatar
gbyte.co committed
230
      '#description' => $this->t('This setting will regenerate all sitemaps including the above changes.'),
231
      '#default_value' => FALSE,
232
    ];
233
    if ($this->generator->getSetting('cron_generate')) {
234
      $form_fragment['simple_sitemap_regenerate_now']['#description'] .= '<br/>' . $this->t('Otherwise the sitemap will be regenerated during a future cron run.');
235 236
    }
  }
237

238 239 240 241 242 243 244 245 246
  protected function negotiateVariant() {
    $all_bundle_settings = $this->generator->setVariants(TRUE)
      ->getBundleSettings($this->getEntityTypeId(), $this->getBundleName(), FALSE, TRUE);
    $this->bundleSettings = NULL !== ($variant = key($all_bundle_settings))
      ? $all_bundle_settings[$variant]
      : [];
    $this->variant = $variant;
  }

247
  /**
248
   * @param array $form_fragment
249 250 251
   * @param bool $multiple
   * @return $this
   */
252
  public function displayEntitySettings(&$form_fragment, $multiple = FALSE) {
253
    $prefix = $multiple ? $this->getEntityTypeId() . '_' : '';
254

255 256 257
    $settings = $this->getEntityCategory() === 'instance' && NULL !== $this->variant && NULL !== $this->getInstanceId()
      ? $this->generator->setVariants($this->variant)->getEntityInstanceSettings($this->getEntityTypeId(), $this->getInstanceId())
      : $this->bundleSettings;
258
    Simplesitemap::supplementDefaultSettings('entity', $settings);
gbyte.co's avatar
gbyte.co committed
259

260
    $bundle_name = !empty($this->getBundleName()) ? $this->getBundleName() : $this->t('undefined');
261

gbyte.co's avatar
gbyte.co committed
262
    // Index
263 264 265
    if (!$multiple) {
      $form_fragment[$prefix . 'simple_sitemap_index_content'] = [
        '#type' => 'radios',
266
        '#default_value' => (int) $settings['index'],
267
        '#options' => [
gbyte.co's avatar
gbyte.co committed
268 269 270 271 272 273
          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'),
gbyte.co's avatar
gbyte.co committed
274
        ],
275
      ];
gbyte.co's avatar
gbyte.co committed
276

277 278
      if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['index'])) {
        $form_fragment[$prefix . 'simple_sitemap_index_content']['#options'][(int) $this->bundleSettings['index']] .= ' <em>(' . $this->t('default') . ')</em>';
279 280 281
      }
    }

282 283 284 285 286
    // Variant
    $form_fragment[$prefix . 'simple_sitemap_variant'] = [
      '#type' => 'select',
      '#title' => $this->t('Sitemap variant'),
      '#description' => $this->t('The sitemap variant entities of this type are to be indexed in.'),
287 288 289 290
      '#options' => array_map(
        function($variant) { return $this->t($variant['label']); },
        $this->generator->getSitemapManager()->getSitemapVariants(NULL, FALSE)
      ),
291 292 293 294 295 296 297 298 299 300 301 302
      '#default_value' => $this->variant,
      '#states' => [
        'visible' => !$multiple
          ? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
          : [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
        'required' => !$multiple // todo Should implement server side validation on top of this.
          ? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
          : [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
      ],
      '#disabled' => $this->getEntityCategory() === 'instance'
    ];

gbyte.co's avatar
gbyte.co committed
303
    // Priority
304 305
    $form_fragment[$prefix . 'simple_sitemap_priority'] = [
      '#type' => 'select',
306
      '#title' => $this->t('Priority'),
307 308 309
      '#description' => $this->getEntityCategory() === 'instance'
        ? $this->t('The priority this @bundle entity will have in the eyes of search engine bots.', ['@bundle' => $bundle_name])
        : $this->t('The priority entities of this type will have in the eyes of search engine bots.'),
gbyte.co's avatar
gbyte.co committed
310
      '#default_value' => $settings['priority'],
311
      '#options' => $this->getPrioritySelectValues(),
312 313 314 315 316
      '#states' => [
        'visible' => !$multiple
          ? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
          : [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
      ],
317
    ];
318

319 320
    if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['priority'])) {
      $form_fragment[$prefix . 'simple_sitemap_priority']['#options'][$this->formatPriority($this->bundleSettings['priority'])] .= ' (' . $this->t('default') . ')';
321
    }
322

gbyte.co's avatar
gbyte.co committed
323
    // Changefreq
324 325 326
    $form_fragment[$prefix . 'simple_sitemap_changefreq'] = [
      '#type' => 'select',
      '#title' => $this->t('Change frequency'),
327 328 329
      '#description' => $this->getEntityCategory() === 'instance'
      ? $this->t('The frequency with which this @bundle entity changes. Search engine bots may take this as an indication of how often to index it.', ['@bundle' => $bundle_name])
      : $this->t('The frequency with which entities of this type change. Search engine bots may take this as an indication of how often to index them.'),
gbyte.co's avatar
gbyte.co committed
330
      '#default_value' => $settings['changefreq'],
331
      '#options' => $this->getChangefreqSelectValues(),
332 333 334 335 336
      '#states' => [
        'visible' => !$multiple
          ? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
          : [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
      ],
337 338
    ];

339 340
    if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['changefreq'])) {
      $form_fragment[$prefix . 'simple_sitemap_changefreq']['#options'][$this->bundleSettings['changefreq']] .= ' (' . $this->t('default') . ')';
341 342
    }

gbyte.co's avatar
gbyte.co committed
343
    // Images
344 345 346 347
    $form_fragment[$prefix . 'simple_sitemap_include_images'] = [
      '#type' => 'select',
      '#title' => $this->t('Include images'),
      '#description' => $this->getEntityCategory() === 'instance'
gbyte.co's avatar
gbyte.co committed
348 349
        ? $this->t('Determines if images referenced by this @bundle entity should be included in the sitemap.', ['@bundle' => $bundle_name])
        : $this->t('Determines if images referenced by entities of this type should be included in the sitemap.'),
350
      '#default_value' => (int) $settings['include_images'],
351
      '#options' => [0 => $this->t('No'), 1 => $this->t('Yes')],
352 353 354 355 356
      '#states' => [
        'visible' => !$multiple
          ? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
          : [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
      ],
357 358
    ];

359 360
    if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['include_images'])) {
      $form_fragment[$prefix . 'simple_sitemap_include_images']['#options'][(int) $this->bundleSettings['include_images']] .= ' (' . $this->t('default') . ')';
361 362
    }

363
    return $this;
364 365 366 367 368 369 370
  }

  /**
   * Checks if this particular form is a bundle form, or a bundle instance form
   * and gathers sitemap settings from the database.
   *
   * @return bool
gbyte.co's avatar
gbyte.co committed
371
   *   TRUE if this is a bundle or bundle instance form, FALSE otherwise.
372
   */
373
  protected function getEntityDataFromFormEntity() {
gbyte.co's avatar
gbyte.co committed
374
    if (!$form_entity = $this->getFormEntity()) {
gbyte.co's avatar
gbyte.co committed
375 376
      return FALSE;
    }
377

gbyte.co's avatar
gbyte.co committed
378 379 380 381 382 383
    $entity_type_id = $form_entity->getEntityTypeId();
    $sitemap_entity_types = $this->entityHelper->getSupportedEntityTypes();
    if (isset($sitemap_entity_types[$entity_type_id])) {
      $this->setEntityCategory('instance');
    }
    else {
384
      /** @var \Drupal\Core\Entity\EntityType $sitemap_entity_type */
gbyte.co's avatar
gbyte.co committed
385 386 387
      foreach ($sitemap_entity_types as $sitemap_entity_type) {
        if ($sitemap_entity_type->getBundleEntityType() === $entity_type_id) {
          $this->setEntityCategory('bundle');
388
          break;
gbyte.co's avatar
gbyte.co committed
389
        }
390
      }
391
    }
gbyte.co's avatar
gbyte.co committed
392 393

    // Menu fix.
gbyte.co's avatar
gbyte.co committed
394
    $this->setEntityCategory(NULL === $this->getEntityCategory() && $entity_type_id === 'menu' ? 'bundle' : $this->getEntityCategory());
gbyte.co's avatar
gbyte.co committed
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

    switch ($this->getEntityCategory()) {
      case 'bundle':
        $this->setEntityTypeId($this->entityHelper->getBundleEntityTypeId($form_entity));
        $this->setBundleName($form_entity->id());
        $this->setInstanceId(NULL);
        break;

      case 'instance':
        $this->setEntityTypeId($entity_type_id);
        $this->setBundleName($this->entityHelper->getEntityInstanceBundleName($form_entity));
        // New menu link's id is '' instead of NULL, hence checking for empty.
        $this->setInstanceId(!empty($form_entity->id()) ? $form_entity->id() : NULL);
        break;

      default:
        return FALSE;
    }
    return TRUE;
414 415 416 417 418
  }

  /**
   * Gets the object entity of the form if available.
   *
gbyte.co's avatar
gbyte.co committed
419
   * @return \Drupal\Core\Entity\Entity|false
gbyte.co's avatar
gbyte.co committed
420 421
   *   Entity or FALSE if non-existent or if form operation is
   *   'delete'.
422
   */
423
  protected function getFormEntity() {
424
    $form_object = $this->formState->getFormObject();
425
    if (NULL !== $form_object
426
      && method_exists($form_object, 'getOperation')
427
      && method_exists($form_object, 'getEntity')
428
      && in_array($form_object->getOperation(), self::$allowedFormOperations)) {
429 430 431 432 433
      return $form_object->getEntity();
    }
    return FALSE;
  }

434 435 436 437 438 439 440 441 442 443 444
  /**
   * 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;
445 446
    $this->variant = NULL;
    $this->bundleSettings = NULL;
447 448
  }

449 450 451 452
  /**
   * Gets new entity Id after entity creation.
   * To be used in an entity form submit.
   *
gbyte.co's avatar
gbyte.co committed
453
   * @return int
gbyte.co's avatar
gbyte.co committed
454
   *   Entity ID.
455
   */
456 457
  public function getFormEntityId() {
    return $this->formState->getFormObject()->getEntity()->id();
458 459 460 461 462 463
  }

  /**
   * Checks if simple_sitemap values have been changed after submitting the form.
   * To be used in an entity form submit.
   *
464
   * @param $form
465
   * @param array $values
gbyte.co's avatar
gbyte.co committed
466
   *
467
   * @return bool
gbyte.co's avatar
gbyte.co committed
468
   *   TRUE if simple_sitemap form values have been altered by the user.
469
   */
470
  public function valuesChanged($form, array $values) {
471
    foreach (self::$valuesToCheck as $field_name) {
472 473
      if (!isset($form['simple_sitemap'][$field_name]['#default_value'])
        || (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value'])) {
474 475 476 477 478
        return TRUE;
      }
    }
    return FALSE;
  }
gbyte.co's avatar
gbyte.co committed
479 480 481 482

  /**
   * Gets the values needed to display the priority dropdown setting.
   *
483
   * @return array
484
   *   Select options.
gbyte.co's avatar
gbyte.co committed
485
   */
486
  public function getPrioritySelectValues() {
487
    $options = [];
gbyte.co's avatar
gbyte.co committed
488
    foreach (range(0, self::PRIORITY_HIGHEST) as $value) {
489
      $value = $this->formatPriority($value / self::PRIORITY_DIVIDER);
490
      $options[$value] = $value;
gbyte.co's avatar
gbyte.co committed
491 492 493
    }
    return $options;
  }
494

495 496 497 498 499 500 501
  /**
   * Gets the values needed to display the changefreq dropdown setting.
   *
   * @return array
   *   Select options.
   */
  public function getChangefreqSelectValues() {
gbyte.co's avatar
gbyte.co committed
502
    $options = ['' => $this->t('- Not specified -')];
gbyte.co's avatar
gbyte.co committed
503
    foreach (self::getChangefreqOptions() as $setting) {
gbyte.co's avatar
gbyte.co committed
504
      $options[$setting] = $this->t($setting);
505 506 507 508 509 510 511 512
    }
    return $options;
  }

  /**
   * @return array
   */
  public static function getChangefreqOptions() {
513
    return self::$changefreqValues;
514 515
  }

516
  /**
517
   * @param string $priority
518 519 520
   * @return string
   */
  public function formatPriority($priority) {
gbyte.co's avatar
gbyte.co committed
521
    return number_format((float) $priority, 1, '.', '');
522 523
  }

524
  /**
525
   * @param string|int $priority
526 527
   * @return bool
   */
528
  public static function isValidPriority($priority) {
529
    return is_numeric($priority) && $priority >= 0 && $priority <= 1;
530
  }
531 532 533 534 535 536

  /**
   * @param string $changefreq
   * @return bool
   */
  public static function isValidChangefreq($changefreq) {
537
    return in_array($changefreq, self::$changefreqValues);
538
  }
539
}