FormHelper.php 10.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 13
 * Class FormHelper.
 *
14
 * @package Drupal\simple_sitemap\Form
15
 */
16
class FormHelper {
17
  use StringTranslationTrait;
18

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

23
  private $generator;
24
  private $entityHelper;
25
  private $currentUser;
26 27 28 29
  private $formState;

  public $alteringForm = TRUE;
  public $entityCategory = NULL;
30 31
  public $entityTypeId;
  public $bundleName;
32
  public $instanceId;
33

34 35 36 37
  private static $allowedFormOperations = [
    'default',
    'edit',
    'add',
Pawel G's avatar
Pawel G committed
38
    'register',
39 40 41 42 43
  ];

  private static $valuesToCheck = [
    'simple_sitemap_index_content',
    'simple_sitemap_priority',
Pawel G's avatar
Pawel G committed
44
    'simple_sitemap_regenerate_now',
45
  ];
46

47
  /**
48 49 50 51
   * FormHelper constructor.
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
52
   */
Pawel G's avatar
Pawel G committed
53 54
  public function __construct(
    Simplesitemap $generator,
55
    EntityHelper $entityHelper,
Pawel G's avatar
Pawel G committed
56 57
    AccountProxyInterface $current_user
  ) {
58
    $this->generator = $generator;
59
    $this->entityHelper = $entityHelper;
60
    $this->currentUser = $current_user;
61
  }
Pawel G's avatar
Pawel G committed
62

63 64 65 66
  /**
   * @param $form_state
   * @return $this
   */
67
  public function processForm(FormState $form_state) {
Pawel G's avatar
Pawel G committed
68
    $this->formState = $form_state;
Pawel G's avatar
Pawel G committed
69
    if (!is_null($this->formState)) {
70
      $this->getEntityDataFromFormEntity();
Pawel G's avatar
Pawel G committed
71 72
      $this->assertAlteringForm();
    }
73
    return $this;
74 75
  }

76 77 78 79
  /**
   * @param $entity_category
   * @return $this
   */
80 81
  public function setEntityCategory($entity_category) {
    $this->entityCategory = $entity_category;
82
    return $this;
83 84
  }

85 86 87 88
  /**
   * @param $entity_type_id
   * @return $this
   */
89 90
  public function setEntityTypeId($entity_type_id) {
    $this->entityTypeId = $entity_type_id;
91
    return $this;
92 93
  }

94 95 96 97
  /**
   * @param $bundle_name
   * @return $this
   */
98 99
  public function setBundleName($bundle_name) {
    $this->bundleName = $bundle_name;
100
    return $this;
101 102
  }

103 104 105 106
  /**
   * @param $instance_id
   * @return $this
   */
107 108
  public function setInstanceId($instance_id) {
    $this->instanceId = $instance_id;
109
    return $this;
110 111
  }

Pawel G's avatar
Pawel G committed
112 113 114
  /**
   *
   */
Pawel G's avatar
Pawel G committed
115 116 117
  private function assertAlteringForm() {

    // Do not alter the form if user lacks certain permissions.
Pawel G's avatar
Pawel G committed
118
    if (!$this->currentUser->hasPermission('administer sitemap settings')) {
Pawel G's avatar
Pawel G committed
119
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
120
    }
Pawel G's avatar
Pawel G committed
121 122

    // Do not alter the form if it is irrelevant to sitemap generation.
Pawel G's avatar
Pawel G committed
123
    elseif (empty($this->entityCategory)) {
Pawel G's avatar
Pawel G committed
124
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
125
    }
Pawel G's avatar
Pawel G committed
126 127

    // Do not alter the form if entity is not enabled in sitemap settings.
Pawel G's avatar
Pawel G committed
128
    elseif (!$this->generator->entityTypeIsEnabled($this->entityTypeId)) {
Pawel G's avatar
Pawel G committed
129
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
130
    }
Pawel G's avatar
Pawel G committed
131 132 133 134

    // Do not alter the form, if sitemap is disabled for the entity type of this
    // entity instance.
    elseif ($this->entityCategory == 'instance'
Pawel G's avatar
Pawel G committed
135
      && !$this->generator->bundleIsIndexed($this->entityTypeId, $this->bundleName)) {
Pawel G's avatar
Pawel G committed
136
      $this->alteringForm = FALSE;
Pawel G's avatar
Pawel G committed
137
    }
Pawel G's avatar
Pawel G committed
138 139
  }

140 141 142
  /**
   * @param $form_fragment
   */
Pawel G's avatar
Pawel G committed
143
  public function displayRegenerateNow(&$form_fragment) {
Pawel G's avatar
Pawel G committed
144
    $form_fragment['simple_sitemap_regenerate_now'] = [
145
      '#type' => 'checkbox',
146 147
      '#title' => $this->t('Regenerate sitemap after hitting <em>Save</em>'),
      '#description' => $this->t('This setting will regenerate the whole sitemap including the above changes.'),
148
      '#default_value' => FALSE,
Pawel G's avatar
Pawel G committed
149
    ];
Pawel G's avatar
Pawel G committed
150
    if ($this->generator->getSetting('cron_generate')) {
151
      $form_fragment['simple_sitemap_regenerate_now']['#description'] .= '</br>' . $this->t('Otherwise the sitemap will be regenerated on the next cron run.');
152 153
    }
  }
154 155

