You are here

function ContactComponent::wf_crm_find_relations in Webform CiviCRM Integration 8.5

Get a contact's relations of certain types

Parameters

int cid: Contact id

array types: Array of relationship_type_ids

bool $current: Limit to current & enabled relations?

Return value

array

Overrides ContactComponentInterface::wf_crm_find_relations

1 call to ContactComponent::wf_crm_find_relations()
ContactComponent::wf_crm_contact_search in src/ContactComponent.php
Returns a list of contacts based on component settings.

File

src/ContactComponent.php, line 246

Class

ContactComponent
Class ContactComponent

Namespace

Drupal\webform_civicrm

Code

function wf_crm_find_relations($cid, $types = [], $current = TRUE) {
  $utils = \Drupal::service('webform_civicrm.utils');
  $found = $allowed = $type_ids = [];
  $cid = (int) $cid;
  static $employer_type = 0;
  if ($cid) {
    if (!$employer_type && $current) {
      $employer_type = \CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_relationship_type WHERE name_a_b = 'Employee of'");
    }
    foreach ($types as $t) {
      list($type, $a) = explode('_', $t);

      // Put current employer first in the list
      if ($type == $employer_type && $current) {
        $search_key = $a == 'b' ? 'id' : 'employer_id';

        // Note: inconsistency in api3 - search key is "employer_id" but return key is "current_employer_id"
        $employer = $utils
          ->wf_crm_apivalues('contact', 'get', [
          $search_key => $cid,
          'sequential' => 1,
        ], $a == 'b' ? 'current_employer_id' : 'id');
        if ($employer) {
          $found[$employer[0]] = $employer[0];
        }
      }
      $type_ids[] = $type;
      if ($a == 'a' || $a == 'r') {
        $allowed[] = $type . '_a';
      }
      if ($a == 'b' || $a == 'r') {
        $allowed[] = $type . '_b';
      }
    }
    $params = [
      'return' => [
        'contact_id_a',
        'contact_id_b',
        'relationship_type_id',
        'end_date',
      ],
      'contact_id_a' => $cid,
      'contact_id_b' => $cid,
      'options' => [
        'or' => [
          [
            'contact_id_a',
            'contact_id_b',
          ],
        ],
      ],
    ];
    if ($type_ids) {
      $params['relationship_type_id'] = [
        'IN' => $type_ids,
      ];
    }
    if ($current) {
      $params['is_active'] = 1;
    }
    foreach ($utils
      ->wf_crm_apivalues('relationship', 'get', $params) as $relationship) {
      $a = $relationship['contact_id_a'] == $cid ? 'b' : 'a';
      if (!$current || empty($relationship['end_date']) || strtotime($relationship['end_date']) > time()) {
        if (!$allowed || in_array($relationship['relationship_type_id'] . '_' . $a, $allowed)) {
          $c = $relationship["contact_id_{$a}"];
          $found[$c] = $c;
        }
      }
    }
  }
  return $found;
}