You are here

public function FormAssemblyRequest::syncForms in FormAssembly 7

Request all form data from FormAssembly and perform CRUD ops as needed.

File

includes/FormAssemblyRequest.php, line 141
Authorizes the current site and handles API requests to FormAssembly.

Class

FormAssemblyRequest
@file Authorizes the current site and handles API requests to FormAssembly.

Code

public function syncForms() {
  $forms_by_faid = array();
  $fa_form_controller = entity_get_controller('fa_form');
  foreach ($this->forms as $form_item) {
    $forms_by_faid[$form_item['Form']['id']] = array(
      'faid' => $form_item['Form']['id'],
      'name' => filter_xss(decode_entities($form_item['Form']['name'])),
      'modified' => date('U', strtotime($form_item['Form']['modified'])),
    );
  }

  // Update forms that have changed since the last sync.
  foreach ($forms_by_faid as $form_data) {

    // Load an existing fa_id entity if one matches $form_data->id or
    // create a new entity otherwise.
    $fa_form_search = $fa_form_controller
      ->loadByProperties(array(
      'faid' => $form_data['faid'],
    ));

    // The search returns data as an array keyed by eid or an empty array if
    // no match. There should only be one item - faid is a unique key so pop
    // the first item off the array or we get NULL if the array was empty...
    $found_form = array_shift($fa_form_search);
    if ($found_form != NULL) {

      // Update forms that have changed since the last sync.
      if ($found_form
        ->getModified() < $form_data['modified']) {

        // Update the title and modified date stored.
        $found_form
          ->updateData($form_data);
        $fa_form_controller
          ->save($found_form);
      }
    }
    else {
      $new_fa_form = $fa_form_controller
        ->create($form_data);
      $fa_form_controller
        ->save($new_fa_form);
    }

    // Now check for fa_forms that are no longer in $forms_by_faid.
    // First pull the faids currently stored...
    $stored = $fa_form_controller
      ->loadPropertySet('faid');

    // Now check those against the faids from the rest request...
    foreach ($stored as $record) {
      if (!array_key_exists($record->faid, $forms_by_faid)) {

        // The faid of the current record is not a key of $forms_by_faid,
        // so the form is no longer in FormAssembly.
        $eids_to_delete[] = $record->eid;
      }
    }
    if (isset($eids_to_delete)) {
      formassembly_delete_multiple($eids_to_delete);
    }
  }
  watchdog('formassembly', 'Form sync complete.', array(), WATCHDOG_NOTICE);
}