  /**
156
   * @param array $form_fragment
157 158 159
   * @param bool $multiple
   * @return $this
   */
160
  public function displayEntitySettings(array &$form_fragment, $multiple = FALSE) {
161
    $prefix = $multiple ? $this->entityTypeId . '_' : '';
162

163
    if ($this->entityCategory == 'instance') {
Pawel G's avatar
Pawel G committed
164 165
      $bundle_settings = $this->generator->getBundleSettings($this->entityTypeId, $this->bundleName);
      $settings = !is_null($this->instanceId) ? $this->generator->getEntityInstanceSettings($this->entityTypeId, $this->instanceId) : $bundle_settings;
166
    }
167
    else {
Pawel G's avatar
Pawel G committed
168
      $settings = $this->generator->getBundleSettings($this->entityTypeId, $this->bundleName);
169 170 171
    }
    $index = isset($settings['index']) ? $settings['index'] : 0;
    $priority = isset($settings['priority']) ? $settings['priority'] : self::PRIORITY_DEFAULT;
172
    $bundle_name = !empty($this->bundleName) ? $this->bundleName : $this->t('undefined');
173 174 175 176 177 178

    if (!$multiple) {
      $form_fragment[$prefix . 'simple_sitemap_index_content'] = [
        '#type' => 'radios',
        '#default_value' => $index,
        '#options' => [
179 180
          0 => $this->entityCategory == 'instance' ? $this->t('Do not index this @bundle entity', ['@bundle' => $bundle_name]) : $this->t('Do not index entities of this type'),
          1 => $this->entityCategory == 'instance' ? $this->t('Index this @bundle entity', ['@bundle' => $bundle_name]) : $this->t('Index entities of this type'),
Pawel G's avatar
Pawel G committed
181
        ],
182
      ];
183
      if ($this->entityCategory == 'instance' && isset($bundle_settings['index'])) {
184
        $form_fragment[$prefix . 'simple_sitemap_index_content']['#options'][$bundle_settings['index']] .= ' <em>(' . $this->t('Default') . ')</em>';
185 186 187
      }
    }

Pawel G's avatar
Pawel G committed
188
    if ($this->entityCategory == 'instance') {
189
      $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
190 191
    }
    else {
192
      $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
193
    }
194 195
    $form_fragment[$prefix . 'simple_sitemap_priority'] = [
      '#type' => 'select',
196
      '#title' => $this->t('Priority'),
197 198
      '#description' => $priority_description,
      '#default_value' => $priority,
199
      '#options' => $this->getPrioritySelectValues(),
200
    ];
201
    if ($this->entityCategory == 'instance' && isset($bundle_settings['priority'])) {
202
      $form_fragment[$prefix . 'simple_sitemap_priority']['#options'][$this->formatPriority($bundle_settings['priority'])] .= ' (' . $this->t('Default') . ')';
203
    }
Pawel G's avatar
Pawel G committed
204
    return $this;
205 206 207 208 209 210 211
  }

