Send a set of mutations to the API for processing

@param array|Patch|Transaction $mutations Either an array of mutations, a patch or a transaction
@param array $options Optional array of options for the request
@return array Mutation result
429158
public function mutate($mutations, $options = null)
    {
        $mut = $mutations;
        if ($mut instanceof Patch) {
            $mut = ['patch' => $mut->serialize()];
        } elseif ($mut instanceof Transaction) {
            $mut = $mut->serialize();
        }

        $body = ['mutations' => !isset($mut[0]) ? [$mut] : $mut];
        $queryParams = $this->getMutationQueryParams($options);
        $requestOptions = [
            'method' => 'POST',
            'query' => $queryParams,
            'headers' => ['Content-Type: application/json'],
            'body' => json_encode($body),
            'url' => '/data/mutate/' . $this->clientConfig['dataset'],
        ];

        // Try to perform request
        $body = $this->request($requestOptions);

        // Should we return the documents?
        $returnDocuments = isset($options['returnDocuments']) && $options['returnDocuments'];
        $returnFirst = isset($options['returnFirst']) && $options['returnFirst'];
        $results = isset($body['results']) ? $body['results'] : [];

        if ($returnDocuments && $returnFirst) {
            return isset($results[0]) ? $results[0]['document'] : null;
        } elseif ($returnDocuments) {
            return array_column($results, 'document', 'id');
        }

        // Return a reduced subset
        if ($returnFirst) {
            $ids = isset($results[0]) ? $results[0]['id'] : null;
        } else {
            $ids = array_column($results, 'id');
        }

        $key = $returnFirst ? 'documentId' : 'documentIds';
        return [
          'transactionId' => $body['transactionId'],
          'results' => $results,
          $key => $ids,
        ];
    }
332879
protected function doTransact(Transaction $transaction, array $options = array())
    {
        $this->validateTransaction($transaction);

        $account = $transaction->getAccount();
        $result = $transaction->getResult();
        $result->setTransactor($this);

        $adjustment = $transaction->getAmount();
        if (Transaction\TransactionType::SALE === $transaction->getType()->getValue()) {
            if ($transaction->getAmount() > $account->getBalance()) {
                $result->setStatus(new Result\ResultStatus(Result\ResultStatus::DECLINED));
                $result->setMessage('Amount exceeds account balance');

                return $result;
            }

            $adjustment *= -1; // Negate the adjustment
        }

        $result->setStatus(new Result\ResultStatus(Result\ResultStatus::APPROVED));
        $account->adjustBalance($adjustment);

        return $result;
    }
1269191
public function otherTrans(array $transaction = null)
    {
        // morph Transaction extension - will read the type of transaction
        // and instantiate the correct class extending Transaction.
        $morphed = Transaction::create($transaction ?: $this->getAttribute("otherTrans"));

        if ($morphed->type === TransactionType::MULTISIG) {
            // cannot nest multisig in another multisig.
            throw new InvalidArgumentException("It is forbidden to nest a Multisig transaction in another Multisig transaction.");
        }
        elseif ($morphed->type === TransactionType::MULTISIG_SIGNATURE) {
            // cannot nest multisig in another multisig.
            throw new InvalidArgumentException("It is forbidden to nest a Signature transaction in the inner transaction of a Multisig transaction.");
        }

        return $morphed;
    }
714664
protected function runAction($action, array $options = array())
    {
        switch ($action) {
            case 'merge':
                return $this->runMergeAction($options);

            case 'tag':
                return $this->runTagAction($options);

            case 'pull':
                return $this->runPullAction($options);

            case 'push':
                return $this->runPushAction($options);
        }


        return false;
    }
