You are here

public function SocialProfileNameService::getProfileName in Open Social 10.3.x

Same name and namespace in other branches
  1. 10.2.x modules/social_features/social_profile/src/SocialProfileNameService.php \Drupal\social_profile\SocialProfileNameService::getProfileName()

Get profile name.

Parameters

\Drupal\profile\Entity\ProfileInterface|null $profile: The profile.

Return value

string|void The generated profile name value.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

modules/social_features/social_profile/src/SocialProfileNameService.php, line 111

Class

SocialProfileNameService
Provide a service for Profile name.

Namespace

Drupal\social_profile

Code

public function getProfileName(ProfileInterface $profile = NULL) {

  // Do nothing if no profile.
  if ($profile == NULL) {
    return '';
  }

  /** @var \Drupal\user\UserStorageInterface $user_storage */
  $user_storage = $this->entityTypeManager
    ->getStorage('user');

  /** @var \Drupal\user\UserInterface $account */
  $account = $user_storage
    ->load($profile
    ->getOwnerId());

  // Set default profile name.
  $account_name = $account
    ->getAccountName();

  // If enable module social_profile_privacy we need get hidden fields and
  // later check if the Profile name fields are there.
  $private_fields_list = [];
  if ($this->moduleHandler
    ->moduleExists('social_profile_privacy')) {

    // Get profile private fields list.
    $uid = $account
      ->id();
    $private_fields_list = social_profile_privacy_private_fields_list($uid);
  }
  $account_name_fields = SocialProfileNameService::getProfileNameFields();

  // We do nothing further if all fields of the Profile name are hidden.
  if (count(array_intersect($private_fields_list, $account_name_fields)) == count($account_name_fields)) {
    return $account_name;
  }
  $account_name_values = [];

  // We need set Nickname as Profile name if that field is not hidden and not
  // empty.
  if (!in_array('field_profile_nick_name', $private_fields_list) && in_array('field_profile_nick_name', $account_name_fields) && !empty($nick_name = $profile
    ->get('field_profile_nick_name')
    ->getString())) {
    $account_name = $nick_name;
  }
  else {

    // We need concatenate Firstname and Lastname for Profile name if at least
    // one of those fields are not hidden and not empty.
    foreach ($account_name_fields as $account_name_field) {
      if (!in_array($account_name_field, $private_fields_list) && !empty($name_field = $profile
        ->get($account_name_field)
        ->getString())) {
        $account_name_values[] = $name_field;
      }
    }
    if (!empty($account_name_values) && !empty($full_name = implode(" ", $account_name_values))) {
      $account_name = $full_name;
    }
  }
  return $account_name;
}