  /**
   * 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
212
   *   TRUE if this is a bundle or bundle instance form, FALSE otherwise.
213
   */
214
  private function getEntityDataFromFormEntity() {
215 216
    $form_entity = $this->getFormEntity();
    if ($form_entity !== FALSE) {
217
      $entity_type_id = $form_entity->getEntityTypeId();
218
      $sitemap_entity_types = $this->entityHelper->getSitemapEntityTypes();
219 220
      if (isset($sitemap_entity_types[$entity_type_id])) {
        $this->entityCategory = 'instance';
221 222
      }
      else {
Pawel G's avatar
Pawel G committed
223
        foreach ($sitemap_entity_types as $sitemap_entity) {
224 225 226
          if ($sitemap_entity->getBundleEntityType() == $entity_type_id) {
            $this->entityCategory = 'bundle';
            break;
227 228 229
          }
        }
      }
230

231
      // Menu fix.
232
      $this->entityCategory = is_null($this->entityCategory) && $entity_type_id == 'menu' ? 'bundle' : $this->entityCategory;
233 234 235

      switch ($this->entityCategory) {
        case 'bundle':
236
          $this->entityTypeId = $this->entityHelper->getBundleEntityTypeId($form_entity);
237 238 239 240 241
          $this->bundleName = $form_entity->id();
          $this->instanceId = NULL;
          break;

        case 'instance':
242
          $this->entityTypeId = $entity_type_id;
243
          $this->bundleName = $this->entityHelper->getEntityInstanceBundleName($form_entity);
Pawel G's avatar
Pawel G committed
244 245
          // New menu link's id is '' instead of NULL, hence checking for empty.
          $this->instanceId = !empty($form_entity->id()) ? $form_entity->id() : NULL;
246 247 248 249 250 251
          break;

        default:
          return FALSE;
      }
      return TRUE;
252 253 254 255 256 257 258
    }
    return FALSE;
  }

  /**
   * Gets the object entity of the form if available.
   *
Pawel G's avatar
Pawel G committed
259
   * @return object|false
Pawel G's avatar
Pawel G committed
260 261
   *   Entity or FALSE if non-existent or if form operation is
   *   'delete'.
262 263 264 265 266
   */
  private function getFormEntity() {
    $form_object = $this->formState->getFormObject();
    if (!is_null($form_object)
      && method_exists($form_object, 'getEntity')
267
      && in_array($form_object->getOperation(), self::$allowedFormOperations)) {
268 269 270 271 272 273 274 275 276
      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
277
   * @return int
Pawel G's avatar
Pawel G committed
278
   *   Entity ID.
279
   */
Pawel G's avatar
Pawel G committed
280 281
  public function getFormEntityId() {
    return $this->formState->getFormObject()->getEntity()->id();
282 283 284 285 286 287
  }

  /**
   * Checks if simple_sitemap values have been changed after submitting the form.
   * To be used in an entity form submit.
   *
288
   * @param $form
289
   * @param array $values
Pawel G's avatar
Pawel G committed
290
   *
291
   * @return bool
Pawel G's avatar
Pawel G committed
292
   *   TRUE if simple_sitemap form values have been altered by the user.
293
   */
294
  public function valuesChanged($form, array $values) {
Pawel G's avatar
Pawel G committed
295
    foreach (self::$valuesToCheck as $field_name) {
296
      if (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value']) {
297 298 299 300 301
        return TRUE;
      }
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
302 303 304 305

  /**
   * Gets the values needed to display the priority dropdown setting.
   *
306
   * @return array
Pawel G's avatar
Pawel G committed
307
   */
308
  public function getPrioritySelectValues() {
Pawel G's avatar
Pawel G committed
309
    $options = [];
Pawel G's avatar
Pawel G committed
310
    foreach (range(0, self::PRIORITY_HIGHEST) as $value) {
311
      $value = $this->formatPriority($value / self::PRIORITY_DIVIDER);
312
      $options[$value] = $value;
Pawel G's avatar
Pawel G committed
313 314 315
    }
    return $options;
  }
316

317
  /**
318
   * @param string $priority
319 320 321
   * @return string
   */
  public function formatPriority($priority) {
Pawel G's avatar
Pawel G committed
322
    return number_format((float) $priority, 1, '.', '');
323 324
  }

325
  /**
326
   * @param string|int $priority
327 328
   * @return bool
   */
329
  public static function isValidPriority($priority) {
330
    return is_numeric($priority) && $priority >= 0 && $priority <= 1;
331
  }
332
}