Store.php 12.7 KB
Newer Older
rszrama's avatar
rszrama committed
1 2
<?php

3
namespace Drupal\commerce_store\Entity;
rszrama's avatar
rszrama committed
4

5
use CommerceGuys\Addressing\AddressFormat\AddressField;
6
use CommerceGuys\Addressing\AddressFormat\FieldOverride;
7
use Drupal\address\AddressInterface;
8
use Drupal\commerce\EntityOwnerTrait;
pcambra's avatar
pcambra committed
9
use Drupal\commerce_price\Entity\CurrencyInterface;
rszrama's avatar
rszrama committed
10
use Drupal\Core\Entity\ContentEntityBase;
11
use Drupal\Core\Entity\EntityStorageInterface;
rszrama's avatar
rszrama committed
12
use Drupal\Core\Entity\EntityTypeInterface;
13
use Drupal\Core\Field\BaseFieldDefinition;
rszrama's avatar
rszrama committed
14 15

/**
bojanz's avatar
bojanz committed
16
 * Defines the store entity class.
rszrama's avatar
rszrama committed
17 18 19
 *
 * @ContentEntityType(
 *   id = "commerce_store",
20 21 22 23
 *   label = @Translation("Store", context = "Commerce"),
 *   label_collection = @Translation("Stores", context = "Commerce"),
 *   label_singular = @Translation("store", context = "Commerce"),
 *   label_plural = @Translation("stores", context = "Commerce"),
24 25 26
 *   label_count = @PluralTranslation(
 *     singular = "@count store",
 *     plural = "@count stores",
27
 *     context = "Commerce",
28
 *   ),
29
 *   bundle_label = @Translation("Store type", context = "Commerce"),
30
 *   handlers = {
31
 *     "event" = "Drupal\commerce_store\Event\StoreEvent",
32
 *     "storage" = "Drupal\commerce_store\StoreStorage",
33
 *     "access" = "Drupal\entity\EntityAccessControlHandler",
34
 *     "query_access" = "Drupal\entity\QueryAccess\QueryAccessHandler",
35
 *     "permission_provider" = "Drupal\entity\EntityPermissionProvider",
rszrama's avatar
rszrama committed
36
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
37
 *     "list_builder" = "Drupal\commerce_store\StoreListBuilder",
38
 *     "views_data" = "Drupal\commerce\CommerceEntityViewsData",
rszrama's avatar
rszrama committed
39
 *     "form" = {
40
 *       "default" = "Drupal\commerce_store\Form\StoreForm",
41 42
 *       "add" = "Drupal\commerce_store\Form\StoreForm",
 *       "edit" = "Drupal\commerce_store\Form\StoreForm",
43
 *       "duplicate" = "Drupal\commerce_store\Form\StoreForm",
44
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
rszrama's avatar
rszrama committed
45
 *     },
46 47 48
 *     "local_task_provider" = {
 *       "default" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
 *     },
bojanz's avatar
bojanz committed
49
 *     "route_provider" = {
50
 *       "default" = "Drupal\entity\Routing\AdminHtmlRouteProvider",
51
 *       "delete-multiple" = "Drupal\entity\Routing\DeleteMultipleRouteProvider",
bojanz's avatar
bojanz committed
52
 *     },
53
 *     "translation" = "Drupal\content_translation\ContentTranslationHandler"
rszrama's avatar
rszrama committed
54 55
 *   },
 *   base_table = "commerce_store",
56
 *   data_table = "commerce_store_field_data",
57 58
 *   admin_permission = "administer commerce_store",
 *   permission_granularity = "bundle",
rszrama's avatar
rszrama committed
59 60 61
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "store_id",
62
 *     "uuid" = "uuid",
63
 *     "bundle" = "type",
rszrama's avatar
rszrama committed
64
 *     "label" = "name",
65
 *     "langcode" = "langcode",
66 67
 *     "owner" = "uid",
 *     "uid" = "uid",
rszrama's avatar
rszrama committed
68 69
 *   },
 *   links = {
70
 *     "canonical" = "/store/{commerce_store}",
71
 *     "add-page" = "/store/add",
bojanz's avatar
bojanz committed
72
 *     "add-form" = "/store/add/{commerce_store_type}",
73
 *     "edit-form" = "/store/{commerce_store}/edit",
74
 *     "duplicate-form" = "/store/{commerce_store}/duplicate",
75
 *     "delete-form" = "/store/{commerce_store}/delete",
76 77
 *     "delete-multiple-form" = "/admin/commerce/config/stores/delete",
 *     "collection" = "/admin/commerce/config/stores",
78
 *   },
79
 *   bundle_entity_type = "commerce_store_type",
80
 *   field_ui_base_route = "entity.commerce_store_type.edit_form",
rszrama's avatar
rszrama committed
81 82
 * )
 */
