Form.php 8.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
/**
 * @file
 * Contains \Drupal\simple_sitemap\Form.
 */

namespace Drupal\simple_sitemap;

/**
 * Form class.
 */
class Form {

gbyte.co's avatar
gbyte.co committed
14 15 16 17
  const PRIORITY_DEFAULT = 0.5;
  const PRIORITY_HIGHEST = 10;
  const PRIORITY_DIVIDER = 10;

18
  public $alteringForm;
19
  public $entityCategory;
20 21
  public $entityTypeId;
  public $bundleName;
22
  public $instanceId;
23
  
24
  private $formState;
25
  private $generator;
26

27 28
  private static $allowedFormOperations = ['default', 'edit', 'add'];
  private static $valuesToCheck = ['simple_sitemap_index_content', 'simple_sitemap_priority', 'simple_sitemap_regenerate_now'];
29

30 31 32
  /**
   * Form constructor.
   */
33 34 35 36 37 38
  function __construct($form_state = NULL) {
    // Do not alter the form if user lacks certain permissions.
    if (!\Drupal::currentUser()->hasPermission('administer sitemap settings')) {
      $this->alteringForm = FALSE;
      return;
    }
39 40 41 42

    $this->formState = $form_state;
    $this->entityCategory = NULL;
    $this->alteringForm = TRUE;
43
    $this->generator = \Drupal::service('simple_sitemap.generator');
44

45 46
    $this->getEntityData();
  }
47

48 49
  private function getEntityData() {
    if (!is_null($this->formState))
50
      $this->getEntityDataFromFormEntity();
51 52 53 54 55 56

    // Do not alter the form if it is irrelevant to sitemap generation.
    if (empty($this->entityCategory))
      $this->alteringForm = FALSE;

    // Do not alter the form if entity is not enabled in sitemap settings.
57
    elseif (!$this->generator->entityTypeIsEnabled($this->entityTypeId))
58
      $this->alteringForm = FALSE;
59 60

    // Do not alter the form, if sitemap is disabled for the entity type of this entity instance.
61
    elseif ($this->entityCategory == 'instance'
62
      && !$this->generator->bundleIsIndexed($this->entityTypeId, $this->bundleName))
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
      $this->alteringForm = FALSE;
  }

  public function setEntityCategory($entity_category) {
    $this->entityCategory = $entity_category;
  }

  public function setEntityTypeId($entity_type_id) {
    $this->entityTypeId = $entity_type_id;
  }

  public function setBundleName($bundle_name) {
    $this->bundleName = $bundle_name;
  }

  public function setInstanceId($instance_id) {
    $this->instanceId = $instance_id;
  }

  public function displaySitemapRegenerationSetting(&$form_fragment) {
83
    $form_fragment['simple_sitemap_regenerate_now'] = [
84 85 86 87
      '#type' => 'checkbox',
      '#title' => t('Regenerate sitemap after hitting <em>Save</em>'),
      '#description' => t('This setting will regenerate the whole sitemap including the above changes.'),
      '#default_value' => FALSE,
88
    ];
89
    if ($this->generator->getSetting('cron_generate')) {
90
      $form_fragment['simple_sitemap_regenerate_now']['#description'] .= '</br>' . t('Otherwise the sitemap will be regenerated on the next cron run.');
91 92
    }
  }
93 94 95
  
  public function displayEntitySitemapSettings(&$form_fragment, $multiple = FALSE) {
    $prefix = $multiple ? $this->entityTypeId . '_' : '';
96

97
    if ($this->entityCategory == 'instance') {
98 99
      $bundle_settings = $this->generator->getBundleSettings($this->entityTypeId, $this->bundleName);
      $settings = !is_null($this->instanceId) ? $this->generator->getEntityInstanceSettings($this->entityTypeId, $this->instanceId) : $bundle_settings;
100
    }
101
    else {
102
      $settings = $this->generator->getBundleSettings($this->entityTypeId, $this->bundleName);
103 104 105
    }
    $index = isset($settings['index']) ? $settings['index'] : 0;
    $priority = isset($settings['priority']) ? $settings['priority'] : self::PRIORITY_DEFAULT;
106 107 108 109 110 111 112 113 114 115

    if (!$multiple) {
      $form_fragment[$prefix . 'simple_sitemap_index_content'] = [
        '#type' => 'radios',
        '#default_value' => $index,
        '#options' => [
          0 => $this->entityCategory == 'instance' ? t('Do not index this entity') : t('Do not index entities of this type'),
          1 => $this->entityCategory == 'instance' ? t('Index this entity') : t('Index entities of this type'),
        ]
      ];
116 117
      if ($this->entityCategory == 'instance' && isset($bundle_settings['index'])) {
        $form_fragment[$prefix . 'simple_sitemap_index_content']['#options'][$bundle_settings['index']] .= ' <em>(' . t('Default') . ')</em>';
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
      }
    }

    if ($this->entityCategory == 'instance') {
      $priority_description = t('The priority this entity will have in the eyes of search engine bots.');
    }
    elseif (!$multiple) {
      $priority_description = t('The priority entities of this bundle will have in the eyes of search engine bots.');
    }
    else {
      $priority_description = t('The priority entities of this type will have in the eyes of search engine bots.');
    }
    $form_fragment[$prefix . 'simple_sitemap_priority'] = [
      '#type' => 'select',
      '#title' => t('Priority'),
      '#description' => $priority_description,
      '#default_value' => $priority,
      '#options' => self::getPrioritySelectValues(),
    ];
137 138
    if ($this->entityCategory == 'instance' && isset($bundle_settings['priority'])) {
      $form_fragment[$prefix . 'simple_sitemap_priority']['#options'][(string)$bundle_settings['priority']] .= ' (' . t('Default') . ')';
139 140 141 142 143 144 145 146 147 148
    }
  }

