You are here

class EntitySaveHandler in Services Client 7.2

General entity save handler.

Hierarchy

Expanded class hierarchy of EntitySaveHandler

4 string references to 'EntitySaveHandler'
hook_services_client_event_handler in ./services_client.api.php
ctools hook for Event Hanlder plugin discover.
ServicesClientBaseWebTestCase::createSCEvent in tests/services_client.test
Create new services client event.
ServicesClientPluginsTestCase::createFakeEvent in tests/plugin.test
Create new event.
services_client_services_client_event_handler in ./services_client.plugins.inc
List availalable event handler plugins.

File

include/event.inc, line 844

View source
class EntitySaveHandler extends EventHandler {
  public function getDefaultConfiguration() {
    $config = parent::getDefaultConfiguration();
    $config['mapping'] = array();
    return $config;
  }
  public function configForm(&$form, &$form_state) {

    // Show conditions
    $mapping = array();
    foreach ($this->config['mapping'] as $uuid => $plugin) {
      try {
        $handler = $this
          ->getPluginInstance($plugin['type'], $plugin['config'], $uuid);
        $mapping[] = array(
          $handler
            ->getReaderSummary(),
          $handler
            ->getFormatterSummary(),
          implode(' | ', array(
            l(t('Edit'), $this
              ->getUrl('plugin/mapping/' . $uuid . '/edit')),
            l(t('Remove'), $this
              ->getUrl('plugin/mapping/' . $uuid . '/remove'), array(
              'query' => array(
                'token' => drupal_get_token($uuid),
              ),
            )),
          )),
        );
      } catch (Exception $e) {
        watchdog_exception('services_client', $e);
      }
    }
    $form['mapping']['title'] = array(
      '#markup' => '<h2>' . t('Mapping') . '</h2>',
    );
    $form['mapping']['table'] = array(
      '#theme' => 'table',
      '#header' => array(
        t('Source (local)'),
        t('Destination (remote)'),
        t('Actions'),
      ),
      '#rows' => $mapping,
      '#empty' => t('There are no mappings added'),
    );
    $form['mapping']['add_mapping'] = array(
      '#theme_wrappers' => array(
        'container',
      ),
      '#markup' => l('+ ' . t('Add mapping'), $this
        ->getUrl('add_plugin/mapping')),
    );
    parent::configForm($form, $form_state);
  }

  /**
   * Retrieve object that should be send to remote site.
   *
   * @return stdClass
   *   Mapped object.
   */
  protected function getMappedObject() {
    $entity = $this
      ->getEntity();
    $mapped = new stdClass();
    foreach ($this->config['mapping'] as $uuid => $plugin) {
      try {
        $handler = $this
          ->getPluginInstance($plugin['type'], $plugin['config'], $uuid);
        $source = $handler
          ->getReader()
          ->read($entity);
        if (!empty($source)) {
          $formatted = $handler
            ->getFormatter()
            ->format($source);
          if (!empty($formatted['key'])) {

            // Merge fields
            if (isset($mapped->{$formatted['key']}) && is_array($mapped->{$formatted['key']})) {
              $mapped->{$formatted['key']} = array_replace_recursive($mapped->{$formatted['key']}, $formatted['value']);
            }
            else {
              $mapped->{$formatted['key']} = $formatted['value'];
            }
          }
        }
      } catch (Exception $e) {
        watchdog_exception('services_client', $e);
      }
    }

    // Automatically map UUIDs
    if (isset($entity->uuid) && !isset($mapped->uuid)) {
      $mapped->uuid = $entity->uuid;
    }
    $this
      ->log(ServicesClientLogLevel::DEVEL, "MAPPED DATA; source : <pre>@source</pre>, mapped: <pre>@mapped</pre>", array(
      '@source' => $this
        ->debugObject($entity),
      '@mapped' => $this
        ->debugObject($mapped),
    ));
    return $mapped;
  }

