annotate core/lib/Drupal/Core/Entity/ContentEntityBase.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 7a779792577d
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\Entity;
Chris@0 4
Chris@0 5 use Drupal\Component\Utility\SafeMarkup;
Chris@0 6 use Drupal\Core\Entity\Plugin\DataType\EntityReference;
Chris@0 7 use Drupal\Core\Field\BaseFieldDefinition;
Chris@0 8 use Drupal\Core\Field\ChangedFieldItemList;
Chris@0 9 use Drupal\Core\Language\Language;
Chris@0 10 use Drupal\Core\Language\LanguageInterface;
Chris@0 11 use Drupal\Core\Session\AccountInterface;
Chris@0 12 use Drupal\Core\StringTranslation\TranslatableMarkup;
Chris@0 13 use Drupal\Core\TypedData\TranslationStatusInterface;
Chris@0 14 use Drupal\Core\TypedData\TypedDataInterface;
Chris@0 15
Chris@0 16 /**
Chris@0 17 * Implements Entity Field API specific enhancements to the Entity class.
Chris@0 18 *
Chris@0 19 * @ingroup entity_api
Chris@0 20 */
Chris@0 21 abstract class ContentEntityBase extends Entity implements \IteratorAggregate, ContentEntityInterface, TranslationStatusInterface {
Chris@0 22
Chris@0 23 /**
Chris@0 24 * The plain data values of the contained fields.
Chris@0 25 *
Chris@0 26 * This always holds the original, unchanged values of the entity. The values
Chris@0 27 * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
Chris@0 28 * is used for values in default language.
Chris@0 29 *
Chris@0 30 * @todo: Add methods for getting original fields and for determining
Chris@0 31 * changes.
Chris@0 32 * @todo: Provide a better way for defining default values.
Chris@0 33 *
Chris@0 34 * @var array
Chris@0 35 */
Chris@0 36 protected $values = [];
Chris@0 37
Chris@0 38 /**
Chris@0 39 * The array of fields, each being an instance of FieldItemListInterface.
Chris@0 40 *
Chris@0 41 * @var array
Chris@0 42 */
Chris@0 43 protected $fields = [];
Chris@0 44
Chris@0 45 /**
Chris@0 46 * Local cache for field definitions.
Chris@0 47 *
Chris@0 48 * @see ContentEntityBase::getFieldDefinitions()
Chris@0 49 *
Chris@0 50 * @var array
Chris@0 51 */
Chris@0 52 protected $fieldDefinitions;
Chris@0 53
Chris@0 54 /**
Chris@0 55 * Local cache for the available language objects.
Chris@0 56 *
Chris@0 57 * @var \Drupal\Core\Language\LanguageInterface[]
Chris@0 58 */
Chris@0 59 protected $languages;
Chris@0 60
Chris@0 61 /**
Chris@0 62 * The language entity key.
Chris@0 63 *
Chris@0 64 * @var string
Chris@0 65 */
Chris@0 66 protected $langcodeKey;
Chris@0 67
Chris@0 68 /**
Chris@0 69 * The default langcode entity key.
Chris@0 70 *
Chris@0 71 * @var string
Chris@0 72 */
Chris@0 73 protected $defaultLangcodeKey;
Chris@0 74
Chris@0 75 /**
Chris@0 76 * Language code identifying the entity active language.
Chris@0 77 *
Chris@0 78 * This is the language field accessors will use to determine which field
Chris@0 79 * values manipulate.
Chris@0 80 *
Chris@0 81 * @var string
Chris@0 82 */
Chris@0 83 protected $activeLangcode = LanguageInterface::LANGCODE_DEFAULT;
Chris@0 84
Chris@0 85 /**
Chris@0 86 * Local cache for the default language code.
Chris@0 87 *
Chris@0 88 * @var string
Chris@0 89 */
Chris@0 90 protected $defaultLangcode;
Chris@0 91
Chris@0 92 /**
Chris@0 93 * An array of entity translation metadata.
Chris@0 94 *
Chris@0 95 * An associative array keyed by translation language code. Every value is an
Chris@0 96 * array containing the translation status and the translation object, if it has
Chris@0 97 * already been instantiated.
Chris@0 98 *
Chris@0 99 * @var array
Chris@0 100 */
Chris@0 101 protected $translations = [];
Chris@0 102
Chris@0 103 /**
Chris@0 104 * A flag indicating whether a translation object is being initialized.
Chris@0 105 *
Chris@0 106 * @var bool
Chris@0 107 */
Chris@0 108 protected $translationInitialize = FALSE;
Chris@0 109
Chris@0 110 /**
Chris@0 111 * Boolean indicating whether a new revision should be created on save.
Chris@0 112 *
Chris@0 113 * @var bool
Chris@0 114 */
Chris@0 115 protected $newRevision = FALSE;
Chris@0 116
Chris@0 117 /**
Chris@0 118 * Indicates whether this is the default revision.
Chris@0 119 *
Chris@0 120 * @var bool
Chris@0 121 */
Chris@0 122 protected $isDefaultRevision = TRUE;
Chris@0 123
Chris@0 124 /**
Chris@0 125 * Holds untranslatable entity keys such as the ID, bundle, and revision ID.
Chris@0 126 *
Chris@0 127 * @var array
Chris@0 128 */
Chris@0 129 protected $entityKeys = [];
Chris@0 130
Chris@0 131 /**
Chris@0 132 * Holds translatable entity keys such as the label.
Chris@0 133 *
Chris@0 134 * @var array
Chris@0 135 */
Chris@0 136 protected $translatableEntityKeys = [];
Chris@0 137
Chris@0 138 /**
Chris@0 139 * Whether entity validation was performed.
Chris@0 140 *
Chris@0 141 * @var bool
Chris@0 142 */
Chris@0 143 protected $validated = FALSE;
Chris@0 144
Chris@0 145 /**
Chris@0 146 * Whether entity validation is required before saving the entity.
Chris@0 147 *
Chris@0 148 * @var bool
Chris@0 149 */
Chris@0 150 protected $validationRequired = FALSE;
Chris@0 151
Chris@0 152 /**
Chris@0 153 * The loaded revision ID before the new revision was set.
Chris@0 154 *
Chris@0 155 * @var int
Chris@0 156 */
Chris@0 157 protected $loadedRevisionId;
Chris@0 158
Chris@0 159 /**
Chris@0 160 * {@inheritdoc}
Chris@0 161 */
Chris@0 162 public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
Chris@0 163 $this->entityTypeId = $entity_type;
Chris@0 164 $this->entityKeys['bundle'] = $bundle ? $bundle : $this->entityTypeId;
Chris@0 165 $this->langcodeKey = $this->getEntityType()->getKey('langcode');
Chris@0 166 $this->defaultLangcodeKey = $this->getEntityType()->getKey('default_langcode');
Chris@0 167
Chris@0 168 foreach ($values as $key => $value) {
Chris@0 169 // If the key matches an existing property set the value to the property
Chris@0 170 // to set properties like isDefaultRevision.
Chris@0 171 // @todo: Should this be converted somehow?
Chris@0 172 if (property_exists($this, $key) && isset($value[LanguageInterface::LANGCODE_DEFAULT])) {
Chris@0 173 $this->$key = $value[LanguageInterface::LANGCODE_DEFAULT];
Chris@0 174 }
Chris@0 175 }
Chris@0 176
Chris@0 177 $this->values = $values;
Chris@0 178 foreach ($this->getEntityType()->getKeys() as $key => $field_name) {
Chris@0 179 if (isset($this->values[$field_name])) {
Chris@0 180 if (is_array($this->values[$field_name])) {
Chris@0 181 // We store untranslatable fields into an entity key without using a
Chris@0 182 // langcode key.
Chris@0 183 if (!$this->getFieldDefinition($field_name)->isTranslatable()) {
Chris@0 184 if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
Chris@0 185 if (is_array($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
Chris@0 186 if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'])) {
Chris@0 187 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'];
Chris@0 188 }
Chris@0 189 }
Chris@0 190 else {
Chris@0 191 $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT];
Chris@0 192 }
Chris@0 193 }
Chris@0 194 }
Chris@0 195 else {
Chris@0 196 // We save translatable fields such as the publishing status of a node
Chris@0 197 // into an entity key array keyed by langcode as a performance
Chris@0 198 // optimization, so we don't have to go through TypedData when we
Chris@0 199 // need these values.
Chris@0 200 foreach ($this->values[$field_name] as $langcode => $field_value) {
Chris@0 201 if (is_array($this->values[$field_name][$langcode])) {
Chris@0 202 if (isset($this->values[$field_name][$langcode][0]['value'])) {
Chris@0 203 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode][0]['value'];
Chris@0 204 }
Chris@0 205 }
Chris@0 206 else {
Chris@0 207 $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode];
Chris@0 208 }
Chris@0 209 }
Chris@0 210 }
Chris@0 211 }
Chris@0 212 }
Chris@0 213 }
Chris@0 214
Chris@0 215 // Initialize translations. Ensure we have at least an entry for the default
Chris@0 216 // language.
Chris@0 217 // We determine if the entity is new by checking in the entity values for
Chris@0 218 // the presence of the id entity key, as the usage of ::isNew() is not
Chris@0 219 // possible in the constructor.
Chris@0 220 $data = isset($values[$this->getEntityType()->getKey('id')]) ? ['status' => static::TRANSLATION_EXISTING] : ['status' => static::TRANSLATION_CREATED];
Chris@0 221 $this->translations[LanguageInterface::LANGCODE_DEFAULT] = $data;
Chris@0 222 $this->setDefaultLangcode();
Chris@0 223 if ($translations) {
Chris@0 224 foreach ($translations as $langcode) {
Chris@0 225 if ($langcode != $this->defaultLangcode && $langcode != LanguageInterface::LANGCODE_DEFAULT) {
Chris@0 226 $this->translations[$langcode] = $data;
Chris@0 227 }
Chris@0 228 }
Chris@0 229 }
Chris@0 230 if ($this->getEntityType()->isRevisionable()) {
Chris@0 231 // Store the loaded revision ID the entity has been loaded with to
Chris@0 232 // keep it safe from changes.
Chris@0 233 $this->updateLoadedRevisionId();
Chris@0 234 }
Chris@0 235 }
Chris@0 236
Chris@0 237 /**
Chris@0 238 * {@inheritdoc}
Chris@0 239 */
Chris@0 240 protected function getLanguages() {
Chris@0 241 if (empty($this->languages)) {
Chris@0 242 $this->languages = $this->languageManager()->getLanguages(LanguageInterface::STATE_ALL);
Chris@0 243 // If the entity references a language that is not or no longer available,
Chris@0 244 // we return a mock language object to avoid disrupting the consuming
Chris@0 245 // code.
Chris@0 246 if (!isset($this->languages[$this->defaultLangcode])) {
Chris@0 247 $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]);
Chris@0 248 }
Chris@0 249 }
Chris@0 250 return $this->languages;
Chris@0 251 }
Chris@0 252
Chris@0 253 /**
Chris@0 254 * {@inheritdoc}
Chris@0 255 */
Chris@0 256 public function postCreate(EntityStorageInterface $storage) {
Chris@0 257 $this->newRevision = TRUE;
Chris@0 258 }
Chris@0 259
Chris@0 260 /**
Chris@0 261 * {@inheritdoc}
Chris@0 262 */
Chris@0 263 public function setNewRevision($value = TRUE) {
Chris@0 264 if (!$this->getEntityType()->hasKey('revision')) {
Chris@0 265 throw new \LogicException("Entity type {$this->getEntityTypeId()} does not support revisions.");
Chris@0 266 }
Chris@0 267
Chris@0 268 if ($value && !$this->newRevision) {
Chris@0 269 // When saving a new revision, set any existing revision ID to NULL so as
Chris@0 270 // to ensure that a new revision will actually be created.
Chris@0 271 $this->set($this->getEntityType()->getKey('revision'), NULL);
Chris@0 272
Chris@0 273 // Make sure that the flag tracking which translations are affected by the
Chris@0 274 // current revision is reset.
Chris@0 275 foreach ($this->translations as $langcode => $data) {
Chris@0 276 // But skip removed translations.
Chris@0 277 if ($this->hasTranslation($langcode)) {
Chris@0 278 $this->getTranslation($langcode)->setRevisionTranslationAffected(NULL);
Chris@0 279 }
Chris@0 280 }
Chris@0 281 }
Chris@0 282
Chris@0 283 $this->newRevision = $value;
Chris@0 284 }
Chris@0 285
Chris@0 286 /**
Chris@0 287 * {@inheritdoc}
Chris@0 288 */
Chris@0 289 public function getLoadedRevisionId() {
Chris@0 290 return $this->loadedRevisionId;
Chris@0 291 }
Chris@0 292
Chris@0 293 /**
Chris@0 294 * {@inheritdoc}
Chris@0 295 */
Chris@0 296 public function updateLoadedRevisionId() {
Chris@0 297 $this->loadedRevisionId = $this->getRevisionId() ?: $this->loadedRevisionId;
Chris@0 298 return $this;
Chris@0 299 }
Chris@0 300
Chris@0 301 /**
Chris@0 302 * {@inheritdoc}
Chris@0 303 */
Chris@0 304 public function isNewRevision() {
Chris@0 305 return $this->newRevision || ($this->getEntityType()->hasKey('revision') && !$this->getRevisionId());
Chris@0 306 }
Chris@0 307
Chris@0 308 /**
Chris@0 309 * {@inheritdoc}
Chris@0 310 */
Chris@0 311 public function isDefaultRevision($new_value = NULL) {
Chris@0 312 $return = $this->isDefaultRevision;
Chris@0 313 if (isset($new_value)) {
Chris@0 314 $this->isDefaultRevision = (bool) $new_value;
Chris@0 315 }
Chris@0 316 // New entities should always ensure at least one default revision exists,
Chris@0 317 // creating an entity without a default revision is an invalid state.
Chris@0 318 return $this->isNew() || $return;
Chris@0 319 }
Chris@0 320
Chris@0 321 /**
Chris@0 322 * {@inheritdoc}
Chris@0 323 */
Chris@0 324 public function isRevisionTranslationAffected() {
Chris@0 325 $field_name = $this->getEntityType()->getKey('revision_translation_affected');
Chris@0 326 return $this->hasField($field_name) ? $this->get($field_name)->value : TRUE;
Chris@0 327 }
Chris@0 328
Chris@0 329 /**
Chris@0 330 * {@inheritdoc}
Chris@0 331 */
Chris@0 332 public function setRevisionTranslationAffected($affected) {
Chris@0 333 $field_name = $this->getEntityType()->getKey('revision_translation_affected');
Chris@0 334 if ($this->hasField($field_name)) {
Chris@0 335 $this->set($field_name, $affected);
Chris@0 336 }
Chris@0 337 return $this;
Chris@0 338 }
Chris@0 339
Chris@0 340 /**
Chris@0 341 * {@inheritdoc}
Chris@0 342 */
Chris@0 343 public function isDefaultTranslation() {
Chris@0 344 return $this->activeLangcode === LanguageInterface::LANGCODE_DEFAULT;
Chris@0 345 }
Chris@0 346
Chris@0 347 /**
Chris@0 348 * {@inheritdoc}
Chris@0 349 */
Chris@0 350 public function getRevisionId() {
Chris@0 351 return $this->getEntityKey('revision');
Chris@0 352 }
Chris@0 353
Chris@0 354 /**
Chris@0 355 * {@inheritdoc}
Chris@0 356 */
Chris@0 357 public function isTranslatable() {
Chris@0 358 // Check that the bundle is translatable, the entity has a language defined
Chris@0 359 // and if we have more than one language on the site.
Chris@0 360 $bundles = $this->entityManager()->getBundleInfo($this->entityTypeId);
Chris@0 361 return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual();
Chris@0 362 }
Chris@0 363
Chris@0 364 /**
Chris@0 365 * {@inheritdoc}
Chris@0 366 */
Chris@0 367 public function preSave(EntityStorageInterface $storage) {
Chris@0 368 // An entity requiring validation should not be saved if it has not been
Chris@0 369 // actually validated.
Chris@0 370 if ($this->validationRequired && !$this->validated) {
Chris@0 371 // @todo Make this an assertion in https://www.drupal.org/node/2408013.
Chris@0 372 throw new \LogicException('Entity validation was skipped.');
Chris@0 373 }
Chris@0 374 else {
Chris@0 375 $this->validated = FALSE;
Chris@0 376 }
Chris@0 377
Chris@0 378 parent::preSave($storage);
Chris@0 379 }
Chris@0 380
Chris@0 381 /**
Chris@0 382 * {@inheritdoc}
Chris@0 383 */
Chris@0 384 public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
Chris@0 385 }
Chris@0 386
Chris@0 387 /**
Chris@0 388 * {@inheritdoc}
Chris@0 389 */
Chris@0 390 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
Chris@0 391 parent::postSave($storage, $update);
Chris@0 392
Chris@0 393 // Update the status of all saved translations.
Chris@0 394 $removed = [];
Chris@0 395 foreach ($this->translations as $langcode => &$data) {
Chris@0 396 if ($data['status'] == static::TRANSLATION_REMOVED) {
Chris@0 397 $removed[$langcode] = TRUE;
Chris@0 398 }
Chris@0 399 else {
Chris@0 400 $data['status'] = static::TRANSLATION_EXISTING;
Chris@0 401 }
Chris@0 402 }
Chris@0 403 $this->translations = array_diff_key($this->translations, $removed);
Chris@0 404 }
Chris@0 405
Chris@0 406 /**
Chris@0 407 * {@inheritdoc}
Chris@0 408 */
Chris@0 409 public function validate() {
Chris@0 410 $this->validated = TRUE;
Chris@0 411 $violations = $this->getTypedData()->validate();
Chris@0 412 return new EntityConstraintViolationList($this, iterator_to_array($violations));
Chris@0 413 }
Chris@0 414
Chris@0 415 /**
Chris@0 416 * {@inheritdoc}
Chris@0 417 */
Chris@0 418 public function isValidationRequired() {
Chris@0 419 return (bool) $this->validationRequired;
Chris@0 420 }
Chris@0 421
Chris@0 422 /**
Chris@0 423 * {@inheritdoc}
Chris@0 424 */
Chris@0 425 public function setValidationRequired($required) {
Chris@0 426 $this->validationRequired = $required;
Chris@0 427 return $this;
Chris@0 428 }
Chris@0 429
Chris@0 430 /**
Chris@0 431 * Clear entity translation object cache to remove stale references.
Chris@0 432 */
Chris@0 433 protected function clearTranslationCache() {
Chris@0 434 foreach ($this->translations as &$translation) {
Chris@0 435 unset($translation['entity']);
Chris@0 436 }
Chris@0 437 }
Chris@0 438
Chris@0 439 /**
Chris@0 440 * {@inheritdoc}
Chris@0 441 */
Chris@0 442 public function __sleep() {
Chris@0 443 // Get the values of instantiated field objects, only serialize the values.
Chris@0 444 foreach ($this->fields as $name => $fields) {
Chris@0 445 foreach ($fields as $langcode => $field) {
Chris@0 446 $this->values[$name][$langcode] = $field->getValue();
Chris@0 447 }
Chris@0 448 }
Chris@0 449 $this->fields = [];
Chris@0 450 $this->fieldDefinitions = NULL;
Chris@0 451 $this->languages = NULL;
Chris@0 452 $this->clearTranslationCache();
Chris@0 453
Chris@0 454 return parent::__sleep();
Chris@0 455 }
Chris@0 456
Chris@0 457 /**
Chris@0 458 * {@inheritdoc}
Chris@0 459 */
Chris@0 460 public function id() {
Chris@0 461 return $this->getEntityKey('id');
Chris@0 462 }
Chris@0 463
Chris@0 464 /**
Chris@0 465 * {@inheritdoc}
Chris@0 466 */
Chris@0 467 public function bundle() {
Chris@0 468 return $this->getEntityKey('bundle');
Chris@0 469 }
Chris@0 470
Chris@0 471 /**
Chris@0 472 * {@inheritdoc}
Chris@0 473 */
Chris@0 474 public function uuid() {
Chris@0 475 return $this->getEntityKey('uuid');
Chris@0 476 }
Chris@0 477
Chris@0 478 /**
Chris@0 479 * {@inheritdoc}
Chris@0 480 */
Chris@0 481 public function hasField($field_name) {
Chris@0 482 return (bool) $this->getFieldDefinition($field_name);
Chris@0 483 }
Chris@0 484
Chris@0 485 /**
Chris@0 486 * {@inheritdoc}
Chris@0 487 */
Chris@0 488 public function get($field_name) {
Chris@0 489 if (!isset($this->fields[$field_name][$this->activeLangcode])) {
Chris@0 490 return $this->getTranslatedField($field_name, $this->activeLangcode);
Chris@0 491 }
Chris@0 492 return $this->fields[$field_name][$this->activeLangcode];
Chris@0 493 }
Chris@0 494
Chris@0 495 /**
Chris@0 496 * Gets a translated field.
Chris@0 497 *
Chris@0 498 * @return \Drupal\Core\Field\FieldItemListInterface
Chris@0 499 */
Chris@0 500 protected function getTranslatedField($name, $langcode) {
Chris@0 501 if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
Chris@0 502 throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
Chris@0 503 }
Chris@0 504 // Populate $this->fields to speed-up further look-ups and to keep track of
Chris@0 505 // fields objects, possibly holding changes to field values.
Chris@0 506 if (!isset($this->fields[$name][$langcode])) {
Chris@0 507 $definition = $this->getFieldDefinition($name);
Chris@0 508 if (!$definition) {
Chris@0 509 throw new \InvalidArgumentException("Field $name is unknown.");
Chris@0 510 }
Chris@0 511 // Non-translatable fields are always stored with
Chris@0 512 // LanguageInterface::LANGCODE_DEFAULT as key.
Chris@0 513
Chris@0 514 $default = $langcode == LanguageInterface::LANGCODE_DEFAULT;
Chris@0 515 if (!$default && !$definition->isTranslatable()) {
Chris@0 516 if (!isset($this->fields[$name][LanguageInterface::LANGCODE_DEFAULT])) {
Chris@0 517 $this->fields[$name][LanguageInterface::LANGCODE_DEFAULT] = $this->getTranslatedField($name, LanguageInterface::LANGCODE_DEFAULT);
Chris@0 518 }
Chris@0 519 $this->fields[$name][$langcode] = &$this->fields[$name][LanguageInterface::LANGCODE_DEFAULT];
Chris@0 520 }
Chris@0 521 else {
Chris@0 522 $value = NULL;
Chris@0 523 if (isset($this->values[$name][$langcode])) {
Chris@0 524 $value = $this->values[$name][$langcode];
Chris@0 525 }
Chris@0 526 $field = \Drupal::service('plugin.manager.field.field_type')->createFieldItemList($this->getTranslation($langcode), $name, $value);
Chris@0 527 if ($default) {
Chris@0 528 // $this->defaultLangcode might not be set if we are initializing the
Chris@0 529 // default language code cache, in which case there is no valid
Chris@0 530 // langcode to assign.
Chris@0 531 $field_langcode = isset($this->defaultLangcode) ? $this->defaultLangcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
Chris@0 532 }
Chris@0 533 else {
Chris@0 534 $field_langcode = $langcode;
Chris@0 535 }
Chris@0 536 $field->setLangcode($field_langcode);
Chris@0 537 $this->fields[$name][$langcode] = $field;
Chris@0 538 }
Chris@0 539 }
Chris@0 540 return $this->fields[$name][$langcode];
Chris@0 541 }
Chris@0 542
Chris@0 543 /**
Chris@0 544 * {@inheritdoc}
Chris@0 545 */
Chris@0 546 public function set($name, $value, $notify = TRUE) {
Chris@0 547 // Assign the value on the child and overrule notify such that we get
Chris@0 548 // notified to handle changes afterwards. We can ignore notify as there is
Chris@0 549 // no parent to notify anyway.
Chris@0 550 $this->get($name)->setValue($value, TRUE);
Chris@0 551 return $this;
Chris@0 552 }
Chris@0 553
Chris@0 554 /**
Chris@0 555 * {@inheritdoc}
Chris@0 556 */
Chris@0 557 public function getFields($include_computed = TRUE) {
Chris@0 558 $fields = [];
Chris@0 559 foreach ($this->getFieldDefinitions() as $name => $definition) {
Chris@0 560 if ($include_computed || !$definition->isComputed()) {
Chris@0 561 $fields[$name] = $this->get($name);
Chris@0 562 }
Chris@0 563 }
Chris@0 564 return $fields;
Chris@0 565 }
Chris@0 566
Chris@0 567 /**
Chris@0 568 * {@inheritdoc}
Chris@0 569 */
Chris@0 570 public function getTranslatableFields($include_computed = TRUE) {
Chris@0 571 $fields = [];
Chris@0 572 foreach ($this->getFieldDefinitions() as $name => $definition) {
Chris@0 573 if (($include_computed || !$definition->isComputed()) && $definition->isTranslatable()) {
Chris@0 574 $fields[$name] = $this->get($name);
Chris@0 575 }
Chris@0 576 }
Chris@0 577 return $fields;
Chris@0 578 }
Chris@0 579
Chris@0 580 /**
Chris@0 581 * {@inheritdoc}
Chris@0 582 */
Chris@0 583 public function getIterator() {
Chris@0 584 return new \ArrayIterator($this->getFields());
Chris@0 585 }
Chris@0 586
Chris@0 587 /**
Chris@0 588 * {@inheritdoc}
Chris@0 589 */
Chris@0 590 public function getFieldDefinition($name) {
Chris@0 591 if (!isset($this->fieldDefinitions)) {
Chris@0 592 $this->getFieldDefinitions();
Chris@0 593 }
Chris@0 594 if (isset($this->fieldDefinitions[$name])) {
Chris@0 595 return $this->fieldDefinitions[$name];
Chris@0 596 }
Chris@0 597 }
Chris@0 598
Chris@0 599 /**
Chris@0 600 * {@inheritdoc}
Chris@0 601 */
Chris@0 602 public function getFieldDefinitions() {
Chris@0 603 if (!isset($this->fieldDefinitions)) {
Chris@0 604 $this->fieldDefinitions = $this->entityManager()->getFieldDefinitions($this->entityTypeId, $this->bundle());
Chris@0 605 }
Chris@0 606 return $this->fieldDefinitions;
Chris@0 607 }
Chris@0 608
Chris@0 609 /**
Chris@0 610 * {@inheritdoc}
Chris@0 611 */
Chris@0 612 public function toArray() {
Chris@0 613 $values = [];
Chris@0 614 foreach ($this->getFields() as $name => $property) {
Chris@0 615 $values[$name] = $property->getValue();
Chris@0 616 }
Chris@0 617 return $values;
Chris@0 618 }
Chris@0 619
Chris@0 620 /**
Chris@0 621 * {@inheritdoc}
Chris@0 622 */
Chris@0 623 public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
Chris@0 624 if ($operation == 'create') {
Chris@0 625 return $this->entityManager()
Chris@0 626 ->getAccessControlHandler($this->entityTypeId)
Chris@0 627 ->createAccess($this->bundle(), $account, [], $return_as_object);
Chris@0 628 }
Chris@0 629 return $this->entityManager()
Chris@0 630 ->getAccessControlHandler($this->entityTypeId)
Chris@0 631 ->access($this, $operation, $account, $return_as_object);
Chris@0 632 }
Chris@0 633
Chris@0 634 /**
Chris@0 635 * {@inheritdoc}
Chris@0 636 */
Chris@0 637 public function language() {
Chris@0 638 $language = NULL;
Chris@0 639 if ($this->activeLangcode != LanguageInterface::LANGCODE_DEFAULT) {
Chris@0 640 if (!isset($this->languages[$this->activeLangcode])) {
Chris@0 641 $this->getLanguages();
Chris@0 642 }
Chris@0 643 $language = $this->languages[$this->activeLangcode];
Chris@0 644 }
Chris@0 645 else {
Chris@0 646 // @todo Avoid this check by getting the language from the language
Chris@0 647 // manager directly in https://www.drupal.org/node/2303877.
Chris@0 648 if (!isset($this->languages[$this->defaultLangcode])) {
Chris@0 649 $this->getLanguages();
Chris@0 650 }
Chris@0 651 $language = $this->languages[$this->defaultLangcode];
Chris@0 652 }
Chris@0 653 return $language;
Chris@0 654 }
Chris@0 655
Chris@0 656 /**
Chris@0 657 * Populates the local cache for the default language code.
Chris@0 658 */
Chris@0 659 protected function setDefaultLangcode() {
Chris@0 660 // Get the language code if the property exists.
Chris@0 661 // Try to read the value directly from the list of entity keys which got
Chris@0 662 // initialized in __construct(). This avoids creating a field item object.
Chris@0 663 if (isset($this->translatableEntityKeys['langcode'][$this->activeLangcode])) {
Chris@0 664 $this->defaultLangcode = $this->translatableEntityKeys['langcode'][$this->activeLangcode];
Chris@0 665 }
Chris@0 666 elseif ($this->hasField($this->langcodeKey) && ($item = $this->get($this->langcodeKey)) && isset($item->language)) {
Chris@0 667 $this->defaultLangcode = $item->language->getId();
Chris@0 668 $this->translatableEntityKeys['langcode'][$this->activeLangcode] = $this->defaultLangcode;
Chris@0 669 }
Chris@0 670
Chris@0 671 if (empty($this->defaultLangcode)) {
Chris@0 672 // Make sure we return a proper language object, if the entity has a
Chris@0 673 // langcode field, default to the site's default language.
Chris@0 674 if ($this->hasField($this->langcodeKey)) {
Chris@0 675 $this->defaultLangcode = $this->languageManager()->getDefaultLanguage()->getId();
Chris@0 676 }
Chris@0 677 else {
Chris@0 678 $this->defaultLangcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
Chris@0 679 }
Chris@0 680 }
Chris@0 681
Chris@0 682 // This needs to be initialized manually as it is skipped when instantiating
Chris@0 683 // the language field object to avoid infinite recursion.
Chris@0 684 if (!empty($this->fields[$this->langcodeKey])) {
Chris@0 685 $this->fields[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT]->setLangcode($this->defaultLangcode);
Chris@0 686 }
Chris@0 687 }
Chris@0 688
Chris@0 689 /**
Chris@0 690 * Updates language for already instantiated fields.
Chris@0 691 */
Chris@0 692 protected function updateFieldLangcodes($langcode) {
Chris@0 693 foreach ($this->fields as $name => $items) {
Chris@0 694 if (!empty($items[LanguageInterface::LANGCODE_DEFAULT])) {
Chris@0 695 $items[LanguageInterface::LANGCODE_DEFAULT]->setLangcode($langcode);
Chris@0 696 }
Chris@0 697 }
Chris@0 698 }
Chris@0 699
Chris@0 700 /**
Chris@0 701 * {@inheritdoc}
Chris@0 702 */
Chris@0 703 public function onChange($name) {
Chris@0 704 // Check if the changed name is the value of an entity key and if the value
Chris@0 705 // of that is currently cached, if so, reset it. Exclude the bundle from
Chris@0 706 // that check, as it ready only and must not change, unsetting it could
Chris@0 707 // lead to recursions.
Chris@0 708 if ($key = array_search($name, $this->getEntityType()->getKeys())) {
Chris@0 709 if ($key != 'bundle') {
Chris@0 710 if (isset($this->entityKeys[$key])) {
Chris@0 711 unset($this->entityKeys[$key]);
Chris@0 712 }
Chris@0 713 elseif (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
Chris@0 714 unset($this->translatableEntityKeys[$key][$this->activeLangcode]);
Chris@0 715 }
Chris@0 716 }
Chris@0 717 }
Chris@0 718
Chris@0 719 switch ($name) {
Chris@0 720 case $this->langcodeKey:
Chris@0 721 if ($this->isDefaultTranslation()) {
Chris@0 722 // Update the default internal language cache.
Chris@0 723 $this->setDefaultLangcode();
Chris@0 724 if (isset($this->translations[$this->defaultLangcode])) {
Chris@0 725 $message = SafeMarkup::format('A translation already exists for the specified language (@langcode).', ['@langcode' => $this->defaultLangcode]);
Chris@0 726 throw new \InvalidArgumentException($message);
Chris@0 727 }
Chris@0 728 $this->updateFieldLangcodes($this->defaultLangcode);
Chris@0 729 }
Chris@0 730 else {
Chris@0 731 // @todo Allow the translation language to be changed. See
Chris@0 732 // https://www.drupal.org/node/2443989.
Chris@0 733 $items = $this->get($this->langcodeKey);
Chris@0 734 if ($items->value != $this->activeLangcode) {
Chris@0 735 $items->setValue($this->activeLangcode, FALSE);
Chris@0 736 $message = SafeMarkup::format('The translation language cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
Chris@0 737 throw new \LogicException($message);
Chris@0 738 }
Chris@0 739 }
Chris@0 740 break;
Chris@0 741
Chris@0 742 case $this->defaultLangcodeKey:
Chris@0 743 // @todo Use a standard method to make the default_langcode field
Chris@0 744 // read-only. See https://www.drupal.org/node/2443991.
Chris@0 745 if (isset($this->values[$this->defaultLangcodeKey]) && $this->get($this->defaultLangcodeKey)->value != $this->isDefaultTranslation()) {
Chris@0 746 $this->get($this->defaultLangcodeKey)->setValue($this->isDefaultTranslation(), FALSE);
Chris@0 747 $message = SafeMarkup::format('The default translation flag cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
Chris@0 748 throw new \LogicException($message);
Chris@0 749 }
Chris@0 750 break;
Chris@0 751 }
Chris@0 752 }
Chris@0 753
Chris@0 754 /**
Chris@0 755 * {@inheritdoc}
Chris@0 756 */
Chris@0 757 public function getTranslation($langcode) {
Chris@0 758 // Ensure we always use the default language code when dealing with the
Chris@0 759 // original entity language.
Chris@0 760 if ($langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode == $this->defaultLangcode) {
Chris@0 761 $langcode = LanguageInterface::LANGCODE_DEFAULT;
Chris@0 762 }
Chris@0 763
Chris@0 764 // Populate entity translation object cache so it will be available for all
Chris@0 765 // translation objects.
Chris@0 766 if ($langcode == $this->activeLangcode) {
Chris@0 767 $this->translations[$langcode]['entity'] = $this;
Chris@0 768 }
Chris@0 769
Chris@0 770 // If we already have a translation object for the specified language we can
Chris@0 771 // just return it.
Chris@0 772 if (isset($this->translations[$langcode]['entity'])) {
Chris@0 773 $translation = $this->translations[$langcode]['entity'];
Chris@0 774 }
Chris@0 775 // Otherwise if an existing translation language was specified we need to
Chris@0 776 // instantiate the related translation.
Chris@0 777 elseif (isset($this->translations[$langcode])) {
Chris@0 778 $translation = $this->initializeTranslation($langcode);
Chris@0 779 $this->translations[$langcode]['entity'] = $translation;
Chris@0 780 }
Chris@0 781
Chris@0 782 if (empty($translation)) {
Chris@0 783 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
Chris@0 784 }
Chris@0 785
Chris@0 786 return $translation;
Chris@0 787 }
Chris@0 788
Chris@0 789 /**
Chris@0 790 * {@inheritdoc}
Chris@0 791 */
Chris@0 792 public function getUntranslated() {
Chris@0 793 return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
Chris@0 794 }
Chris@0 795
Chris@0 796 /**
Chris@0 797 * Instantiates a translation object for an existing translation.
Chris@0 798 *
Chris@0 799 * The translated entity will be a clone of the current entity with the
Chris@0 800 * specified $langcode. All translations share the same field data structures
Chris@0 801 * to ensure that all of them deal with fresh data.
Chris@0 802 *
Chris@0 803 * @param string $langcode
Chris@0 804 * The language code for the requested translation.
Chris@0 805 *
Chris@0 806 * @return \Drupal\Core\Entity\EntityInterface
Chris@0 807 * The translation object. The content properties of the translation object
Chris@0 808 * are stored as references to the main entity.
Chris@0 809 */
Chris@0 810 protected function initializeTranslation($langcode) {
Chris@0 811 // If the requested translation is valid, clone it with the current language
Chris@0 812 // as the active language. The $translationInitialize flag triggers a
Chris@0 813 // shallow (non-recursive) clone.
Chris@0 814 $this->translationInitialize = TRUE;
Chris@0 815 $translation = clone $this;
Chris@0 816 $this->translationInitialize = FALSE;
Chris@0 817
Chris@0 818 $translation->activeLangcode = $langcode;
Chris@0 819
Chris@0 820 // Ensure that changes to fields, values and translations are propagated
Chris@0 821 // to all the translation objects.
Chris@0 822 // @todo Consider converting these to ArrayObject.
Chris@0 823 $translation->values = &$this->values;
Chris@0 824 $translation->fields = &$this->fields;
Chris@0 825 $translation->translations = &$this->translations;
Chris@0 826 $translation->enforceIsNew = &$this->enforceIsNew;
Chris@0 827 $translation->newRevision = &$this->newRevision;
Chris@0 828 $translation->entityKeys = &$this->entityKeys;
Chris@0 829 $translation->translatableEntityKeys = &$this->translatableEntityKeys;
Chris@0 830 $translation->translationInitialize = FALSE;
Chris@0 831 $translation->typedData = NULL;
Chris@0 832 $translation->loadedRevisionId = &$this->loadedRevisionId;
Chris@0 833 $translation->isDefaultRevision = &$this->isDefaultRevision;
Chris@0 834
Chris@0 835 return $translation;
Chris@0 836 }
Chris@0 837
Chris@0 838 /**
Chris@0 839 * {@inheritdoc}
Chris@0 840 */
Chris@0 841 public function hasTranslation($langcode) {
Chris@0 842 if ($langcode == $this->defaultLangcode) {
Chris@0 843 $langcode = LanguageInterface::LANGCODE_DEFAULT;
Chris@0 844 }
Chris@0 845 return !empty($this->translations[$langcode]['status']);
Chris@0 846 }
Chris@0 847
Chris@0 848 /**
Chris@0 849 * {@inheritdoc}
Chris@0 850 */
Chris@0 851 public function isNewTranslation() {
Chris@0 852 return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED;
Chris@0 853 }
Chris@0 854
Chris@0 855 /**
Chris@0 856 * {@inheritdoc}
Chris@0 857 */
Chris@0 858 public function addTranslation($langcode, array $values = []) {
Chris@0 859 // Make sure we do not attempt to create a translation if an invalid
Chris@0 860 // language is specified or the entity cannot be translated.
Chris@0 861 $this->getLanguages();
Chris@0 862 if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) {
Chris@0 863 throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
Chris@0 864 }
Chris@0 865 if ($this->languages[$this->defaultLangcode]->isLocked()) {
Chris@0 866 throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
Chris@0 867 }
Chris@0 868
Chris@0 869 // Initialize the translation object.
Chris@0 870 /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
Chris@0 871 $storage = $this->entityManager()->getStorage($this->getEntityTypeId());
Chris@0 872 $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
Chris@0 873 return $storage->createTranslation($this, $langcode, $values);
Chris@0 874 }
Chris@0 875
Chris@0 876 /**
Chris@0 877 * {@inheritdoc}
Chris@0 878 */
Chris@0 879 public function removeTranslation($langcode) {
Chris@0 880 if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) {
Chris@0 881 foreach ($this->getFieldDefinitions() as $name => $definition) {
Chris@0 882 if ($definition->isTranslatable()) {
Chris@0 883 unset($this->values[$name][$langcode]);
Chris@0 884 unset($this->fields[$name][$langcode]);
Chris@0 885 }
Chris@0 886 }
Chris@0 887 // If removing a translation which has not been saved yet, then we have
Chris@0 888 // to remove it completely so that ::getTranslationStatus returns the
Chris@0 889 // proper status.
Chris@0 890 if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) {
Chris@0 891 unset($this->translations[$langcode]);
Chris@0 892 }
Chris@0 893 else {
Chris@0 894 if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) {
Chris@0 895 $this->translations[$langcode]['status_existed'] = TRUE;
Chris@0 896 }
Chris@0 897 $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED;
Chris@0 898 }
Chris@0 899 }
Chris@0 900 else {
Chris@0 901 throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed.");
Chris@0 902 }
Chris@0 903 }
Chris@0 904
Chris@0 905 /**
Chris@0 906 * {@inheritdoc}
Chris@0 907 */
Chris@0 908 public function getTranslationStatus($langcode) {
Chris@0 909 if ($langcode == $this->defaultLangcode) {
Chris@0 910 $langcode = LanguageInterface::LANGCODE_DEFAULT;
Chris@0 911 }
Chris@0 912 return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL;
Chris@0 913 }
Chris@0 914
Chris@0 915 /**
Chris@0 916 * {@inheritdoc}
Chris@0 917 */
Chris@0 918 public function getTranslationLanguages($include_default = TRUE) {
Chris@0 919 $translations = array_filter($this->translations, function ($translation) {
Chris@0 920 return $translation['status'];
Chris@0 921 });
Chris@0 922 unset($translations[LanguageInterface::LANGCODE_DEFAULT]);
Chris@0 923
Chris@0 924 if ($include_default) {
Chris@0 925 $translations[$this->defaultLangcode] = TRUE;
Chris@0 926 }
Chris@0 927
Chris@0 928 // Now load language objects based upon translation langcodes.
Chris@0 929 return array_intersect_key($this->getLanguages(), $translations);
Chris@0 930 }
Chris@0 931
Chris@0 932 /**
Chris@0 933 * Updates the original values with the interim changes.
Chris@0 934 */
Chris@0 935 public function updateOriginalValues() {
Chris@0 936 if (!$this->fields) {
Chris@0 937 return;
Chris@0 938 }
Chris@0 939 foreach ($this->getFieldDefinitions() as $name => $definition) {
Chris@0 940 if (!$definition->isComputed() && !empty($this->fields[$name])) {
Chris@0 941 foreach ($this->fields[$name] as $langcode => $item) {
Chris@0 942 $item->filterEmptyItems();
Chris@0 943 $this->values[$name][$langcode] = $item->getValue();
Chris@0 944 }
Chris@0 945 }
Chris@0 946 }
Chris@0 947 }
Chris@0 948
Chris@0 949 /**
Chris@0 950 * Implements the magic method for getting object properties.
Chris@0 951 *
Chris@0 952 * @todo: A lot of code still uses non-fields (e.g. $entity->content in view
Chris@0 953 * builders) by reference. Clean that up.
Chris@0 954 */
Chris@0 955 public function &__get($name) {
Chris@0 956 // If this is an entity field, handle it accordingly. We first check whether
Chris@0 957 // a field object has been already created. If not, we create one.
Chris@0 958 if (isset($this->fields[$name][$this->activeLangcode])) {
Chris@0 959 return $this->fields[$name][$this->activeLangcode];
Chris@0 960 }
Chris@0 961 // Inline getFieldDefinition() to speed things up.
Chris@0 962 if (!isset($this->fieldDefinitions)) {
Chris@0 963 $this->getFieldDefinitions();
Chris@0 964 }
Chris@0 965 if (isset($this->fieldDefinitions[$name])) {
Chris@0 966 $return = $this->getTranslatedField($name, $this->activeLangcode);
Chris@0 967 return $return;
Chris@0 968 }
Chris@0 969 // Else directly read/write plain values. That way, non-field entity
Chris@0 970 // properties can always be accessed directly.
Chris@0 971 if (!isset($this->values[$name])) {
Chris@0 972 $this->values[$name] = NULL;
Chris@0 973 }
Chris@0 974 return $this->values[$name];
Chris@0 975 }
Chris@0 976
Chris@0 977 /**
Chris@0 978 * Implements the magic method for setting object properties.
Chris@0 979 *
Chris@0 980 * Uses default language always.
Chris@0 981 */
Chris@0 982 public function __set($name, $value) {
Chris@0 983 // Inline getFieldDefinition() to speed things up.
Chris@0 984 if (!isset($this->fieldDefinitions)) {
Chris@0 985 $this->getFieldDefinitions();
Chris@0 986 }
Chris@0 987 // Handle Field API fields.
Chris@0 988 if (isset($this->fieldDefinitions[$name])) {
Chris@0 989 // Support setting values via property objects.
Chris@0 990 if ($value instanceof TypedDataInterface) {
Chris@0 991 $value = $value->getValue();
Chris@0 992 }
Chris@0 993 // If a FieldItemList object already exists, set its value.
Chris@0 994 if (isset($this->fields[$name][$this->activeLangcode])) {
Chris@0 995 $this->fields[$name][$this->activeLangcode]->setValue($value);
Chris@0 996 }
Chris@0 997 // If not, create one.
Chris@0 998 else {
Chris@0 999 $this->getTranslatedField($name, $this->activeLangcode)->setValue($value);
Chris@0 1000 }
Chris@0 1001 }
Chris@0 1002 // The translations array is unset when cloning the entity object, we just
Chris@0 1003 // need to restore it.
Chris@0 1004 elseif ($name == 'translations') {
Chris@0 1005 $this->translations = $value;
Chris@0 1006 }
Chris@0 1007 // Directly write non-field values.
Chris@0 1008 else {
Chris@0 1009 $this->values[$name] = $value;
Chris@0 1010 }
Chris@0 1011 }
Chris@0 1012
Chris@0 1013 /**
Chris@0 1014 * Implements the magic method for isset().
Chris@0 1015 */
Chris@0 1016 public function __isset($name) {
Chris@0 1017 // "Official" Field API fields are always set. For non-field properties,
Chris@0 1018 // check the internal values.
Chris@0 1019 return $this->hasField($name) ? TRUE : isset($this->values[$name]);
Chris@0 1020 }
Chris@0 1021
Chris@0 1022 /**
Chris@0 1023 * Implements the magic method for unset().
Chris@0 1024 */
Chris@0 1025 public function __unset($name) {
Chris@0 1026 // Unsetting a field means emptying it.
Chris@0 1027 if ($this->hasField($name)) {
Chris@0 1028 $this->get($name)->setValue([]);
Chris@0 1029 }
Chris@0 1030 // For non-field properties, unset the internal value.
Chris@0 1031 else {
Chris@0 1032 unset($this->values[$name]);
Chris@0 1033 }
Chris@0 1034 }
Chris@0 1035
Chris@0 1036 /**
Chris@0 1037 * {@inheritdoc}
Chris@0 1038 */
Chris@0 1039 public function createDuplicate() {
Chris@0 1040 if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
Chris@0 1041 throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
Chris@0 1042 }
Chris@0 1043
Chris@0 1044 $duplicate = clone $this;
Chris@0 1045 $entity_type = $this->getEntityType();
Chris@0 1046 $duplicate->{$entity_type->getKey('id')}->value = NULL;
Chris@0 1047 $duplicate->enforceIsNew();
Chris@0 1048
Chris@0 1049 // Check if the entity type supports UUIDs and generate a new one if so.
Chris@0 1050 if ($entity_type->hasKey('uuid')) {
Chris@0 1051 $duplicate->{$entity_type->getKey('uuid')}->value = $this->uuidGenerator()->generate();
Chris@0 1052 }
Chris@0 1053
Chris@0 1054 // Check whether the entity type supports revisions and initialize it if so.
Chris@0 1055 if ($entity_type->isRevisionable()) {
Chris@0 1056 $duplicate->{$entity_type->getKey('revision')}->value = NULL;
Chris@0 1057 $duplicate->loadedRevisionId = NULL;
Chris@0 1058 }
Chris@0 1059
Chris@0 1060 return $duplicate;
Chris@0 1061 }
Chris@0 1062
Chris@0 1063 /**
Chris@0 1064 * Magic method: Implements a deep clone.
Chris@0 1065 */
Chris@0 1066 public function __clone() {
Chris@0 1067 // Avoid deep-cloning when we are initializing a translation object, since
Chris@0 1068 // it will represent the same entity, only with a different active language.
Chris@0 1069 if ($this->translationInitialize) {
Chris@0 1070 return;
Chris@0 1071 }
Chris@0 1072
Chris@0 1073 // The translation is a different object, and needs its own TypedData
Chris@0 1074 // adapter object.
Chris@0 1075 $this->typedData = NULL;
Chris@0 1076 $definitions = $this->getFieldDefinitions();
Chris@0 1077
Chris@0 1078 // The translation cache has to be cleared before cloning the fields
Chris@0 1079 // below so that the call to getTranslation() does not re-use the
Chris@0 1080 // translation objects of the old entity but instead creates new
Chris@0 1081 // translation objects from the newly cloned entity. Otherwise the newly
Chris@0 1082 // cloned field item lists would hold references to the old translation
Chris@0 1083 // objects in their $parent property after the call to setContext().
Chris@0 1084 $this->clearTranslationCache();
Chris@0 1085
Chris@0 1086 // Because the new translation objects that are created below are
Chris@0 1087 // themselves created by *cloning* the newly cloned entity we need to
Chris@0 1088 // make sure that the references to property values are properly cloned
Chris@0 1089 // before cloning the fields. Otherwise calling
Chris@0 1090 // $items->getEntity()->isNew(), for example, would return the
Chris@0 1091 // $enforceIsNew value of the old entity.
Chris@0 1092
Chris@0 1093 // Ensure the translations array is actually cloned by overwriting the
Chris@0 1094 // original reference with one pointing to a copy of the array.
Chris@0 1095 $translations = $this->translations;
Chris@0 1096 $this->translations = &$translations;
Chris@0 1097
Chris@0 1098 // Ensure that the following properties are actually cloned by
Chris@0 1099 // overwriting the original references with ones pointing to copies of
Chris@0 1100 // them: enforceIsNew, newRevision, loadedRevisionId, fields, entityKeys,
Chris@0 1101 // translatableEntityKeys, values and isDefaultRevision.
Chris@0 1102 $enforce_is_new = $this->enforceIsNew;
Chris@0 1103 $this->enforceIsNew = &$enforce_is_new;
Chris@0 1104
Chris@0 1105 $new_revision = $this->newRevision;
Chris@0 1106 $this->newRevision = &$new_revision;
Chris@0 1107
Chris@0 1108 $original_revision_id = $this->loadedRevisionId;
Chris@0 1109 $this->loadedRevisionId = &$original_revision_id;
Chris@0 1110
Chris@0 1111 $fields = $this->fields;
Chris@0 1112 $this->fields = &$fields;
Chris@0 1113
Chris@0 1114 $entity_keys = $this->entityKeys;
Chris@0 1115 $this->entityKeys = &$entity_keys;
Chris@0 1116
Chris@0 1117 $translatable_entity_keys = $this->translatableEntityKeys;
Chris@0 1118 $this->translatableEntityKeys = &$translatable_entity_keys;
Chris@0 1119
Chris@0 1120 $values = $this->values;
Chris@0 1121 $this->values = &$values;
Chris@0 1122
Chris@0 1123 $default_revision = $this->isDefaultRevision;
Chris@0 1124 $this->isDefaultRevision = &$default_revision;
Chris@0 1125
Chris@0 1126 foreach ($this->fields as $name => $fields_by_langcode) {
Chris@0 1127 $this->fields[$name] = [];
Chris@0 1128 // Untranslatable fields may have multiple references for the same field
Chris@0 1129 // object keyed by language. To avoid creating different field objects
Chris@0 1130 // we retain just the original value, as references will be recreated
Chris@0 1131 // later as needed.
Chris@0 1132 if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) {
Chris@0 1133 $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]);
Chris@0 1134 }
Chris@0 1135 foreach ($fields_by_langcode as $langcode => $items) {
Chris@0 1136 $this->fields[$name][$langcode] = clone $items;
Chris@0 1137 $this->fields[$name][$langcode]->setContext($name, $this->getTranslation($langcode)->getTypedData());
Chris@0 1138 }
Chris@0 1139 }
Chris@0 1140 }
Chris@0 1141
Chris@0 1142 /**
Chris@0 1143 * {@inheritdoc}
Chris@0 1144 */
Chris@0 1145 public function label() {
Chris@0 1146 $label = NULL;
Chris@0 1147 $entity_type = $this->getEntityType();
Chris@0 1148 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
Chris@0 1149 $label = call_user_func($label_callback, $this);
Chris@0 1150 }
Chris@0 1151 elseif (($label_key = $entity_type->getKey('label'))) {
Chris@0 1152 $label = $this->getEntityKey('label');
Chris@0 1153 }
Chris@0 1154 return $label;
Chris@0 1155 }
Chris@0 1156
Chris@0 1157 /**
Chris@0 1158 * {@inheritdoc}
Chris@0 1159 */
Chris@0 1160 public function referencedEntities() {
Chris@0 1161 $referenced_entities = [];
Chris@0 1162
Chris@0 1163 // Gather a list of referenced entities.
Chris@0 1164 foreach ($this->getFields() as $field_items) {
Chris@0 1165 foreach ($field_items as $field_item) {
Chris@0 1166 // Loop over all properties of a field item.
Chris@0 1167 foreach ($field_item->getProperties(TRUE) as $property) {
Chris@0 1168 if ($property instanceof EntityReference && $entity = $property->getValue()) {
Chris@0 1169 $referenced_entities[] = $entity;
Chris@0 1170 }
Chris@0 1171 }
Chris@0 1172 }
Chris@0 1173 }
Chris@0 1174
Chris@0 1175 return $referenced_entities;
Chris@0 1176 }
Chris@0 1177
Chris@0 1178 /**
Chris@0 1179 * Gets the value of the given entity key, if defined.
Chris@0 1180 *
Chris@0 1181 * @param string $key
Chris@0 1182 * Name of the entity key, for example id, revision or bundle.
Chris@0 1183 *
Chris@0 1184 * @return mixed
Chris@0 1185 * The value of the entity key, NULL if not defined.
Chris@0 1186 */
Chris@0 1187 protected function getEntityKey($key) {
Chris@0 1188 // If the value is known already, return it.
Chris@0 1189 if (isset($this->entityKeys[$key])) {
Chris@0 1190 return $this->entityKeys[$key];
Chris@0 1191 }
Chris@0 1192 if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
Chris@0 1193 return $this->translatableEntityKeys[$key][$this->activeLangcode];
Chris@0 1194 }
Chris@0 1195
Chris@0 1196 // Otherwise fetch the value by creating a field object.
Chris@0 1197 $value = NULL;
Chris@0 1198 if ($this->getEntityType()->hasKey($key)) {
Chris@0 1199 $field_name = $this->getEntityType()->getKey($key);
Chris@0 1200 $definition = $this->getFieldDefinition($field_name);
Chris@0 1201 $property = $definition->getFieldStorageDefinition()->getMainPropertyName();
Chris@0 1202 $value = $this->get($field_name)->$property;
Chris@0 1203
Chris@0 1204 // Put it in the right array, depending on whether it is translatable.
Chris@0 1205 if ($definition->isTranslatable()) {
Chris@0 1206 $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
Chris@0 1207 }
Chris@0 1208 else {
Chris@0 1209 $this->entityKeys[$key] = $value;
Chris@0 1210 }
Chris@0 1211 }
Chris@0 1212 else {
Chris@0 1213 $this->entityKeys[$key] = $value;
Chris@0 1214 }
Chris@0 1215 return $value;
Chris@0 1216 }
Chris@0 1217
Chris@0 1218 /**
Chris@0 1219 * {@inheritdoc}
Chris@0 1220 */
Chris@0 1221 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
Chris@0 1222 $fields = [];
Chris@0 1223 if ($entity_type->hasKey('id')) {
Chris@0 1224 $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')
Chris@0 1225 ->setLabel(new TranslatableMarkup('ID'))
Chris@0 1226 ->setReadOnly(TRUE)
Chris@0 1227 ->setSetting('unsigned', TRUE);
Chris@0 1228 }
Chris@0 1229 if ($entity_type->hasKey('uuid')) {
Chris@0 1230 $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')
Chris@0 1231 ->setLabel(new TranslatableMarkup('UUID'))
Chris@0 1232 ->setReadOnly(TRUE);
Chris@0 1233 }
Chris@0 1234 if ($entity_type->hasKey('revision')) {
Chris@0 1235 $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')
Chris@0 1236 ->setLabel(new TranslatableMarkup('Revision ID'))
Chris@0 1237 ->setReadOnly(TRUE)
Chris@0 1238 ->setSetting('unsigned', TRUE);
Chris@0 1239 }
Chris@0 1240 if ($entity_type->hasKey('langcode')) {
Chris@0 1241 $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language')
Chris@0 1242 ->setLabel(new TranslatableMarkup('Language'))
Chris@0 1243 ->setDisplayOptions('view', [
Chris@0 1244 'region' => 'hidden',
Chris@0 1245 ])
Chris@0 1246 ->setDisplayOptions('form', [
Chris@0 1247 'type' => 'language_select',
Chris@0 1248 'weight' => 2,
Chris@0 1249 ]);
Chris@0 1250 if ($entity_type->isRevisionable()) {
Chris@0 1251 $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
Chris@0 1252 }
Chris@0 1253 if ($entity_type->isTranslatable()) {
Chris@0 1254 $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
Chris@0 1255 }
Chris@0 1256 }
Chris@0 1257 if ($entity_type->hasKey('bundle')) {
Chris@0 1258 if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
Chris@0 1259 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference')
Chris@0 1260 ->setLabel($entity_type->getBundleLabel())
Chris@0 1261 ->setSetting('target_type', $bundle_entity_type_id)
Chris@0 1262 ->setRequired(TRUE)
Chris@0 1263 ->setReadOnly(TRUE);
Chris@0 1264 }
Chris@0 1265 else {
Chris@0 1266 $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')
Chris@0 1267 ->setLabel($entity_type->getBundleLabel())
Chris@0 1268 ->setRequired(TRUE)
Chris@0 1269 ->setReadOnly(TRUE);
Chris@0 1270 }
Chris@0 1271 }
Chris@0 1272
Chris@0 1273 return $fields;
Chris@0 1274 }
Chris@0 1275
Chris@0 1276 /**
Chris@0 1277 * {@inheritdoc}
Chris@0 1278 */
Chris@0 1279 public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
Chris@0 1280 return [];
Chris@0 1281 }
Chris@0 1282
Chris@0 1283 /**
Chris@0 1284 * Returns an array of field names to skip in ::hasTranslationChanges.
Chris@0 1285 *
Chris@0 1286 * @return array
Chris@0 1287 * An array of field names.
Chris@0 1288 */
Chris@0 1289 protected function getFieldsToSkipFromTranslationChangesCheck() {
Chris@0 1290 /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
Chris@0 1291 $entity_type = $this->getEntityType();
Chris@0 1292 // A list of known revision metadata fields which should be skipped from
Chris@0 1293 // the comparision.
Chris@0 1294 $fields = [
Chris@0 1295 $entity_type->getKey('revision'),
Chris@0 1296 'revision_translation_affected',
Chris@0 1297 ];
Chris@0 1298 $fields = array_merge($fields, array_values($entity_type->getRevisionMetadataKeys()));
Chris@0 1299
Chris@0 1300 return $fields;
Chris@0 1301 }
Chris@0 1302
Chris@0 1303 /**
Chris@0 1304 * {@inheritdoc}
Chris@0 1305 */
Chris@0 1306 public function hasTranslationChanges() {
Chris@0 1307 if ($this->isNew()) {
Chris@0 1308 return TRUE;
Chris@0 1309 }
Chris@0 1310
Chris@0 1311 // $this->original only exists during save. See
Chris@0 1312 // \Drupal\Core\Entity\EntityStorageBase::save(). If it exists we re-use it
Chris@0 1313 // here for performance reasons.
Chris@0 1314 /** @var \Drupal\Core\Entity\ContentEntityBase $original */
Chris@0 1315 $original = $this->original ? $this->original : NULL;
Chris@0 1316
Chris@0 1317 if (!$original) {
Chris@0 1318 $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id();
Chris@0 1319 $original = $this->entityManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id);
Chris@0 1320 }
Chris@0 1321
Chris@0 1322 // If the current translation has just been added, we have a change.
Chris@0 1323 $translated = count($this->translations) > 1;
Chris@0 1324 if ($translated && !$original->hasTranslation($this->activeLangcode)) {
Chris@0 1325 return TRUE;
Chris@0 1326 }
Chris@0 1327
Chris@0 1328 // Compare field item current values with the original ones to determine
Chris@0 1329 // whether we have changes. If a field is not translatable and the entity is
Chris@0 1330 // translated we skip it because, depending on the use case, it would make
Chris@0 1331 // sense to mark all translations as changed or none of them. We skip also
Chris@0 1332 // computed fields as comparing them with their original values might not be
Chris@0 1333 // possible or be meaningless.
Chris@0 1334 /** @var \Drupal\Core\Entity\ContentEntityBase $translation */
Chris@0 1335 $translation = $original->getTranslation($this->activeLangcode);
Chris@0 1336
Chris@0 1337 // The list of fields to skip from the comparision.
Chris@0 1338 $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck();
Chris@0 1339
Chris@0 1340 foreach ($this->getFieldDefinitions() as $field_name => $definition) {
Chris@0 1341 // @todo Avoid special-casing the following fields. See
Chris@0 1342 // https://www.drupal.org/node/2329253.
Chris@0 1343 if (in_array($field_name, $skip_fields, TRUE)) {
Chris@0 1344 continue;
Chris@0 1345 }
Chris@0 1346 $field = $this->get($field_name);
Chris@0 1347 // When saving entities in the user interface, the changed timestamp is
Chris@0 1348 // automatically incremented by ContentEntityForm::submitForm() even if
Chris@0 1349 // nothing was actually changed. Thus, the changed time needs to be
Chris@0 1350 // ignored when determining whether there are any actual changes in the
Chris@0 1351 // entity.
Chris@0 1352 if (!($field instanceof ChangedFieldItemList) && !$definition->isComputed()) {
Chris@0 1353 $items = $field->filterEmptyItems();
Chris@0 1354 $original_items = $translation->get($field_name)->filterEmptyItems();
Chris@0 1355 if (!$items->equals($original_items)) {
Chris@0 1356 return TRUE;
Chris@0 1357 }
Chris@0 1358 }
Chris@0 1359 }
Chris@0 1360
Chris@0 1361 return FALSE;
Chris@0 1362 }
Chris@0 1363
Chris@0 1364 }