83
class Store extends ContentEntityBase implements StoreInterface {
bojanz's avatar
bojanz committed
84

85 86
  use EntityOwnerTrait;

rszrama's avatar
rszrama committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getEmail() {
    return $this->get('mail')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setEmail($mail) {
    $this->set('mail', $mail);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultCurrency() {
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    return $this->get('default_currency')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function setDefaultCurrency(CurrencyInterface $currency) {
    $this->set('default_currency', $currency->getCurrencyCode());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultCurrencyCode() {
    return $this->get('default_currency')->target_id;
rszrama's avatar
rszrama committed
137 138 139 140 141
  }

  /**
   * {@inheritdoc}
   */
142 143
  public function setDefaultCurrencyCode($currency_code) {
    $this->set('default_currency', $currency_code);
rszrama's avatar
rszrama committed
144 145 146
    return $this;
  }

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  /**
   * {@inheritdoc}
   */
  public function getTimezone() {
    return $this->get('timezone')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setTimezone($timezone) {
    $this->set('timezone', $timezone);
    return $this;
  }

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  /**
   * {@inheritdoc}
   */
  public function getAddress() {
    return $this->get('address')->first();
  }

  /**
   * {@inheritdoc}
   */
  public function setAddress(AddressInterface $address) {
    // $this->set('address', $address) results in the address being appended
    // to the item list, instead of replacing the existing first item.
    $this->address = $address;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
182
  public function getBillingCountries() {
183
    $countries = [];
184
    foreach ($this->get('billing_countries') as $countryItem) {
185 186 187 188 189 190 191 192
      $countries[] = $countryItem->value;
    }
    return $countries;
  }

  /**
   * {@inheritdoc}
   */
193 194
  public function setBillingCountries(array $countries) {
    $this->set('billing_countries', $countries);
195 196 197
    return $this;
  }

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  /**
   * {@inheritdoc}
   */
  public function isDefault() {
    return (bool) $this->get('is_default')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setDefault($is_default) {
    $this->set('is_default', (bool) $is_default);
    return $this;
  }

213 214 215 216 217 218 219 220 221
  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

    foreach (array_keys($this->getTranslationLanguages()) as $langcode) {
      $translation = $this->getTranslation($langcode);

222 223 224 225
      // Explicitly set the owner ID to 0 if the translation owner is anonymous
      // (This will ensure we don't store a broken reference in case the user
      // no longer exists).
      if ($translation->getOwner()->isAnonymous()) {
226 227 228 229 230
        $translation->setOwnerId(0);
      }
    }
  }

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    /** @var \Drupal\commerce_store\StoreStorage $storage */
    parent::postSave($storage, $update);

    $default = $this->isDefault();
    $original_default = $this->original ? $this->original->isDefault() : FALSE;
    if ($default && !$original_default) {
      // The store was set as default, remove the flag from other stores.
      $store_ids = $storage->getQuery()
        ->condition('store_id', $this->id(), '<>')
        ->condition('is_default', TRUE)
        ->accessCheck(FALSE)
        ->execute();
      foreach ($store_ids as $store_id) {
        /** @var \Drupal\commerce_store\Entity\StoreInterface $store */
        $store = $storage->load($store_id);
        $store->setDefault(FALSE);
        $store->save();
      }
    }
  }

rszrama's avatar
rszrama committed
256 257 258
  /**
   * {@inheritdoc}
   */
259
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
bojanz's avatar
bojanz committed
260
    $fields = parent::baseFieldDefinitions($entity_type);
261
    $fields += static::ownerBaseFieldDefinitions($entity_type);
rszrama's avatar
rszrama committed
262

263 264 265 266 267 268
    $fields['type'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Type'))
      ->setDescription(t('The store type.'))
      ->setSetting('target_type', 'commerce_store_type')
      ->setReadOnly(TRUE);

269
    $fields['uid']
270 271
      ->setLabel(t('Owner'))
      ->setDescription(t('The store owner.'))
272 273
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);
274

275
    $fields['name'] = BaseFieldDefinition::create('string')
276
      ->setLabel(t('Name'))
277
      ->setDescription(t('The store name.'))
jbekker's avatar
jbekker committed
278
      ->setRequired(TRUE)
rszrama's avatar
rszrama committed
279
      ->setTranslatable(TRUE)
280
      ->setSettings([
rszrama's avatar
rszrama committed
281 282
        'default_value' => '',
        'max_length' => 255,
283 284
      ])
      ->setDisplayOptions('form', [
285
        'type' => 'string_textfield',
286 287 288 289
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);
rszrama's avatar
rszrama committed
290

291
    $fields['mail'] = BaseFieldDefinition::create('email')
292 293
      ->setLabel(t('Email'))
      ->setDescription(t('Store email notifications are sent from this address.'))
jbekker's avatar
jbekker committed
294
      ->setRequired(TRUE)
295
      ->setDisplayOptions('form', [
296
        'type' => 'email_default',
297 298
        'weight' => 1,
      ])
299
      ->setSetting('display_description', TRUE)
300 301
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);
rszrama's avatar
rszrama committed
302

303
    $fields['default_currency'] = BaseFieldDefinition::create('entity_reference')
rszrama's avatar
rszrama committed
304
      ->setLabel(t('Default currency'))
305
      ->setDescription(t('The default currency of the store.'))
306 307 308 309 310
      ->setCardinality(1)
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_currency')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
311
      ->setDisplayOptions('form', [
312
        'type' => 'options_select',
313 314 315 316
        'weight' => 2,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);
317

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    $fields['timezone'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Timezone'))
      ->setDescription(t('Used when determining promotion and tax availability.'))
      ->setCardinality(1)
      ->setRequired(TRUE)
      ->setDefaultValueCallback('Drupal\commerce_store\Entity\Store::getSiteTimezone')
      ->setSetting('allowed_values_function', ['\Drupal\commerce_store\Entity\Store', 'getTimezones'])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 3,
      ])
      ->setSetting('display_description', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

333 334
    $fields['address'] = BaseFieldDefinition::create('address')
      ->setLabel(t('Address'))
335
      ->setDescription(t('The store address.'))
336 337
      ->setCardinality(1)
      ->setRequired(TRUE)
338 339 340 341 342 343
      ->setSetting('field_overrides', [
        AddressField::GIVEN_NAME => ['override' => FieldOverride::HIDDEN],
        AddressField::ADDITIONAL_NAME => ['override' => FieldOverride::HIDDEN],
        AddressField::FAMILY_NAME => ['override' => FieldOverride::HIDDEN],
        AddressField::ORGANIZATION => ['override' => FieldOverride::HIDDEN],
      ])
344 345
      ->setDisplayOptions('form', [
        'type' => 'address_default',
346
        'weight' => 4,
347 348 349 350
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

351 352
    $fields['billing_countries'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Supported billing countries'))
353
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
354
      ->setSetting('allowed_values_function', ['\Drupal\commerce_store\Entity\Store', 'getAvailableCountries'])
bojanz's avatar
bojanz committed
355
      ->setDisplayOptions('form', [
356
        'type' => 'options_select',
357
        'weight' => 5,
bojanz's avatar
bojanz committed
358
      ])
359 360 361
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

362 363 364 365 366 367 368 369 370 371 372
    $fields['path'] = BaseFieldDefinition::create('path')
      ->setLabel(t('URL alias'))
      ->setDescription(t('The store URL alias.'))
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'path',
        'weight' => 30,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setCustomStorage(TRUE);

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    // 'default' is a reserved SQL word, hence the 'is_' prefix.
    $fields['is_default'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Default'))
      ->setDescription(t('Whether this is the default store.'))
      ->setDefaultValue(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 90,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

rszrama's avatar
rszrama committed
388 389
    return $fields;
  }
bojanz's avatar
bojanz committed
390

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
  /**
   * Default value callback for the 'timezone' base field definition.
   *
   * @see ::baseFieldDefinitions()
   *
   * @return array
   *   An array of default values.
   */
  public static function getSiteTimezone() {
    $site_timezone = \Drupal::config('system.date')->get('timezone.default');
    if (empty($site_timezone)) {
      $site_timezone = @date_default_timezone_get();
    }

    return [$site_timezone];
  }

  /**
   * Gets the allowed values for the 'timezone' base field.
   *
   * @return array
   *   The allowed values.
   */
  public static function getTimezones() {
    return system_time_zones(NULL, TRUE);
  }

418
  /**
419
   * Gets the allowed values for the 'billing_countries' base field.
420 421 422 423 424 425 426 427
   *
   * @return array
   *   The allowed values.
   */
  public static function getAvailableCountries() {
    return \Drupal::service('address.country_repository')->getList();
  }

rszrama's avatar
rszrama committed
428
}