  /**
   * Checks if this particular form is a bundle form, or a bundle instance form
   * and gathers sitemap settings from the database.
   *
   * @return bool
   *  TRUE if this is a bundle or bundle instance form, FALSE otherwise.
   */
149
  private function getEntityDataFromFormEntity() {
150 151
    $form_entity = $this->getFormEntity();
    if ($form_entity !== FALSE) {
152
      $entity_type_id = $form_entity->getEntityTypeId();
153 154 155
      $sitemap_entity_types = Simplesitemap::getSitemapEntityTypes();
      if (isset($sitemap_entity_types[$entity_type_id])) {
        $this->entityCategory = 'instance';
156 157
      }
      else {
158
        foreach($sitemap_entity_types as $sitemap_entity) {
159 160 161
          if ($sitemap_entity->getBundleEntityType() == $entity_type_id) {
            $this->entityCategory = 'bundle';
            break;
162 163 164
          }
        }
      }
165

166
      // Menu fix.
167
      $this->entityCategory = is_null($this->entityCategory) && $entity_type_id == 'menu' ? 'bundle' : $this->entityCategory;
168 169 170

      switch ($this->entityCategory) {
        case 'bundle':
171
          $this->entityTypeId = Simplesitemap::getBundleEntityTypeId($form_entity);
172 173 174 175 176
          $this->bundleName = $form_entity->id();
          $this->instanceId = NULL;
          break;

        case 'instance':
177
          $this->entityTypeId = $entity_type_id;
178
          $this->bundleName = Simplesitemap::getEntityInstanceBundleName($form_entity);
179
          $this->instanceId = !empty($form_entity->id()) ? $form_entity->id() : NULL; // New menu link's id is '' instead of NULL, hence checking for empty.
180 181 182 183 184 185
          break;

        default:
          return FALSE;
      }
      return TRUE;
186 187 188 189 190 191 192 193 194 195 196 197 198 199
    }
    return FALSE;
  }

  /**
   * Gets the object entity of the form if available.
   *
   * @return object $entity or FALSE if non-existent or if form operation is
   *  'delete'.
   */
  private function getFormEntity() {
    $form_object = $this->formState->getFormObject();
    if (!is_null($form_object)
      && method_exists($form_object, 'getEntity')
200
      && in_array($form_object->getOperation(), self::$allowedFormOperations)) {
201 202 203 204 205 206 207 208 209 210 211
      return $form_object->getEntity();
    }
    return FALSE;
  }

  /**
   * Gets new entity Id after entity creation.
   * To be used in an entity form submit.
   *
   * @return int entity ID.
   */
212 213
  public function getFormEntityId() {
    return $this->formState->getFormObject()->getEntity()->id();
214 215 216 217 218 219 220 221 222
  }

  /**
   * Checks if simple_sitemap values have been changed after submitting the form.
   * To be used in an entity form submit.
   *
   * @return bool
   *  TRUE if simple_sitemap form values have been altered by the user.
   */
223
  public static function valuesChanged($form, $values) {
224
    foreach (self::$valuesToCheck as $field_name) {
225
      if (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value']) {
226 227 228 229 230
        return TRUE;
      }
    }
    return FALSE;
  }
gbyte.co's avatar
gbyte.co committed
231 232 233 234 235 236 237

  /**
   * Gets the values needed to display the priority dropdown setting.
   *
   * @return array $options
   */
  public static function getPrioritySelectValues() {
238
    $options = [];
gbyte.co's avatar
gbyte.co committed
239
    foreach(range(0, self::PRIORITY_HIGHEST) as $value) {
240 241
      $value = self::formatPriority($value / self::PRIORITY_DIVIDER);
      $options[$value] = $value;
gbyte.co's avatar
gbyte.co committed
242 243 244
    }
    return $options;
  }
245 246 247 248 249 250 251 252

  public static function formatPriority($priority) {
    return number_format((float)$priority, 1, '.', '');
  }

  public static function isValidPriority($priority) {
    return !is_numeric($priority) || $priority < 0 || $priority > 1 ? FALSE : TRUE;
  }
253
}