本文整理汇总了PHP中DreamFactory\Library\Utility\ArrayUtils::getBool方法的典型用法代码示例。如果您正苦于以下问题:PHP ArrayUtils::getBool方法的具体用法?PHP ArrayUtils::getBool怎么用?PHP ArrayUtils::getBool使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DreamFactory\Library\Utility\ArrayUtils
的用法示例。
在下文中一共展示了ArrayUtils::getBool方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* Create a new SqlDbSvc
*
* @param array $settings
*
* @throws \InvalidArgumentException
* @throws \Exception
*/
public function __construct($settings = [])
{
parent::__construct($settings);
$config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
Session::replaceLookups($config, true);
$driver = isset($config['driver']) ? $config['driver'] : null;
$this->dbConn = ConnectionFactory::createConnection($driver, $config);
$this->dbConn->setCache($this);
$this->dbConn->setExtraStore($this);
$defaultSchemaOnly = ArrayUtils::getBool($config, 'default_schema_only');
$this->dbConn->setDefaultSchemaOnly($defaultSchemaOnly);
switch ($this->dbConn->getDBName()) {
case SqlDbDriverTypes::MYSQL:
case SqlDbDriverTypes::MYSQLI:
$this->dbConn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
break;
case SqlDbDriverTypes::DBLIB:
$this->dbConn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
break;
}
$attributes = ArrayUtils::clean(ArrayUtils::get($settings, 'attributes'));
if (!empty($attributes)) {
$this->dbConn->setAttributes($attributes);
}
}
示例2: getParameterAsBool
public function getParameterAsBool($key, $default = false)
{
if (!is_null($this->parameters)) {
return ArrayUtils::getBool($this->parameters, $key, $default);
}
return Scalar::boolval(Request::query($key, $default));
}
示例3: __construct
/**
* @param array $settings
*
* @throws ServiceUnavailableException
*/
public function __construct(array $settings = [])
{
parent::__construct($settings);
if (!extension_loaded('v8js')) {
throw new ServiceUnavailableException("This instance cannot run server-side javascript scripts. The 'v8js' is not available.");
}
$name = ArrayUtils::get($settings, 'name', self::EXPOSED_OBJECT_NAME, true);
$variables = ArrayUtils::get($settings, 'variables', [], true);
$extensions = ArrayUtils::get($settings, 'extensions', [], true);
// accept comma-delimited string
$extensions = is_string($extensions) ? array_map('trim', explode(',', trim($extensions, ','))) : $extensions;
$reportUncaughtExceptions = ArrayUtils::getBool($settings, 'report_uncaught_exceptions', false);
$logMemoryUsage = ArrayUtils::getBool($settings, 'log_memory_usage', false);
static::startup($settings);
// Set up our script mappings for module loading
/** @noinspection PhpUndefinedClassInspection */
$this->engine = new \V8Js($name, $variables, $extensions, $reportUncaughtExceptions);
/**
* This is the callback for the exposed "require()" function in the sandbox
*/
if (static::$moduleLoaderAvailable) {
/** @noinspection PhpUndefinedMethodInspection */
$this->engine->setModuleLoader(function ($module) {
return static::loadScriptingModule($module);
});
} else {
/** @noinspection PhpUndefinedClassInspection */
Log::debug(' * no "require()" support in V8 library v' . \V8Js::V8_VERSION);
}
if ($logMemoryUsage) {
/** @noinspection PhpUndefinedMethodInspection */
$loadedExtensions = $this->engine->getExtensions();
Log::debug(' * engine created with the following extensions: ' . (!empty($loadedExtensions) ? implode(', ', array_keys($loadedExtensions)) : '**NONE**'));
}
}
示例4: __construct
/**
* Create a new SqlDbSvc
*
* @param array $settings
*
* @throws \InvalidArgumentException
* @throws \Exception
*/
public function __construct($settings = [])
{
parent::__construct($settings);
$config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
$this->cacheEnabled = ArrayUtils::getBool($config, 'cache_enabled');
$this->cacheTTL = intval(ArrayUtils::get($config, 'cache_ttl', \Config::get('df.default_cache_ttl')));
$this->cachePrefix = 'service_' . $this->id . ':';
}
示例5: toArray
/**
* Convert the model instance to an array.
*
* @return array
*/
public function toArray()
{
$attributes = $this->attributesToArray();
if (ArrayUtils::getBool($attributes, 'private')) {
$attributes['value'] = self::PRIVATE_MASK;
}
return array_merge($attributes, $this->relationsToArray());
}
示例6: retrieveRecordsByFilter
/**
* {@inheritdoc}
*/
public function retrieveRecordsByFilter($table, $filter = null, $params = [], $extras = [])
{
$fields = ArrayUtils::get($extras, ApiOptions::FIELDS);
$ssFilters = ArrayUtils::get($extras, 'ss_filters');
$scanProperties = [static::TABLE_INDICATOR => $table];
$fields = static::buildAttributesToGet($fields);
if (!empty($fields)) {
$scanProperties['AttributesToGet'] = $fields;
}
$parsedFilter = static::buildCriteriaArray($filter, $params, $ssFilters);
if (!empty($parsedFilter)) {
$scanProperties['ScanFilter'] = $parsedFilter;
}
$limit = intval(ArrayUtils::get($extras, ApiOptions::LIMIT));
if ($limit > 0) {
$scanProperties['Limit'] = $limit;
$scanProperties['Count'] = true;
}
$offset = intval(ArrayUtils::get($extras, ApiOptions::OFFSET));
if ($offset > 0) {
$scanProperties['ExclusiveStartKey'] = $offset;
$scanProperties['Count'] = true;
}
try {
$result = $this->parent->getConnection()->scan($scanProperties);
$items = ArrayUtils::clean($result['Items']);
$out = [];
foreach ($items as $item) {
$out[] = $this->unformatAttributes($item);
}
$next = $this->unformatAttributes($result['LastEvaluatedKey']);
$next = current($next);
// todo handle more than one index here.
$count = $result['Count'];
$out = static::cleanRecords($out);
$needMore = $count - $offset > $limit;
$addCount = ArrayUtils::getBool($extras, ApiOptions::INCLUDE_COUNT);
if ($addCount || $needMore) {
$out['meta']['count'] = $count;
if ($needMore) {
$out['meta']['next'] = $next;
}
}
return $out;
} catch (\Exception $ex) {
throw new InternalServerErrorException("Failed to filter records from '{$table}'.\n{$ex->getMessage()}");
}
}
示例7: addToTransaction
/**
* {@inheritdoc}
*/
protected function addToTransaction($record = null, $id = null, $extras = null, $rollback = false, $continue = false, $single = false)
{
$fields = ArrayUtils::get($extras, ApiOptions::FIELDS);
$ssFilters = ArrayUtils::get($extras, 'ss_filters');
$updates = ArrayUtils::get($extras, 'updates');
$idFields = ArrayUtils::get($extras, 'id_fields');
$needToIterate = $single || $continue || 1 < count($this->tableIdsInfo);
$requireMore = ArrayUtils::getBool($extras, 'require_more');
$client = $this->parent->getGuzzleClient();
$out = [];
switch ($this->getAction()) {
case Verbs::POST:
$parsed = $this->parseRecord($record, $this->tableFieldsInfo, $ssFilters);
if (empty($parsed)) {
throw new BadRequestException('No valid fields were found in record.');
}
$native = json_encode($parsed);
$result = $this->parent->callGuzzle('POST', 'sobjects/' . $this->transactionTable . '/', null, $native, $client);
if (!ArrayUtils::getBool($result, 'success', false)) {
$msg = json_encode(ArrayUtils::get($result, 'errors'));
throw new InternalServerErrorException("Record insert failed for table '{$this->transactionTable}'.\n" . $msg);
}
$id = ArrayUtils::get($result, 'id');
// add via record, so batch processing can retrieve extras
return $requireMore ? parent::addToTransaction($id) : [$idFields => $id];
case Verbs::PUT:
case Verbs::MERGE:
case Verbs::PATCH:
if (!empty($updates)) {
$record = $updates;
}
$parsed = $this->parseRecord($record, $this->tableFieldsInfo, $ssFilters, true);
if (empty($parsed)) {
throw new BadRequestException('No valid fields were found in record.');
}
static::removeIds($parsed, $idFields);
$native = json_encode($parsed);
$result = $this->parent->callGuzzle('PATCH', 'sobjects/' . $this->transactionTable . '/' . $id, null, $native, $client);
if ($result && !ArrayUtils::getBool($result, 'success', false)) {
$msg = ArrayUtils::get($result, 'errors');
throw new InternalServerErrorException("Record update failed for table '{$this->transactionTable}'.\n" . $msg);
}
// add via record, so batch processing can retrieve extras
return $requireMore ? parent::addToTransaction($id) : [$idFields => $id];
case Verbs::DELETE:
$result = $this->parent->callGuzzle('DELETE', 'sobjects/' . $this->transactionTable . '/' . $id, null, null, $client);
if ($result && !ArrayUtils::getBool($result, 'success', false)) {
$msg = ArrayUtils::get($result, 'errors');
throw new InternalServerErrorException("Record delete failed for table '{$this->transactionTable}'.\n" . $msg);
}
// add via record, so batch processing can retrieve extras
return $requireMore ? parent::addToTransaction($id) : [$idFields => $id];
case Verbs::GET:
if (!$needToIterate) {
return parent::addToTransaction(null, $id);
}
$fields = $this->buildFieldList($this->transactionTable, $fields, $idFields);
$result = $this->parent->callGuzzle('GET', 'sobjects/' . $this->transactionTable . '/' . $id, ['fields' => $fields]);
if (empty($result)) {
throw new NotFoundException("Record with identifier '" . print_r($id, true) . "' not found.");
}
$out = $result;
break;
}
return $out;
}
示例8: mergeFromArray
/**
* @param array $data Merge some attributes from an array
*/
public function mergeFromArray(array $data)
{
$this->setStatusCode(ArrayUtils::get($data, 'status_code'));
if (ArrayUtils::getBool($data, 'payload_changed')) {
$this->setContentType(ArrayUtils::get($data, 'content_type'));
$this->setContent(ArrayUtils::get($data, 'content'));
}
}
示例9: retrieveRecordsByFilter
/**
* {@inheritdoc}
*/
public function retrieveRecordsByFilter($table, $filter = null, $params = [], $extras = [])
{
$coll = $this->selectTable($table);
$fields = ArrayUtils::get($extras, ApiOptions::FIELDS);
$ssFilters = ArrayUtils::get($extras, 'ss_filters');
$fieldArray = static::buildFieldArray($fields);
$criteria = static::buildCriteriaArray($filter, $params, $ssFilters);
$limit = intval(ArrayUtils::get($extras, ApiOptions::LIMIT, 0));
$offset = intval(ArrayUtils::get($extras, ApiOptions::OFFSET, 0));
$sort = static::buildSortArray(ArrayUtils::get($extras, ApiOptions::ORDER));
$addCount = ArrayUtils::getBool($extras, ApiOptions::INCLUDE_COUNT, false);
try {
/** @var \MongoCursor $result */
$result = $coll->find($criteria, $fieldArray);
$count = $result->count();
$maxAllowed = static::getMaxRecordsReturnedLimit();
if ($offset) {
$result = $result->skip($offset);
}
if ($sort) {
$result = $result->sort($sort);
}
if ($limit < 1 || $limit > $maxAllowed) {
$limit = $maxAllowed;
}
$result = $result->limit($limit);
$out = iterator_to_array($result);
$out = static::cleanRecords($out);
$needMore = $count - $offset > $limit;
if ($addCount || $needMore) {
$out['meta']['count'] = $count;
if ($needMore) {
$out['meta']['next'] = $offset + $limit;
}
}
return $out;
} catch (\Exception $ex) {
throw new InternalServerErrorException("Failed to filter records from '{$table}'.\n{$ex->getMessage()}");
}
}
示例10: mergeFromArray
/**
* @param array $data Merge some attributes from an array
*/
public function mergeFromArray(array $data)
{
$this->setMethod(ArrayUtils::get($data, 'method'));
$this->setParameters(ArrayUtils::get($data, 'parameters'));
$this->setHeaders(ArrayUtils::get($data, 'headers'));
$this->setPayloadData(ArrayUtils::get($data, 'payload'));
if (ArrayUtils::getBool($data, 'content_changed')) {
$this->setContent(ArrayUtils::get($data, 'content'), ArrayUtils::get($data, 'content_type'));
}
}
示例11: handleFolderContentFromData
/**
* @param array $data
* @param bool $extract
* @param bool $clean
* @param bool $checkExist
*
* @return array
*/
protected function handleFolderContentFromData($data, $extract = false, $clean = false, $checkExist = false)
{
$out = [];
if (!empty($data) && ArrayUtils::isArrayNumeric($data)) {
foreach ($data as $key => $resource) {
switch (ArrayUtils::get($resource, 'type')) {
case 'folder':
$name = ArrayUtils::get($resource, 'name', '');
$srcPath = ArrayUtils::get($resource, 'source_path');
if (!empty($srcPath)) {
$srcContainer = ArrayUtils::get($resource, 'source_container', $this->container);
// copy or move
if (empty($name)) {
$name = FileUtilities::getNameFromPath($srcPath);
}
$fullPathName = $this->folderPath . $name . '/';
$out[$key] = ['name' => $name, 'path' => $fullPathName, 'type' => 'folder'];
try {
$this->driver->copyFolder($this->container, $fullPathName, $srcContainer, $srcPath, true);
$deleteSource = ArrayUtils::getBool($resource, 'delete_source');
if ($deleteSource) {
$this->driver->deleteFolder($this->container, $srcPath, true);
}
} catch (\Exception $ex) {
$out[$key]['error'] = ['message' => $ex->getMessage()];
}
} else {
$fullPathName = $this->folderPath . $name . '/';
$content = ArrayUtils::get($resource, 'content', '');
$isBase64 = ArrayUtils::getBool($resource, 'is_base64');
if ($isBase64) {
$content = base64_decode($content);
}
$out[$key] = ['name' => $name, 'path' => $fullPathName, 'type' => 'folder'];
try {
$this->driver->createFolder($this->container, $fullPathName, $content);
} catch (\Exception $ex) {
$out[$key]['error'] = ['message' => $ex->getMessage()];
}
}
break;
case 'file':
$name = ArrayUtils::get($resource, 'name', '');
$srcPath = ArrayUtils::get($resource, 'source_path');
if (!empty($srcPath)) {
// copy or move
$srcContainer = ArrayUtils::get($resource, 'source_container', $this->container);
if (empty($name)) {
$name = FileUtilities::getNameFromPath($srcPath);
}
$fullPathName = $this->folderPath . $name;
$out[$key] = ['name' => $name, 'path' => $fullPathName, 'type' => 'file'];
try {
$this->driver->copyFile($this->container, $fullPathName, $srcContainer, $srcPath, true);
$deleteSource = ArrayUtils::getBool($resource, 'delete_source');
if ($deleteSource) {
$this->driver->deleteFile($this->container, $srcPath);
}
} catch (\Exception $ex) {
$out[$key]['error'] = ['message' => $ex->getMessage()];
}
} elseif (isset($resource['content'])) {
$fullPathName = $this->folderPath . $name;
$out[$key] = ['name' => $name, 'path' => $fullPathName, 'type' => 'file'];
$content = ArrayUtils::get($resource, 'content', '');
$isBase64 = ArrayUtils::getBool($resource, 'is_base64');
if ($isBase64) {
$content = base64_decode($content);
}
try {
$this->driver->writeFile($this->container, $fullPathName, $content);
} catch (\Exception $ex) {
$out[$key]['error'] = ['message' => $ex->getMessage()];
}
}
break;
}
}
}
return $out;
}
示例12: commitTransaction
/**
* {@inheritdoc}
*/
protected function commitTransaction($extras = null)
{
if (empty($this->batchRecords) && empty($this->batchIds)) {
if (isset($this->transaction)) {
$this->transaction->commit();
}
return null;
}
$updates = ArrayUtils::get($extras, 'updates');
$ssFilters = ArrayUtils::get($extras, 'ss_filters');
$fields = ArrayUtils::get($extras, ApiOptions::FIELDS);
$idFields = ArrayUtils::get($extras, 'id_fields');
$related = ArrayUtils::get($extras, 'related');
$requireMore = ArrayUtils::getBool($extras, 'require_more') || !empty($related);
$allowRelatedDelete = ArrayUtils::getBool($extras, 'allow_related_delete', false);
$relatedInfo = $this->describeTableRelated($this->transactionTable);
$where = [];
$params = [];
$idName = isset($this->tableIdsInfo, $this->tableIdsInfo[0], $this->tableIdsInfo[0]->name) ? $this->tableIdsInfo[0]->name : null;
if (empty($idName)) {
throw new BadRequestException('No valid identifier found for this table.');
}
if (!empty($this->batchRecords)) {
if (is_array($this->batchRecords[0])) {
$temp = [];
foreach ($this->batchRecords as $record) {
$temp[] = ArrayUtils::get($record, $idName);
}
$where[] = ['in', $idName, $temp];
} else {
$where[] = ['in', $idName, $this->batchRecords];
}
} else {
$where[] = ['in', $idName, $this->batchIds];
}
$serverFilter = $this->buildQueryStringFromData($ssFilters, $params);
if (!empty($serverFilter)) {
$where[] = $serverFilter;
}
if (count($where) > 1) {
array_unshift($where, 'AND');
} else {
$where = $where[0];
}
$out = [];
$action = $this->getAction();
if (!empty($this->batchRecords)) {
if (1 == count($this->tableIdsInfo)) {
// records are used to retrieve extras
// ids array are now more like records
$fields = empty($fields) ? $idFields : $fields;
$result = $this->parseFieldsForSqlSelect($fields, $this->tableFieldsInfo);
$bindings = ArrayUtils::get($result, 'bindings');
$fields = ArrayUtils::get($result, 'fields');
$fields = empty($fields) ? '*' : $fields;
$result = $this->recordQuery($this->transactionTable, $fields, $where, $params, $bindings, $extras);
if (empty($result)) {
throw new NotFoundException('No records were found using the given identifiers.');
}
$out = $result;
} else {
$out = $this->retrieveRecords($this->transactionTable, $this->batchRecords, $extras);
}
$this->batchRecords = [];
} elseif (!empty($this->batchIds)) {
/** @var Command $command */
$command = $this->dbConn->createCommand();
switch ($action) {
case Verbs::PUT:
case Verbs::MERGE:
case Verbs::PATCH:
if (!empty($updates)) {
$parsed = $this->parseRecord($updates, $this->tableFieldsInfo, $ssFilters, true);
if (!empty($parsed)) {
$rows = $command->update($this->transactionTable, $parsed, $where, $params);
if (0 >= $rows) {
throw new NotFoundException('No records were found using the given identifiers.');
}
if (count($this->batchIds) !== $rows) {
throw new BadRequestException('Batch Error: Not all requested records could be updated.');
}
}
foreach ($this->batchIds as $id) {
if (!empty($relatedInfo)) {
$this->updateRelations($this->transactionTable, $updates, $id, $relatedInfo, $allowRelatedDelete);
}
}
if ($requireMore) {
$fields = empty($fields) ? $idFields : $fields;
$result = $this->parseFieldsForSqlSelect($fields, $this->tableFieldsInfo);
$bindings = ArrayUtils::get($result, 'bindings');
$fields = ArrayUtils::get($result, 'fields');
$fields = empty($fields) ? '*' : $fields;
$result = $this->recordQuery($this->transactionTable, $fields, $where, $params, $bindings, $extras);
if (empty($result)) {
throw new NotFoundException('No records were found using the given identifiers.');
}
//.........这里部分代码省略.........
示例13: retrieveRecordsByIds
/**
* @param string $table
* @param mixed $ids - array or comma-delimited list of record identifiers
* @param array $extras
*
* @throws \Exception
* @return array
*/
public function retrieveRecordsByIds($table, $ids, $extras = [])
{
$ids = DbUtilities::validateAsArray($ids, ',', true, 'The request contains no valid identifiers.');
$fields = ArrayUtils::get($extras, ApiOptions::FIELDS);
$idFields = ArrayUtils::get($extras, ApiOptions::ID_FIELD);
$idTypes = ArrayUtils::get($extras, ApiOptions::ID_TYPE);
$isSingle = 1 == count($ids);
$continue = $isSingle ? false : ArrayUtils::getBool($extras, ApiOptions::CONTINUES, false);
$this->initTransaction($table, $idFields, $idTypes);
$extras['single'] = $isSingle;
$extras['id_fields'] = $idFields;
$extras['require_more'] = static::requireMoreFields($fields, $idFields);
$out = [];
$errors = [];
try {
foreach ($ids as $index => $id) {
try {
if (false === ($id = static::checkForIds($id, $this->tableIdsInfo, $extras, true))) {
throw new BadRequestException("Required id field(s) not valid in request {$index}: " . print_r($id, true));
}
$result = $this->addToTransaction(null, $id, $extras, false, $continue, $isSingle);
if (isset($result)) {
// operation performed, take output
$out[$index] = $result;
}
} catch (\Exception $ex) {
if ($isSingle || !$continue) {
if (0 !== $index) {
// first error, don't worry about batch just throw it
// mark last error and index for batch results
$errors[] = $index;
$out[$index] = $ex->getMessage();
}
throw $ex;
}
// mark error and index for batch results
$errors[] = $index;
$out[$index] = $ex->getMessage();
}
}
if (!empty($errors)) {
throw new BadRequestException();
}
$result = $this->commitTransaction($extras);
if (isset($result)) {
$out = $result;
}
return $out;
} catch (\Exception $ex) {
$msg = $ex->getMessage();
$context = null;
if (!empty($errors)) {
$wrapper = ResourcesWrapper::getWrapper();
$context = ['error' => $errors, $wrapper => $out];
$msg = 'Batch Error: Not all records could be retrieved.';
}
if ($ex instanceof RestException) {
$temp = $ex->getContext();
$context = empty($temp) ? $context : $temp;
$ex->setContext($context);
$ex->setMessage($msg);
throw $ex;
}
throw new InternalServerErrorException("Failed to retrieve records from '{$table}'.\n{$msg}", null, null, $context);
}
}
示例14: commitTransaction
/**
* {@inheritdoc}
*/
protected function commitTransaction($extras = null)
{
if (empty($this->batchRecords) && empty($this->batchIds)) {
return null;
}
$fields = ArrayUtils::get($extras, ApiOptions::FIELDS);
$requireMore = ArrayUtils::getBool($extras, 'require_more');
$out = [];
switch ($this->getAction()) {
case Verbs::POST:
$result = $this->parent->getConnection()->asArray()->storeDocs($this->batchRecords, true);
if ($requireMore) {
$result = static::recordArrayMerge($this->batchRecords, $result);
}
$out = static::cleanRecords($result, $fields);
break;
case Verbs::PUT:
$result = $this->parent->getConnection()->asArray()->storeDocs($this->batchRecords, true);
if ($requireMore) {
$result = static::recordArrayMerge($this->batchRecords, $result);
}
$out = static::cleanRecords($result, $fields);
break;
case Verbs::MERGE:
case Verbs::PATCH:
$result = $this->parent->getConnection()->asArray()->storeDocs($this->batchRecords, true);
if ($requireMore) {
$result = static::recordArrayMerge($this->batchRecords, $result);
}
$out = static::cleanRecords($result, $fields);
break;
case Verbs::DELETE:
$out = [];
if ($requireMore) {
$result = $this->parent->getConnection()->setQueryParameters($extras)->asArray()->include_docs(true)->keys($this->batchIds)->getAllDocs();
$rows = ArrayUtils::get($result, 'rows');
$out = static::cleanRecords($rows, $fields, static::DEFAULT_ID_FIELD, true);
}
$result = $this->parent->getConnection()->asArray()->deleteDocs($this->batchRecords, true);
if (empty($out)) {
$out = static::cleanRecords($result, $fields);
}
break;
case Verbs::GET:
$result = $this->parent->getConnection()->setQueryParameters($extras)->asArray()->include_docs($requireMore)->keys($this->batchIds)->getAllDocs();
$rows = ArrayUtils::get($result, 'rows');
$out = static::cleanRecords($rows, $fields, static::DEFAULT_ID_FIELD, true);
if (count($this->batchIds) !== count($out)) {
throw new BadRequestException('Batch Error: Not all requested ids were found to retrieve.');
}
break;
default:
break;
}
$this->batchIds = [];
$this->batchRecords = [];
return $out;
}
示例15: bulkDelete
/**
* @param $records
* @param array $params
* @param bool $singlePayload
*
* @return array|mixed
* @throws BadRequestException
* @throws \Exception
*/
public static function bulkDelete($records, $params = [], $singlePayload = false)
{
if (empty($records)) {
throw new BadRequestException('There is no record in the request.');
}
$response = [];
$transaction = null;
$errors = [];
$singleRow = 1 === count($records) ? true : false;
$rollback = ArrayUtils::getBool($params, ApiOptions::ROLLBACK);
$continue = ArrayUtils::getBool($params, ApiOptions::CONTINUES);
try {
// Start a transaction
if (!$singleRow && $rollback) {
DB::beginTransaction();
$transaction = true;
}
foreach ($records as $key => $record) {
try {
$m = new static();
$pk = $m->getPrimaryKey();
$id = ArrayUtils::get($record, $pk);
$response[$key] = static::deleteInternal($id, $record, $params);
} catch (\Exception $ex) {
if ($singleRow) {
throw $ex;
}
if ($rollback && $transaction) {
DB::rollBack();
throw $ex;
}
// track the index of the error and copy error to results
$errors[] = $key;
$response[$key] = $ex->getMessage();
if (!$continue) {
break;
}
}
}
} catch (\Exception $ex) {
throw $ex;
}
if (!empty($errors)) {
$msg = ['errors' => $errors, ResourcesWrapper::getWrapper() => $response];
throw new BadRequestException("Batch Error: Not all parts of the request were successful.", null, null, $msg);
}
// Commit
if ($transaction) {
try {
DB::commit();
} catch (\Exception $ex) {
throw $ex;
}
}
return $singlePayload ? current($response) : $response;
}