SimpleSourceTrait.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: fgm
  5. * Date: 11/04/2017
  6. * Time: 08:35
  7. */
  8. namespace Drupal\reinstall\Plugin\migrate\source;
  9. trait SimpleSourceTrait {
  10. protected $sstEntityTypeBundleInfo;
  11. protected $sstEntityFieldManager;
  12. protected $sstEntityType;
  13. protected function getEntityTypeBundleInfo() {
  14. if (!isset($this->sstEntityTypeBundleInfo)) {
  15. $this->sstEntityTypeBundleInfo = \Drupal::service('entity_type.bundle.info');
  16. }
  17. return $this->sstEntityTypeBundleInfo;
  18. }
  19. protected function getEntityFieldManager() {
  20. if (!isset($this->sstEntityFieldManager)) {
  21. $this->sstEntityFieldManager = \Drupal::service('entity_field.manager');
  22. }
  23. return $this->sstEntityFieldManager;
  24. }
  25. protected function getEntityType() {
  26. assert(isset($this->sstEntityType));
  27. return $this->sstEntityType;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function fields() {
  33. $bundles = $this->getEntityTypeBundleInfo()
  34. ->getBundleInfo($typeName = $this->getEntityType());
  35. $rows = [];
  36. foreach ($bundles as $bundleName => $bundle) {
  37. $fieldDefinitions = $this->getEntityFieldManager()
  38. ->getFieldDefinitions($typeName, $bundleName);
  39. foreach ($fieldDefinitions as $fieldName => $fieldDefinition) {
  40. $rows[$fieldName][$bundleName] = $fieldDefinition->getLabel();
  41. }
  42. }
  43. $fields = [];
  44. $singleBundle = count($bundles) === 1;
  45. foreach ($rows as $fieldName => $labels) {
  46. if ($singleBundle) {
  47. $fields[$fieldName] = reset($labels);
  48. continue;
  49. }
  50. if (count(array_unique($labels)) === 1) {
  51. $fields[$fieldName] = reset($labels);
  52. continue;
  53. }
  54. $ret = [];
  55. ksort($labels);
  56. foreach ($labels as $ct => $label) {
  57. $ret[] = $this->t('@ct: @label', ['@ct' => $ct, '@label' => $label]);
  58. }
  59. $fields[$fieldName] = implode(', ', $ret);
  60. }
  61. ksort($fields);
  62. return $fields;
  63. }
  64. }