ProfileTestTrait.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\profile;
  3. use Drupal\profile\Entity\ProfileTypeInterface;
  4. use Drupal\profile\Entity\ProfileType;
  5. use Drupal\profile\Entity\Profile;
  6. use Drupal\user\UserInterface;
  7. /**
  8. * Provides methods to create additional profiles and profile_types.
  9. *
  10. * This trait is meant to be used only by test classes.
  11. */
  12. trait ProfileTestTrait {
  13. /**
  14. * Creates a profile type for tests.
  15. *
  16. * @param string $id
  17. * The profile type machine name.
  18. * @param string $label
  19. * The profile type human display name.
  20. * @param bool $registration
  21. * Boolean if profile type shows on registration form.
  22. * @param array $roles
  23. * Array of user role machine names.
  24. *
  25. * @return \Drupal\profile\Entity\ProfileTypeInterface
  26. * Returns a profile type entity.
  27. */
  28. protected function createProfileType($id = NULL, $label = NULL, $registration = FALSE, array $roles = []) {
  29. $id = !empty($id) ? $id : $this->randomMachineName();
  30. $label = !empty($label) ? $label : $this->randomMachineName();
  31. $type = ProfileType::create([
  32. 'id' => $id,
  33. 'label' => $label,
  34. 'registration' => $registration,
  35. 'roles' => $roles,
  36. ]);
  37. $type->save();
  38. return $type;
  39. }
  40. /**
  41. * Create a user, and optionally a profile.
  42. *
  43. * @param \Drupal\profile\Entity\ProfileTypeInterface $profile_type
  44. * A profile type for the created profile entity.
  45. * @param \Drupal\user\UserInterface $user
  46. * A user to create a profile.
  47. *
  48. * @return \Drupal\profile\Entity\ProfileInterface
  49. * A profile for a user.
  50. */
  51. protected function createProfile(ProfileTypeInterface $profile_type, UserInterface $user) {
  52. $profile = Profile::create([
  53. 'type' => $profile_type->id(),
  54. 'uid' => $user->id(),
  55. ]);
  56. $profile->save();
  57. return $profile;
  58. }
  59. }