You are here

public function StringMongoDBStorage::save in MongoDB 8

Save string object to storage.

Parameters

\Drupal\locale\StringInterface $string: The string object.

Return value

\Drupal\locale\StringStorageInterface The called object.

Throws

\Drupal\locale\StringStorageException In case of failures, an exception is thrown.

Overrides StringStorageInterface::save

File

mongodb_locale/src/StringStorage.php, line 236

Class

StringMongoDBStorage

Namespace

Drupal\mongodb_locale

Code

public function save($string) {
  $collection = $this->mongo
    ->get('locale');
  if ($string
    ->isSource()) {
    $string
      ->setValues(array(
      'context' => '',
      'version' => 'none',
    ), FALSE);
    $values = $string
      ->getValues(array(
      'source',
      'context',
      'version',
    ));
    $criteria = array();
    if ($id = $string
      ->getId()) {
      $criteria = $this
        ->getIdCriteria($id);
      $values += $criteria;
    }
    $collection
      ->update($criteria, $values, array(
      'upsert' => TRUE,
    ));
  }
  elseif ($string
    ->isTranslation()) {
    $string
      ->setValues(array(
      'customized' => FALSE,
    ), FALSE);
    $values = $string
      ->getValues(array(
      'language',
      'translation',
      'customized',
    ));
    $values['customized'] = (bool) $values['customized'];
    $collection = $this->mongo
      ->get('locale');
    $criteria = $this
      ->getIdCriteria($string
      ->getId());

    // Try updating an existing translation.
    $criteria['translations.language'] = $values['language'];
    $result = $collection
      ->update($criteria, array(
      '$set' => array(
        'translations.$' => $values,
      ),
    ));

    // If it didn't exist, try to add it.
    if (!$result['updatedExisting']) {

      // Do not add this translation again if it got added since the
      // previous query (in a race condition).
      $criteria['translations.language'] = array(
        '$ne' => $values['language'],
      );
      $collection
        ->update($criteria, array(
        '$push' => array(
          'translations' => $values,
        ),
      ));
    }
  }
  else {
    throw new StringStorageException(format_string('The string cannot be saved: @string', array(
      '@string' => $string
        ->getString(),
    )));
  }
  return $this;
}