You are here

public function SimpleLdapUserMap::mapFromDrupalToLdap in Simple LDAP 7

Map from Drupal to LDAP.

Parameters

stdClass $drupal_user: The Drupal user account object.

SimpleLdapUser $ldap_user: The LDAP user object.

File

simple_ldap_user/SimpleLdapUserMap.class.php, line 203
Class defining the LDAP <-> Drupal user field mappings.

Class

SimpleLdapUserMap
@file Class defining the LDAP <-> Drupal user field mappings.

Code

public function mapFromDrupalToLdap(stdClass $drupal_user, SimpleLdapUser $ldap_user) {

  // Synchronize the fields in the attribute map.
  foreach ($this->map as $attribute) {

    // Initialize the Drupal value array.
    $drupal_values = array();

    // Parse the drupal attribute name.
    foreach ($attribute['drupal'] as $drupal_attribute) {

      // Skip this field if it couldn't be parsed.
      if (!($parsed = $this
        ->parseDrupalAttribute($drupal_attribute))) {
        continue;
      }
      list($is_field, $field_name) = $parsed;

      // If this is a Field API field, use Field API to get the values.
      if ($is_field) {

        // If we have no items, just skip this field.
        if (!($items = field_get_items('user', $drupal_user, $field_name))) {
          continue;
        }

        // Otherwise, set up an array of values.
        $values = array();

        // Parse the columns from the attribute name.
        $columns = $this
          ->drupalAttributeColumns($drupal_attribute);
        foreach ($items as $key => $item) {

          // If we have a value, add it to the array.
          if ($value = drupal_array_get_nested_value($item, $columns)) {
            $values[] = $value;
          }
        }
        $drupal_values[] = $values;
      }
      else {

        // Get the value directly from the user object.
        $drupal_values[] = array(
          $drupal_user->{$field_name},
        );
      }
    }

    // Merge the $drupal_values array into uniform values for the LDAP server.
    // This is needed to account for drupal attributes of mixed types.
    // First, find the largest value array.
    $size = 0;
    foreach ($drupal_values as $drupal_value) {
      $count = count($drupal_value);
      if ($count > $size) {
        $size = $count;
      }
    }

    // Then, generate the ldap array.
    $ldap_values = array();
    for ($i = 0; $i < $size; $i++) {
      $ldap_values[$i] = '';
      foreach ($drupal_values as $values) {
        if (isset($values[$i])) {
          $ldap_values[$i] .= ' ' . $values[$i];
        }
      }
      $ldap_values[$i] = trim($ldap_values[$i]);
    }

    // Finally, add the values to the LDAP user.
    $ldap_user->{$attribute['ldap']} = $ldap_values;
  }
}