annotate core/lib/Drupal/Core/Entity/ContentEntityBase.php @ 19:fa3358dc1485 tip

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