You are here

public function ApiSync::syncForms in FormAssembly 8

Process form data from FormAssembly and perform CRUD ops as needed.

Parameters

string $id: The id to use as a cache id.

File

src/ApiSync.php, line 341

Class

ApiSync
Service class for FormAssembly API: Handles form sync.

Namespace

Drupal\formassembly

Code

public function syncForms($id = '') {
  $this
    ->loadFromCache($id);
  try {
    $formsByFaId = [];
    foreach ($this->forms as $formData) {
      $formsByFaId[$formData['Form']['id']] = [
        'faid' => $formData['Form']['id'],
        'name' => Xss::filter(Html::decodeEntities($formData['Form']['name'])),
        'modified' => date('U', strtotime($formData['Form']['modified'])),
      ];
    }

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

      // Load an existing FormAssembly entity if one matches
      // $formData['faid'] or create a new entity otherwise.
      $searchByFaId = $this->faStorage
        ->loadByProperties([
        'faid' => $formData['faid'],
      ]);

      // The search returns data as an array keyed by eid or an empty array if
      // no match.
      if (!empty($searchByFaId)) {

        // There should only be one item - faid is a unique key so pop
        // the first item off the array.

        /** @var \Drupal\formassembly\Entity\FormAssemblyEntity $formAssemblyEntity */
        $formAssemblyEntity = array_shift($searchByFaId);

        // Update forms that have changed since the last sync.
        if ($formAssemblyEntity
          ->getModifiedTime() < $formData['modified']) {

          // Update the title and modified date stored.
          $formAssemblyEntity
            ->setModifiedTime($formData['modified']);
          $formAssemblyEntity
            ->setName($formData['name']);
          $formAssemblyEntity
            ->enable();
          $formAssemblyEntity
            ->save();
        }
      }
      else {
        $newEntity = $this->faStorage
          ->create($formData);
        $newEntity
          ->save();
      }
    }
    $this->faStorage
      ->disableInactive(array_keys($formsByFaId));
    $this->logger
      ->info('Form sync complete.');

    // Clean up any cached data.
    $this
      ->clearCache($id);
  } catch (\Exception $e) {
    $this->logger
      ->critical('FormAssembly syncForms request failed with Exception: %exception_type.', [
      '%exception_type' => get_class($e),
    ]);
    throw $e;
  }
}