  /**
   * Execute event and send event to remove endpoint.
   *
   * @return ServicesClientEventResult
   */
  public function execute() {

    // Load mapped object.
    $object = $this
      ->getMappedObject();

    // Set services client control data.
    $control = $this
      ->getControlData();
    $control
      ->setData($object);
    $this
      ->beforeSync($object);

    // Allow other modules to alter mapping.
    drupal_alter('services_client_mapped_object', $this, $object);

    // Create action result.
    $result = new ServicesClientEventResult();
    $result
      ->setHandler($this);
    $result->event = $this
      ->getEvent();
    $result->object = $object;
    $result->entity = $this
      ->getEntity();
    $result->entity_type = $result->event->entity_type;

    // Allow other modules to react on before request.
    module_invoke_all('services_client_before_request', $this, $object);
    if ($control
      ->isLooping()) {
      $this
        ->log(ServicesClientLogLevel::ERROR, "LOOP; entity_type: @type, entity_id: @id, event: @event", array(
        '@type' => $this->event->entity_type,
        '@id' => $this
          ->getEntityId(),
        '@event' => $this->event->name,
      ), WATCHDOG_ERROR);

      // Mark error as loop
      $result->error_type = ServicesClientErrorType::LOOP;
    }
    else {
      $this
        ->log(ServicesClientLogLevel::INFO, "SENDING; connection : @connection, event : @event, entity_type : @entity_type, entity_id : @entity_id, uuid : @uuid, object : <pre>@object</pre>", array(
        '@event' => $this->event->name,
        '@connection' => $this
          ->getConnectionId(),
        '@entity_type' => $this->event->entity_type,
        '@entity_id' => $this
          ->getEntityId(),
        '@uuid' => isset($this
          ->getEntity()->uuid) ? $this
          ->getEntity()->uuid : NULL,
        '@object' => $this
          ->debugObject($object),
      ));
      try {
        $result->response = $this
          ->doSync($object);
        $result->request = $this
          ->getConnection()
          ->getRequest();
      } catch (ServicesClientConnectionResponseException $e) {
        $e
          ->log();
        $result->error_message = $e
          ->getServicesMessage();
        $result->error_code = $e
          ->getErrorCode();
        $result->request = $e->request;
        $result->response = $e->response;

        // Determien what error type, by default we assume remote server failed.
        $error_type = ServicesClientErrorType::REMOTE_SERVER;

        // Logic errors that came from remote site, like can't login
        if ($e
          ->getErrorCode() >= 400 && $e
          ->getErrorCode() < 500) {
          $error_type = ServicesClientErrorType::REMOTE_LOGIC;
        }
        elseif ($e
          ->getErrorCode() < 100) {
          $error_type = ServicesClientErrorType::NETWORK;
        }

        // Set error type
        $result->error_type = $error_type;
      } catch (Exception $e) {
        $result->error_message = $e
          ->getMessage();
        $result->error_type = ServicesClientErrorType::UNKNOWN;
      }
    }
    $this
      ->logErrorResult($result);
    $this
      ->afterSync($object, $result);
    $this
      ->log(ServicesClientLogLevel::DEVEL, "RESULT; <pre>@result</pre>", array(
      '@result' => print_r($result, TRUE),
    ));

    // Allow other modules to react on after request.
    module_invoke_all('services_client_after_request', $this, $object, $result);
    return $result;
  }

