ContentEntityBase.php 48 KB

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