1315417
public function setOptions($options = []) {

		if(false === is_array($options)) {
            return trigger_error(sprintf('Argument 1 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($options)), E_USER_ERROR);
        }

		$this -> options = array_merge($this -> options, $options);
	}
1002996
public function mutateManyToOrigin($attributes)
    {
        $mutations = [];

        foreach ($this->getMutations() as $label => $info)
        {
            $mutationModel = $this->getMutationModel($label);
            $model = $mutationModel->newFromBuilder($attributes[$label]);
            $model->setConnection($mutationModel->getConnectionName());
            $mutations[$label] = $model;
        }

        return $mutations;
    }
959426
private function executeExtraUpdates(array $options)
    {
        foreach ($this->extraUpdates as $oid => $update) {
            list ($document, $changeset) = $update;
            $this->documentChangeSets[$oid] = $changeset;
            $this->getDocumentPersister(get_class($document))->update($document, $options);
        }
    }
337450
protected function buildParams(Transaction $transaction, array $options = array())
    {
        $credentials = $transaction->getCredentials();
        $account = $transaction->getAccount();

        $params = $params = array(
            'ProviderID' => $credentials->getCredential('providerId'),
            'Provider_GateID' => $credentials->getCredential('providerGateId'),
            'Provider_GateKey' => $credentials->getCredential('providerGateKey'),
            'Command' => $this->getCommand($transaction),
            'CommandVersion' => '1.0',
            'TestMode' => !empty($options['test_mode']) ? 'On' : 'Off',
            'MerchantID' => $credentials->getCredential('merchantId'),
            'Merchant_GateID' => $credentials->getCredential('merchantGateId'),
            'Merchant_GateKey' => $credentials->getCredential('merchantGateKey'),
        );

        $transactionType = $transaction->getType()->getValue();

        if (Transaction\TransactionType::SALE === $transactionType) {
            $params = array_merge($params, array(
                'ResponseType' => 'JSON',
                'PaymentDirection' => 'FromCustomer',
                'Amount' => $transaction->getAmount(),
                'CheckType' => in_array($account->getAccountType()->getValue(), array(
                    AccountType::PERSONAL_SAVINGS,
                    AccountType::PERSONAL_CHECKING
                )) ? 'Personal' : 'Business',
                'AccountType' => in_array($account->getAccountType()->getValue(), array(
                    AccountType::PERSONAL_SAVINGS,
                    AccountType::BUSINESS_SAVINGS
                )) ? 'Savings' : 'Checking',
                'RoutingNumber' => $account->getRoutingNumber(),
                'AccountNumber' => $account->getAccountNumber(),
                'Billing_CustomerName' => $account->getName(),
                'Billing_Address1' => $account->getAddress(),
                'Billing_City' => $account->getCity(),
                'Billing_State' => $account->getRegion(),
                'Billing_Zip' => $account->getPostalCode(),
                'Billing_Phone' => $account->getPhoneNumber(),
                'SendEmailToCustomer' => 'No',
                'Run_ExpressVerify' => 'No',
                'SECCode' => 'WEB',
                'Customer_IPAddress' => $account->getIpAddress(),
            ));
        } elseif (Transaction\TransactionType::QUERY === $transactionType) {
            $params['TrackingDate'] = !empty($options['date']) ? $options['date'] : date('mdY');
        } else {
            throw new \RuntimeException(sprintf('The transaction type %s is not yet implemented', $transaction->getType()->getValue()));
        }

        return $params;
    }
138170
public function update(array $options = array())
    {
        $module = $this->utils()->whichModule($this);
        return $this->utils()->update($module, $options);
    }
204838
public function update($query, array $options = []) {
		$params = compact('query', 'options');

		return Filters::run($this, __FUNCTION__, $params, function($params) {
			$query = $params['query'];
			$options = $params['options'];
			$params = $query->export($this);

			list($_path, $conditions) = (array) $params['conditions'];
			$data = $query->data();

			foreach (['id', 'rev'] as $key) {
				$data["_{$key}"] = isset($data[$key]) ? (string) $data[$key] : null;
				unset($data[$key]);
			}
			$data = (array) $conditions + array_filter((array) $data);

			$retry = false;
			do {
				$result = $this->connection->put(
					"{$this->_config['database']}/{$_path}",
					$data,
					['type' => 'json']
				);
				$result = is_string($result) ? json_decode($result, true) : $result;
				$retry = $retry ? !$retry : $this->_autoBuild($result);
			} while ($retry);

			if (isset($result['_id']) || (isset($result['ok']) && $result['ok'] === true)) {
				$result = $this->_format($result, $options);
				$query->entity()->sync($result['id'], ['rev' => $result['rev']]);
				return true;
			}
			if (isset($result['error'])) {
				$query->entity()->errors([$result['error']]);
			}
			return false;
		});
	}
241484
public function patch($url, $params = array(), $options = array())
    {
        return $this->request($url, self::PATCH, $params, $options);
    }
430533
public function transact(Transaction $transaction, array $options = array())
    {
        if ($transaction->isTransacted()) {
            throw TransactorException::transactionAlreadyProcessed();
        } elseif (!$this->supportsType($transaction->getType())) {
            throw TransactorException::unsupportedTransactionType($transaction->getType());
        } elseif (!$this->supportsNetwork($transaction->getNetwork())) {
            throw TransactorException::unsupportedTransactionNetwork($transaction->getNetwork());
        }

        $result = $transaction->getResult();
        $result->setTransactor($this);

        try {
            $options = $this->getResolver()->resolve($options);

            $this->doTransact($transaction, $options);
        } catch (\Exception $e) {
            $result->setStatus(new ResultStatus(ResultStatus::ERROR));
            $result->setMessage('An internal error occurred while processing the transaction.');
            $result->setData('message', $e->getMessage());
            $result->setData('trace', $e->getTraceAsString());
        }

        return $this->filterResult($result);
    }
1214128
public function patch($path = null, $data = [], array $options = []) {
		return $this->send(__FUNCTION__, $path, $data, $options);
	}
15603
private ApiFuture<?> offer(Mutation mutation) {
    ApiFuture<?> future = null;
    try {
      if (mutation == null) {
        future = ApiFutures.immediateFailedFuture(
          new IllegalArgumentException("Cannot perform a mutation on a null object."));
      } else if (mutation instanceof Put) {
        future = bulkMutation.add(adapter.adaptEntry((Put) mutation));
      } else if (mutation instanceof Delete) {
        future = bulkMutation.add(adapter.adaptEntry((Delete) mutation));
      } else if (mutation instanceof Increment) {
        future = dataClient.readModifyWriteRowAsync(adapter.adapt((Increment) mutation));
        operationAccountant.registerOperation(ApiFutureUtil.adapt(future));
      } else if (mutation instanceof Append) {
        future = dataClient.readModifyWriteRowAsync(adapter.adapt((Append) mutation));
        operationAccountant.registerOperation(ApiFutureUtil.adapt(future));
      } else {
        future = ApiFutures.immediateFailedFuture(new IllegalArgumentException(
            "Encountered unknown mutation type: " + mutation.getClass()));
      }
    } catch (Exception e) {
      // issueRequest(mutation) could throw an Exception for validation issues. Remove the heapsize
      // and inflight rpc count.
      future = ApiFutures.immediateFailedFuture(e);
    }
    return future;
  }
679549
public function beginTransaction($transactionOptions, array $options = [])
    {
        $res = $this->connection->beginTransaction([
            'projectId' => $this->projectId,
            'transactionOptions' => $transactionOptions
        ] + $options);

        return $res['transaction'];
    }
143796
public function update(array $attributes = [], array $options = [])
    {
        if (! $this->exists) {
            return false;
        }

        return $this->fill($attributes)->save($options);
    }
644732
public function getChangeLogQuery(array $options)
    {
        $qb = $this->createQueryBuilder();
        $qb->select('*');

        $this->setLimitOrder($qb, $options);

        return $qb;
    }