  /**
   * Execute sync action.
   */
  protected function doSync($object) {
    $object = (array) $object;
    $id = $this
      ->getRemoteEntityId();
    if (empty($id)) {
      $this
        ->getConnection()
        ->create($this->config['resource'], $object);
      return $this
        ->getConnection()
        ->getResponse();
    }
    else {
      $this
        ->getConnection()
        ->update($this->config['resource'], $id, $object);
      return $this
        ->getConnection()
        ->getResponse();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
EntitySaveHandler::configForm public function Configuration form. Overrides EventHandler::configForm 2
EntitySaveHandler::doSync protected function Execute sync action. Overrides EventHandler::doSync
EntitySaveHandler::execute public function Execute event and send event to remove endpoint. Overrides EventHandler::execute
EntitySaveHandler::getDefaultConfiguration public function Retrieve default event configuration. Overrides EventHandler::getDefaultConfiguration 2
EntitySaveHandler::getMappedObject protected function Retrieve object that should be send to remote site.
EventHandler::$connection protected property Holds connection to remote server.
EventHandler::$entity protected property Processed drupal entity in event.
EventHandler::$plugin_instances protected property Initialized plugin classes.
EventHandler::$tags protected property Stores tags assigned to event.
EventHandler::addPlugin public function Add configuration plugin.
EventHandler::addTag public function Add event tag.
EventHandler::afterSync protected function Allow plugin to react on before sync event.
EventHandler::beforeSync protected function Allow plugin to react on before sync event. 2
EventHandler::breakEditLock public function Break any edit lock for current event.
EventHandler::clearObjectCache public function Clear current object cache.
EventHandler::configFormSubmit public function Submit handler; Store plugin configuration. Overrides ServicesClientPlugin::configFormSubmit 2
EventHandler::debugObject protected function Retrieve printed version of any variable. Should be used for logging.
EventHandler::enqueue public function Enqueue item if should be queue.
EventHandler::enqueueEntity protected function Put current entity to queue.
EventHandler::generateUuid protected function Generates a UUID v4 using PHP code.
EventHandler::getBaseUrl public function Retrieve UI base url for event.
EventHandler::getConnection protected function Retrieves event connection to remote site.
EventHandler::getConnectionId protected function Retrieve remote connection id.
EventHandler::getControlData protected function Retrieve controll data for current entity.
EventHandler::getEditLock public function Retrieve edit lock if exists (other user is editing same event).
EventHandler::getEntity public function Retrieve current event entity.
EventHandler::getEntityId public function Retrieve entity ID.
EventHandler::getEvent public function Retrieve event definition.
EventHandler::getObjectCache public function Retrieve object cached version of event.
EventHandler::getObjectCacheOrCache public function Retrieve current object from cache. If not currently in object cache adds object to object cache.
EventHandler::getPlugin public function Retrieve existing plugin.
EventHandler::getPluginInstance protected function Retrieve plugin instance by name and configuration.
EventHandler::getRemoteEntityId public function Retrieve remote entity ID. 1
EventHandler::getRemoteIdByUUID protected function Load remote ID by UUID based on remote UUID configuration.
EventHandler::getUrl public function Get path prefixed with event specific URL.
EventHandler::hasTag public function Check if event has specific tag.
EventHandler::isAutoTriggered public function Determine weather event should be fired automatically on drupal object action like node_save or node_delete.
EventHandler::isChanged public function Determine weather object has been changed by editing configuration and not which isn't stored in permanent storage.
EventHandler::isMatching public function Determine wheather entity is matching event conditions.
EventHandler::log protected function Log messages to Drupal watchdog.
EventHandler::logErrorResult protected function Log error result from services client operation.
EventHandler::objectCached public function Retrieve instance of object initialized with object cache.
EventHandler::removePlugin public function Remove existing plugin from configuration. This does is not saved to DB until save() method is called.
EventHandler::removeTag public function Remove tag from event.
EventHandler::save public function Save current event configuration to database.
EventHandler::setConnection public function Set new connection to remote site.
EventHandler::setEntity public function Set entity for current event.
EventHandler::setObjectCache public function Store current object state to object cache.
EventHandler::setPluginConfig public function Update plugin configuration. This does is not saved to DB until save() method is called.
EventHandler::skipAutosync public function Return TRUE if this entity shouldn't be send automatically to all connections.
EventHandler::__construct public function Constructor. Overrides ServicesClientPlugin::__construct
ServicesClientPlugin::$config protected property Plugin specific configuration
ServicesClientPlugin::$event protected property Event definition
ServicesClientPlugin::configFormValidate public function Validate configuration form. Overrides ServicesClientConfigurableInterface::configFormValidate 1
ServicesClientPlugin::getConfiguration public function Retrieve current plugin configuration. Overrides ServicesClientConfigurableInterface::getConfiguration
ServicesClientPlugin::setConfiguration public function Set configuration of plugin. Overrides ServicesClientConfigurableInterface::setConfiguration