sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public static function updateById($id, array $record, array $params = [])
{
$m = new static;
$pk = $m->getPrimaryKey();
$record[$pk] = $id;
try {
$response = static::bulkUpdate([$record], $params);
return current($response);
} catch (BatchException $ex) {
$response = $ex->pickResponse(0);
if ($response instanceof \Exception) {
throw $response;
}
return $response;
} catch (\Exception $ex) {
throw new InternalServerErrorException($ex->getMessage());
}
} | @param $id
@param $record
@param array $params
@return array|mixed
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
public static function updateByIds($ids, array $record, array $params = [])
{
if (!is_array($ids)) {
$ids = explode(",", $ids);
}
$records = [];
$m = new static;
$pk = $m->getPrimaryKey();
foreach ($ids as $id) {
$record[$pk] = $id;
$records[] = $record;
}
return static::bulkUpdate($records, $params);
} | @param $ids
@param $record
@param array $params
@return array|mixed
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
public static function updateInternal($id, $record, $params = [])
{
if (empty($record)) {
throw new BadRequestException('There are no fields in the record to create . ');
}
if (empty($id)) {
//Todo:perform logging below
//Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
}
$model = static::find($id);
if (!$model instanceof Model) {
throw new NotFoundException("Record with identifier '$id' not found.");
}
$pk = $model->primaryKey;
// Remove the PK from the record since this is an update
unset($record[$pk]);
try {
$model->update($record);
return static::buildResult($model, $params);
} catch (\Exception $ex) {
throw new InternalServerErrorException('Failed to update resource: ' . $ex->getMessage());
}
} | @param $id
@param $record
@param array $params
@return array
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException
@throws \DreamFactory\Core\Exceptions\NotFoundException | entailment |
public static function deleteById($id, array $params = [])
{
$m = new static;
$pk = $m->getPrimaryKey();
try {
$response = static::bulkDelete([[$pk => $id]], $params);
return current($response);
} catch (BatchException $ex) {
$response = $ex->pickResponse(0);
if ($response instanceof \Exception) {
throw $response;
}
return $response;
} catch (\Exception $ex) {
throw new InternalServerErrorException($ex->getMessage());
}
} | @param $id
@param array $params
@return array|mixed
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
public static function deleteByIds($ids, array $params = [])
{
if (!is_array($ids)) {
$ids = explode(",", $ids);
}
$m = new static;
$pk = $m->getPrimaryKey();
$records = [];
foreach ($ids as $id) {
$records[] = [$pk => $id];
}
return static::bulkDelete($records, $params);
} | @param $ids
@param array $params
@return array|mixed
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
public static function bulkDelete(array $records, array $params = [])
{
if (empty($records)) {
throw new BadRequestException('There is no record in the request.');
}
$response = [];
$errors = false;
$rollback = array_get_bool($params, ApiOptions::ROLLBACK);
$continue = array_get_bool($params, ApiOptions::CONTINUES);
if ($rollback) {
// Start a transaction
DB::beginTransaction();
}
foreach ($records as $key => $record) {
try {
$m = new static;
$pk = $m->getPrimaryKey();
$id = array_get($record, $pk);
$response[$key] = static::deleteInternal($id, $record, $params);
} catch (\Exception $ex) {
// track the index of the error and copy error to results
$errors = true;
$response[$key] = $ex;
if ($rollback || !$continue) {
break;
}
}
}
if ($errors) {
$msg = "Batch Error: Not all requested records could be deleted.";
if ($rollback) {
DB::rollBack();
$msg .= " All changes rolled back.";
}
throw new BatchException($response, $msg);
}
if ($rollback) {
DB::commit();
}
return $response;
} | @param $records
@param array $params
@return array|mixed
@throws BadRequestException
@throws \Exception | entailment |
public static function deleteInternal($id, $record, $params = [])
{
if (empty($record)) {
throw new BadRequestException('There are no fields in the record to create . ');
}
if (empty($id)) {
//Todo:perform logging below
//Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
}
$model = static::find($id);
if (!$model instanceof Model) {
throw new NotFoundException("Record with identifier '$id' not found.");
}
try {
$result = static::buildResult($model, $params);
$model->delete();
return $result;
} catch (\Exception $ex) {
throw new InternalServerErrorException('Failed to delete resource: ' . $ex->getMessage());
}
} | @param $id
@param $record
@param array $params
@return array
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException
@throws \DreamFactory\Core\Exceptions\NotFoundException | entailment |
public static function buildResult($model, $params = [])
{
$pk = $model->primaryKey;
$id = $model->{$pk};
$fields = array_get($params, ApiOptions::FIELDS, $pk);
$related = array_get($params, ApiOptions::RELATED);
if ($pk === $fields && empty($related)) {
return [$pk => $id];
}
$fieldsArray = explode(',', $fields);
$result = static::selectById($id, $params, $fieldsArray);
return $result;
} | @param BaseModel $model
@param array $params
@return array | entailment |
public function getTableSchema()
{
return \Cache::rememberForever('model:' . $this->table, function () {
$resourceName = $this->table;
$name = $resourceName;
if (empty($schemaName = $this->getDefaultSchema())) {
$internalName = $resourceName;
$quotedName = $this->getSchema()->quoteTableName($resourceName);;
} else {
$internalName = $schemaName . '.' . $resourceName;
$quotedName = $this->getSchema()->quoteTableName($schemaName) . '.' . $this->getSchema()->quoteTableName($resourceName);;
}
$settings = compact('schemaName', 'resourceName', 'name', 'internalName', 'quotedName');
$tableSchema = new TableSchema($settings);
$tableSchema = $this->getSchema()->getResource(DbResourceTypes::TYPE_TABLE, $tableSchema);
// merge db relationships
if (!empty($references = $this->getTableConstraints())) {
$this->updateTableWithConstraints($tableSchema, $references);
}
$tableSchema->discoveryCompleted = true;
return $tableSchema;
});
} | Gets the TableSchema for this model.
@return TableSchema | entailment |
public static function selectByIds($ids, array $options = [], array $criteria = [])
{
$criteria = static::cleanCriteria($criteria);
if (empty($criteria)) {
$criteria['select'] = ['*'];
}
if (is_array($ids)) {
$ids = implode(',', $ids);
}
$pk = static::getPrimaryKeyStatic();
if (!empty($ids)) {
$idsPhrase = " $pk IN ($ids) ";
$condition = array_get($criteria, 'condition');
if (!empty($condition)) {
$condition .= ' AND ' . $idsPhrase;
} else {
$condition = $idsPhrase;
}
$criteria['condition'] = $condition;
}
$data = static::selectByRequest($criteria, $options);
$data = static::cleanResult($data, array_get($criteria, 'select'));
if (!is_array($ids)) {
$ids = explode(',', $ids);
}
if (count($data) != count($ids)) {
$out = [];
$continue = array_get_bool($options, ApiOptions::CONTINUES);
foreach ($ids as $index => $id) {
$found = false;
foreach ($data as $record) {
if ($id == array_get($record, $pk)) {
$out[$index] = $record;
$found = true;
break;
}
}
if (!$found) {
$out[$index] = new NotFoundException("Record with identifier '$id' not found.");
if (!$continue) {
break;
}
}
}
throw new BatchException($out, 'Batch Error: Not all requested records could be retrieved.');
}
return $data;
} | Selects records by multiple ids.
@param string|array $ids
@param array $options
@param array $criteria
@return mixed
@throws BatchException | entailment |
public static function selectByRequest(array $criteria = [], array $options = [])
{
$criteria = static::cleanCriteria($criteria);
$pk = static::getPrimaryKeyStatic();
$selection = array_get($criteria, 'select');
if (empty($selection)) {
$selection = ['*'];
}
$related = array_get($options, ApiOptions::RELATED, []);
if (is_string($related)) {
$related = explode(',', $related);
}
$condition = array_get($criteria, 'condition');
if (!empty($condition)) {
$params = array_get($criteria, 'params');
$builder = static::whereRaw($condition, $params)->with($related);
} else {
$builder = static::with($related);
}
if (!empty($limit = array_get($criteria, 'limit'))) {
$builder->take($limit);
}
if (!empty($offset = array_get($criteria, 'offset'))) {
$builder->skip($offset);
}
$orderBy = array_get($criteria, 'order', "$pk asc");
$orders = explode(',', $orderBy);
foreach ($orders as $order) {
$order = trim($order);
@list($column, $direction) = explode(' ', $order);
if (empty($direction)) {
$direction = 'ASC';
}
$builder = $builder->orderBy($column, $direction);
}
$groupBy = array_get($criteria, 'group');
if (!empty($groupBy)) {
$groups = explode(',', $groupBy);
foreach ($groups as $group) {
$builder = $builder->groupBy(trim($group));
}
}
$response = $builder->get($selection);
return static::cleanResult($response, array_get($criteria, 'select'));
} | Performs a SELECT query based on
query criteria supplied from api request.
@param array $criteria
@param array $options
@return array | entailment |
public static function countByRequest(array $criteria = [])
{
if (!empty($condition = array_get($criteria, 'condition'))) {
$params = array_get($criteria, 'params', []);
return static::whereRaw($condition, $params)->count();
}
return static::count();
} | Performs a COUNT query based on query criteria supplied from api request.
@param array $criteria
@return int | entailment |
protected function saveHasOneData($relatedModel, HasOne $hasOne, $data, $relationName)
{
if ($this->exists) {
$pk = $hasOne->getRelated()->primaryKey;
$fk = $hasOne->getForeignKeyName();
if (empty($data)) {
// delete a related if it exists
$hasOne->delete();
} else {
/** @var Model $model */
if (empty($pkValue = array_get($data, $pk))) {
$model = $relatedModel::findCompositeForeignKeyModel($this->{$this->primaryKey}, $data);
} else {
$model = $relatedModel::find($pkValue);
}
if (!empty($model)) {
/** @var Model $parent */
$fkId = array_get($data, $fk);
if (array_key_exists($fk, $data) && is_null($fkId)) {
//Foreign key field is set to null therefore delete the child record.
$model->delete();
} elseif (!empty($fkId) &&
$fkId !== $this->{$this->primaryKey} &&
(null !== $parent = static::find($fkId))
) {
//Foreign key field is set but the id belongs to a different parent than this parent.
//There the child is adopted by the supplied parent id (foreign key).
$relatedData = [$relationName => $data];
$parent->update($relatedData);
} else {
$model->fill($data);
$hasOne->save($model);
}
} else {
// not found, create a new one
$model = new $relatedModel($data);
$hasOne->save($model);
}
}
}
} | Saves the HasMany relational data. If id exists
then it updates the record otherwise it will
create the record.
@param BaseModel $relatedModel Model class
@param HasOne $hasOne
@param $data
@param $relationName
@throws \Exception | entailment |
protected function saveHasManyData($relatedModel, HasMany $hasMany, $data, $relationName)
{
if ($this->exists) {
$models = [];
$pk = $hasMany->getRelated()->primaryKey;
$fk = $hasMany->getForeignKeyName();
foreach ((array)$data as $d) {
/** @var Model $model */
if (empty($pkValue = array_get($d, $pk))) {
$model = $relatedModel::findCompositeForeignKeyModel($this->{$this->primaryKey}, $d);
} else {
$model = $relatedModel::find($pkValue);
}
if (!empty($model)) {
/** @var Model $parent */
$fkId = array_get($d, $fk);
if (array_key_exists($fk, $d) && is_null($fkId)) {
//Foreign key field is set to null therefore delete the child record.
$model->delete();
continue;
} elseif (!empty($fkId) &&
$fkId !== $this->{$this->primaryKey} &&
(null !== $parent = static::find($fkId))
) {
//Foreign key field is set but the id belongs to a different parent than this parent.
//There the child is adopted by the supplied parent id (foreign key).
$relatedData = [$relationName => [$d]];
$parent->update($relatedData);
continue;
} else {
$model->fill($d);
}
} else {
// not found, create a new one
$model = new $relatedModel($d);
}
$models[] = $model;
}
$hasMany->saveMany($models);
}
} | Saves the HasMany relational data. If id exists
then it updates the record otherwise it will
create the record.
@param BaseModel $relatedModel Model class
@param HasMany $hasMany
@param $data
@param $relationName
@throws \Exception | entailment |
public function getHasOneByRelationName($name)
{
if ($table = $this->getReferencingTable($name)) {
if ($model = static::getModelFromTable($table)) {
$refField = $this->getReferencingField($table, $name);
return $this->hasOne($model, $refField);
}
}
return null;
} | @param $name
@return HasOne|null | entailment |
public function getHasManyByRelationName($name)
{
if ($table = $this->getReferencingTable($name)) {
if ($model = static::getModelFromTable($table)) {
$refField = $this->getReferencingField($table, $name);
return $this->hasMany($model, $refField);
}
}
return null;
} | @param $name
@return HasMany|null | entailment |
protected function getReferencingField($table, $name)
{
$references = $this->getReferences();
$rf = null;
foreach ($references as $item) {
if ($item->refTable === $table && $table . '_by_' . implode('_', $item->refField) === $name) {
$rf = $item->refField[0];
break;
}
}
return $rf;
} | Gets the foreign key of the referenced table
@param string $table
@param string $name
@return mixed|null | entailment |
protected function getReferencingTable($name)
{
$references = $this->getReferences();
if (array_key_exists($name, $references)) {
return $references[$name]->refTable;
}
return null;
} | Gets the referenced table name by it's relation name
to this model.
@param string $name
@return mixed|null | entailment |
protected function getReferencingModel($name)
{
if (!$this->isRelationMapped($name)) {
return null;
}
$table = $this->getReferencingTable($name);
$model = static::getModelFromTable($table);
return $model;
} | Gets the referenced model via its table using relation name.
@param $name
@return string | entailment |
public function getAttributeValue($key)
{
$value = parent::getAttributeValue($key);
$this->protectAttribute($key, $value);
return $value;
} | {@inheritdoc} | entailment |
protected function getAttributeFromArray($key)
{
$value = parent::getAttributeFromArray($key);
$this->decryptAttribute($key, $value);
return $value;
} | {@inheritdoc} | entailment |
public function setAttribute($key, $value)
{
// if protected, and trying to set the mask, throw it away
if ($this->isProtectedAttribute($key, $value)) {
return $this;
}
$return = parent::setAttribute($key, $value);
if (array_key_exists($key, $this->attributes)) {
$value = $this->attributes[$key];
$this->encryptAttribute($key, $value);
$this->attributes[$key] = $value;
}
return $return;
} | {@inheritdoc} | entailment |
public function attributesToArray()
{
$attributes = parent::attributesToArray();
$attributes = $this->addDecryptedAttributesToArray($attributes);
$attributes = $this->addProtectedAttributesToArray($attributes);
return $attributes;
} | {@inheritdoc} | entailment |
public function handle()
{
try {
if ($result = User::adminExists()) {
$this->error('Your instance is already setup.');
return;
}
} catch (\Exception $e) {
// models may not be setup, keep going
}
try {
$force = $this->option('force');
if (!file_exists('phpunit.xml')) {
copy('phpunit.xml-dist', 'phpunit.xml');
$this->info('Created phpunit.xml with default configuration.');
}
if (!file_exists('.env')) {
copy('.env-dist', '.env');
$this->info('Created .env file with default configuration.');
}
if (empty(env('APP_KEY'))) {
if (false === $this->option('no-app-key')) {
$this->call('key:generate');
} else {
$this->info('Skipping APP_KEY generate.');
}
}
$this->info('**********************************************************************************************************************');
$this->info('* Welcome to DreamFactory Setup.');
$this->info('**********************************************************************************************************************');
$this->info('Running Migrations...');
$this->call('migrate', ['--force' => $force]);
$this->info('Migration completed successfully.');
$this->info('**********************************************************************************************************************');
$this->info('**********************************************************************************************************************');
$this->info('Running Seeder...');
$this->call('db:seed', ['--force' => $force]);
$this->info('All tables were seeded successfully.');
$this->info('**********************************************************************************************************************');
$this->info('**********************************************************************************************************************');
$this->info('Creating the first admin user...');
$user = false;
while (!$user) {
$firstName = $this->option('admin_first_name');
$lastName = $this->option('admin_last_name');
$email = $this->option('admin_email');
$password = $this->option('admin_password');
$prompt = true;
if (!empty($email) && !empty($password)) {
$prompt = false;
}
if (empty($firstName)) {
$firstName = ($prompt) ? $this->ask('Enter your first name') : 'FirstName';
}
if (empty($lastName)) {
$lastName = ($prompt) ? $this->ask('Enter your last name') : 'LastName';
}
if (empty($email)) {
$email = $this->ask('Enter your email address?');
}
if (empty($password)) {
$password = $this->secret('Choose a password');
}
$passwordConfirm = ($prompt) ? $this->secret('Re-enter password') : $password;
$displayName = empty($displayName) ? $firstName . ' ' . $lastName : $displayName;
$data = [
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
'password' => $password,
'password_confirmation' => $passwordConfirm,
'name' => $displayName
];
$user = User::createFirstAdmin($data);
if (!$user) {
$this->error('Failed to create user.' . print_r($data['errors'], true));
$this->info('Please try again...');
}
}
$this->info('Successfully created first admin user.');
$this->info('**********************************************************************************************************************');
$this->warn('*************************************************** WARNING! *********************************************************');
$this->warn('* Please make sure following directories and all directories under them are readable and writable by your web server ');
$this->warn('* -> storage/');
$this->warn('* -> bootstrap/cache/');
$this->warn('* Example:');
$this->warn('* > sudo chown -R {www user}:{your user group} storage/ bootstrap/cache/ ');
$this->warn('* > sudo chmod -R 2775 storage/ bootstrap/cache/ ');
$this->warn('**********************************************************************************************************************');
$this->info('*********************************************** Setup Successful! ****************************************************');
$this->info('* Setup is complete! Your instance is ready. Please launch your instance using a browser.');
$this->info('* You can run "php artisan serve" to try out your instance without setting up a web server.');
$this->info('**********************************************************************************************************************');
} catch (\Exception $e) {
$this->error($e->getMessage());
}
} | Execute the console command. | entailment |
public function getRelation($relation)
{
$query = Relation::noConstraints(
function () use ($relation){
/** @var BaseModel $model */
$model = $this->getModel();
$relationType = $model->getReferencingType($relation);
if (RelationSchema::HAS_ONE === $relationType) {
return $model->getHasOneByRelationName($relation);
} elseif (RelationSchema::HAS_MANY === $relationType) {
return $model->getHasManyByRelationName($relation);
} elseif (RelationSchema::MANY_MANY === $relationType) {
return $model->getBelongsToManyByRelationName($relation);
} elseif (RelationSchema::BELONGS_TO === $relationType) {
return $model->getBelongsToByRelationName($relation);
}
return null;
}
);
if (!empty($query)) {
return $query;
}
if (!method_exists($this->getModel(), $relation)) {
throw new BadRequestException('Unknown relationship: ' . $relation);
}
return parent::getRelation($relation);
} | Get the relation instance for the given relation name.
@param string $relation
@return Relation
@throws BadRequestException | entailment |
protected static function getJSONIfArray($value)
{
if (is_string($value) && strpos($value, ',') !== false) {
$value = explode(',', $value);
}
if (is_array($value)) {
foreach ($value as $k => $v) {
if (is_string($v)) {
$value[$k] = trim($v);
}
}
return json_encode($value);
}
return $value;
} | @param $value
@return string | entailment |
protected static function getArrayIfJSON($value)
{
if (is_array($value)) {
return $value;
} else {
$toArray = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE) {
return $toArray;
} else {
return $value;
}
}
} | @param $value
@return mixed | entailment |
public static function toNumeric($formatType = 'none')
{
if (!is_string($formatType)) {
throw new \InvalidArgumentException('The app type "' . $formatType . '" is not a string.');
}
return static::defines(strtoupper($formatType), true);
} | @param string $formatType
@throws NotImplementedException
@throws \InvalidArgumentException
@return string | entailment |
public static function toString($numericLevel = self::NONE)
{
if (!is_numeric($numericLevel)) {
throw new \InvalidArgumentException('The app type "' . $numericLevel . '" is not numeric.');
}
return static::nameOf($numericLevel);
} | @param int $numericLevel
@throws NotImplementedException
@throws \InvalidArgumentException
@return string | entailment |
public function boot(Request $request, Kernel $kernel)
{
$config = $this->getOptions($request);
$this->app->singleton(CorsService::class, function () use ($config){
return new CorsService($config);
});
/** @noinspection PhpUndefinedMethodInspection */
//$this->app['router']->middleware('cors', HandleCors::class);
if (method_exists(\Illuminate\Routing\Router::class, 'aliasMiddleware')) {
Route::aliasMiddleware('df.cors', HandleCors::class);
} else {
/** @noinspection PhpUndefinedMethodInspection */
Route::middleware('df.cors', HandleCors::class);
}
Route::prependMiddlewareToGroup('df.api', 'df.cors');
if ($request->isMethod('OPTIONS')) {
/** @noinspection PhpUndefinedMethodInspection */
$kernel->prependMiddleware(HandlePreflight::class);
}
} | Add the Cors middleware to the router.
@param Request $request
@param Kernel $kernel
@throws \Exception | entailment |
protected function getOptions(Request $request)
{
$configs = $this->getCorsConfigs();
$uri = $request->getPathInfo() ?: '/';
/** @var CorsConfig $bestMatch */
$bestMatch = null;
foreach ($configs as $config) {
$path = $config->path;
if ($request->is($path) || (Str::startsWith($path, '^') && preg_match('{' . $path . '}i', $uri))) {
if ($bestMatch) {
// simple compare path lengths for accuracy
if (strlen($path) > strlen($bestMatch->path)) {
$bestMatch = $config;
}
} else {
$bestMatch = $config;
}
}
}
if ($bestMatch) {
return [
"allowedOrigins" => explode(',', $bestMatch->origin),
"allowedHeaders" => explode(',', $bestMatch->header),
"exposedHeaders" => explode(',', $bestMatch->exposed_header),
"allowedMethods" => $bestMatch->method,
"maxAge" => $bestMatch->max_age,
"supportsCredentials" => $bestMatch->supports_credentials,
];
}
return [];
} | Find the options for the current request, based on the paths/hosts settings.
@param Request $request
@return array
@throws \Exception | entailment |
public function sendRequest(RequestInterface $request)
{
// Options (Guzzle 6+)
$options = [];
if (Misc::isGuzzle6()) {
$options['exceptions'] = false;
if (($verify = Misc::verify($request->getUrl(), __DIR__ . '/../CA/')) !== null) {
$options['verify'] = $verify;
}
}
// Create the HTTP request
$httpRequest = $this->createHttpRequest($request);
// Send the request
$httpResponse = $this->client->send($httpRequest, $options);
// If Unauthorized, maybe the authorization just timed out.
// Try it again to be sure.
if ($httpResponse->getStatusCode() == 401 && $this->authenticationMethod != null) {
// Create the HTTP request (and Authorize again)
$httpRequest = $this->createHttpRequest($request);
// Execute again
$httpResponse = $this->client->send($httpRequest, $options);
}
// Check the status code (must be 2xx)
$statusCode = $httpResponse->getStatusCode();
if ($statusCode >= 200 && $statusCode < 300) {
return Resource::fromJson((string) $httpResponse->getBody());
}
// Exception depending on status code for 3xx, 4xx and 5xx
if ($statusCode >= 300 && $statusCode < 400) {
throw new Exception\HttpRedirectionException($httpRequest, $httpResponse);
} elseif ($statusCode >= 400 && $statusCode < 500) {
throw new Exception\HttpClientErrorException($httpRequest, $httpResponse);
} elseif ($statusCode >= 500 && $statusCode < 600) {
throw new Exception\HttpServerErrorException($httpRequest, $httpResponse);
} else {
throw new Exception\HttpException($httpRequest, $httpResponse);
}
} | {@inheritDoc} | entailment |
public function sendFollow($follow, ResourceInterface $resource = null)
{
if (!$resource) {
$resource = $this->getEntryPointResource();
}
if (!is_array($follow)) {
$follow = array($follow);
}
foreach ($follow as $hop) {
$resource = $this->sendRequest(new Request(
$hop->getUrl($resource),
$hop->getMethod(),
$hop->getUrlVariables(),
$hop->getMessageBody(),
$hop->getHeaders()
));
}
return $resource;
} | {@inheritDoc} | entailment |
public function getEntryPointResource()
{
if ($this->entryPointResource) {
return $this->entryPointResource;
}
return $this->entryPointResource = $this->sendRequest(new Request($this->entryPointUrl));
} | {@inheritDoc} | entailment |
public function refresh($resource)
{
try {
$url = $resource->getLink(RegisteredRel::SELF)->getHref();
return $this->sendRequest(new Request($url));
} catch (\Exception $ignored) {
return $resource;
}
} | {@inheritDoc} | entailment |
private function createHttpRequest(RequestInterface $request)
{
// Handle authentication first
if ($this->authenticationMethod) {
$request = $this->authenticationMethod->authorizeRequest($this, $request);
}
// The URL
$url = ltrim(trim($request->getUrl()), '/');
// Handle templated URLs
if ($urlVariables = $request->getUrlVariables()) {
$url = (new UriTemplate())->expand($url, $urlVariables);
}
// Headers
$headers = [];
$headersToAdd = $request->getHeaders();
// The message body
$body = null;
if ($messageBody = $request->getMessageBody()) {
$headers['Content-Type'] = $messageBody->getContentType();
$headers['Content-Length'] = $messageBody->getContentLength();
$body = $messageBody->getContent();
}
// Accept hal+json response
if ($this->profile) {
$headers['Accept'] = 'application/hal+json; profile="' . $this->profile . '"';
} else {
$headers['Accept'] = 'application/json';
}
// Prepare the Guzzle request
if (Misc::isGuzzle6()) {
// Guzzle 6
$httpRequest = new \GuzzleHttp\Psr7\Request(
$request->getMethod(),
$url,
array_merge($headers, $headersToAdd),
$body ? \GuzzleHttp\Psr7\stream_for($body) : null
);
} else {
// Guzzle 5.3
$httpRequest = $this->client->createRequest($request->getMethod(), $url, ['exceptions' => false]);
// verify option for HTTPS requests if needed
if (($verify = Misc::verify($url, __DIR__ . '/../CA/')) !== null) {
$httpRequest->getConfig()->set('verify', $verify);
}
foreach ($headers as $key => $value) {
$httpRequest->setHeader($key, $value);
}
foreach ($headersToAdd as $key => $value) {
$httpRequest->setHeader($key, $value);
}
if ($body) {
$httpRequest->setBody(\GuzzleHttp\Stream\Stream::factory($body));
}
}
return $httpRequest;
} | Instantiates the HttpRequest depending on the
configuration from the given Request.
@param $request RequestInterface The Request configuration.
@return The HTTP request. | entailment |
public function export()
{
$this->checkStoragePermission();
$this->gatherData();
$this->package->initZipFile();
$this->addManifestFile();
$this->addResourceFiles();
$this->addStorageFiles();
$url = $this->package->saveZipFile($this->storageService, $this->storageFolder);
return $url;
} | Extracts resources and exports the package file.
Returns URL of the exported file.
@return string
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException
@throws \DreamFactory\Core\Exceptions\NotFoundException
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
protected function checkStoragePermission()
{
Session::checkServicePermission(
Verbs::POST, $this->storageService, trim($this->storageFolder, '/'), Session::getRequestor()
);
} | Checks to see if the user exporting the package
has permission to storage the package in the target
storage service.
@throws \DreamFactory\Core\Exceptions\ForbiddenException | entailment |
public function isPublic()
{
$service = Service::whereName($this->storageService)->first()->toArray();
$publicPaths = array_get($service, 'config.public_path');
if (!empty($publicPaths)) {
foreach ($publicPaths as $pp) {
if (trim($this->storageFolder, '/') == trim($pp, '/')) {
return true;
}
}
}
return false;
} | Checks to see if the URL of the exported zip file is
publicly accessible.
@return bool | entailment |
public function getManifestOnly($systemOnly = false, $fullTree = false)
{
$this->data['system']['role'] = $this->getAllResources('system', 'role', ['fields' => 'id,name']);
$this->data['system']['service'] =
$this->getAllResources('system', 'service', ['fields' => 'id,name'], null, false);
// Keeping a separate copy of all services to fetch exportable resources for each services.
$allServices = $this->data['system']['service'];
$this->data['system']['app'] = $this->getAllResources('system', 'app', ['fields' => 'id,name']);
$this->data['system']['user'] =
$this->getAllResources('system', 'user', ['fields' => 'id,email,username,first_name,last_name']);
$this->data['system']['admin'] =
$this->getAllResources('system', 'admin', ['fields' => 'id,email,username,first_name,last_name']);
$this->data['system']['custom'] = $this->getAllResources('system', 'custom');
$this->data['system']['cors'] = $this->getAllResources('system', 'cors', ['fields' => 'id,path']);
$this->data['system']['email_template'] = $this->getAllResources('system', 'email_template',
['fields' => 'id,name']);
$this->data['system']['event_script'] = $this->getAllResources('system', 'event_script', ['fields' => 'name']);
$this->data['system']['lookup'] = $this->getAllResources('system', 'lookup', ['fields' => 'id,name']);
/* Check for paid limits class */
if (class_exists(\DreamFactory\Core\Limit\ServiceProvider::class)) {
$this->data['system']['limit'] = $this->getAllResources('system', 'limit', ['fields' => 'id,name']);
}
$manifest = $this->package->getManifestHeader();
$this->getAllowedSystemResources($manifest);
// If system/service is not allowed for the user then remove it from output array.
if (!Session::checkServicePermission(Verbs::GET, 'system', 'service', Session::getRequestor(), false)) {
unset($manifest['service']['system']['service']);
if(empty($manifest['service']['system'])){
unset($manifest['service']['system']);
}
}
if (false === $systemOnly) {
$this->getAllowedServiceResources($manifest, $allServices, $fullTree);
}
return $manifest;
} | Returns a manifest file for system-wide resources.
@param bool $systemOnly
@param bool $fullTree
@return array | entailment |
private function getAllowedServiceResources(&$manifest, $allServices, $fullTree)
{
if (!empty($allServices)) {
// Get list of active services with type for group lookup
foreach ($allServices as $service) {
$serviceName = array_get($service, 'name');
$serviceId = array_get($service, 'id');
if (Session::allowsServiceAccess($serviceName, Session::getRequestor())) {
try {
$service = ServiceManager::getService($serviceName);
if ($service->isActive()) {
$typeInfo = $service->getServiceTypeInfo();
switch ($typeInfo->getGroup()) {
case ServiceTypeGroups::FILE:
$this->getAllowedStoragePaths($manifest, $serviceName, $serviceId, $fullTree);
break;
case ServiceTypeGroups::DATABASE:
$this->getAllowedDatabaseResources($manifest, $serviceName);
break;
}
} else {
\Log::warning('Excluding inactive service:' . $serviceName . ' from manifest.');
}
} catch (\Exception $e) {
// Error occurred. Flag it, Log and let go.
$manifest['service'][$serviceName][static::REACHABLE_FLAG] = false;
\Log::alert('Failed to include service:' .
$serviceName .
' in manifest due to error:' .
$e->getMessage());
}
}
}
}
} | Gets all service resources (storage and databases) based on RBAC
@param array $manifest
@param array $allServices
@param bool $fullTree | entailment |
private function getAllowedSystemResources(&$manifest)
{
foreach ($this->data as $serviceName => $resource) {
foreach ($resource as $resourceName => $records) {
foreach ($records as $record) {
$api = $serviceName . '/' . $resourceName;
switch ($api) {
case 'system/user':
case 'system/admin':
$manifest['service'][$serviceName][$resourceName][] = [
'username' => array_get($record, 'username'),
'email' => array_get($record, 'email'),
'first_name' => array_get($record, 'first_name'),
'last_name' => array_get($record, 'last_name')
];
break;
case 'system/cors':
$manifest['service'][$serviceName][$resourceName][] = array_get($record, 'id');
break;
default:
$manifest['service'][$serviceName][$resourceName][] = array_get($record, 'name');
break;
}
}
}
}
} | Gets all system resources based on RBAC
@param array $manifest | entailment |
private function getAllowedDatabaseResources(&$manifest, $serviceName)
{
$manifest['service'][$serviceName][static::REACHABLE_FLAG] = true;
// Get all schema. This honors RBAC at the service level.
$result = $this->getAllResources($serviceName, '_schema', ['as_list' => true], null, false);
if (Session::isSysAdmin()) {
// For admins we have all schemas which apply to tables to
$manifest['service'][$serviceName]['_schema'] = $result;
$manifest['service'][$serviceName]['_table'] = $result;
} else {
if (!empty($result)) {
$manifest['service'][$serviceName]['_schema'] = $result;
} else {
$manifest['service'][$serviceName]['_schema'] = [];
}
// Get all allowed tables for non-admins
$result = $this->getAllResources($serviceName, '_table', ['as_list' => true], null, false);
if (!empty($result)) {
$manifest['service'][$serviceName]['_table'] = $result;
} else {
$manifest['service'][$serviceName]['_table'] = [];
}
}
} | Gets all DB service resources based on RBAC
@param array $manifest
@param string $serviceName | entailment |
private function getAllowedStoragePaths(&$manifest, $serviceName, $serviceId, $fullTree)
{
if (Session::isSysAdmin()) {
// Get all paths bypassing RBAC
$manifest['service'][$serviceName] = $this->getAllResources(
$serviceName, '', ['as_list' => true, 'full_tree' => $fullTree], null, false
);
} else {
$roleId = Session::getRoleId();
$requestorMask = Session::getRequestor();
$manifest['service'][$serviceName] = [];
$accesses = RoleServiceAccess::whereRoleId($roleId)
->whereServiceId($serviceId)
->whereRequestorMask($requestorMask)
->get(['component', 'verb_mask']);
foreach ($accesses as $access) {
if ($access->verb_mask & VerbsMask::toNumeric(Verbs::GET)) {
$allowedPath = $access->component;
if ($allowedPath === '*') {
$manifest['service'][$serviceName] = $this->getAllResources(
$serviceName, '', ['as_list' => true, 'full_tree' => $fullTree]
);
// Safe to break out from the loop here.
// Access === '*' mean everything is allowed anyway.
// No need to check further accesses.
break;
} else {
// Only consider paths ending with * like my/path/*
// A path without * at the end (my/path/) only allows
// for directory listing which is not useful for exports.
if (substr($allowedPath, strlen($allowedPath) - 1) === '*') {
if ($fullTree) {
$allPaths = $this->getAllResources(
$serviceName,
substr($allowedPath, 0, strlen($allowedPath) - 1),
['as_list' => true, 'full_tree' => $fullTree]
);
$manifest['service'][$serviceName] = array_merge(
$manifest['service'][$serviceName],
$allPaths
);
} else {
$manifest['service'][$serviceName][] =
substr($allowedPath, 0, strlen($allowedPath) - 1);
}
}
}
}
}
}
} | Gets all allowed storage paths based on RBAC
@param array $manifest
@param string $serviceName
@param integer $serviceId
@param bool $fullTree | entailment |
protected function getAllResources($service, $resource, $params = [], $payload = null, $checkPermission = true)
{
$resources = $this->getResource($service, $resource, $params, $payload, $checkPermission);
if (Arr::isAssoc($resources)) {
$resources = [$resources];
}
return $resources;
} | Returns all resources for service/resource.
@param $service
@param $resource
@param array $params
@param null $payload
@param bool $checkPermission
@return array|\DreamFactory\Core\Contracts\ServiceResponseInterface|mixed
@throws \DreamFactory\Core\Exceptions\NotFoundException
@throws \Exception | entailment |
protected function addResourceFiles()
{
foreach ($this->data as $service => $resources) {
foreach ($resources as $resourceName => $records) {
$this->package->zipResourceFile($service . '/' . $resourceName . '.json', $records);
}
}
} | Adds resource files to the package.
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function addStorageFiles()
{
$items = $this->package->getStorageServices();
foreach ($items as $service => $resources) {
if (is_string($resources)) {
$resources = explode(',', $resources);
}
foreach ($resources as $resourceName => $resource) {
// If reachable flag is present and service is not reachable then skip it.
if ($resourceName === static::REACHABLE_FLAG && $resource === false) {
continue;
}
if (Session::checkServicePermission(
Verbs::GET, $service, $resource, Session::getRequestor(), false
)) {
/** @type FileServiceInterface $storage */
$storage = ServiceManager::getService($service);
if (!$storage) {
throw new InternalServerErrorException("Can not find storage service $service.");
}
if ($storage->folderExists($resource)) {
$zippedResource = $this->getStorageFolderZip($storage, $resource);
if ($zippedResource !== false) {
$newFileName = $service . '/' . rtrim($resource, '/') . '/' . md5($resource) . '.zip';
$this->package->zipFile($zippedResource, $newFileName);
$this->destructible[] = $zippedResource;
}
} elseif ($storage->fileExists($resource)) {
$content = $storage->getFileContent($resource, null, false);
$this->package->zipContent($service . '/' . $resource, $content);
}
}
}
}
} | Adds app files or other storage files to the package.
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function getStorageFolderZip($storage, $resource)
{
$resource = rtrim($resource, '/') . DIRECTORY_SEPARATOR;
$zip = new \ZipArchive();
$tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$zipFileName = $tmpDir . str_replace('/', '_', $resource) . time() . '.zip';
if (true !== $zip->open($zipFileName, \ZipArchive::CREATE)) {
throw new InternalServerErrorException('Could not create zip file for extracting ' . $resource);
}
if ($storage->folderExists($resource)) {
$storage->getFolderAsZip($resource, $zip, $zipFileName, true);
} else {
return false;
}
$zip->close();
return $zipFileName;
} | Returns the path of the zip file containing
app files or other storage files.
@param FileServiceInterface $storage
@param $resource
@return bool|string
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function generateManifest()
{
$manifest = $this->package->getManifestHeader();
$requestedItems = $this->package->getServices();
foreach ($requestedItems as $service => $resources) {
foreach ($resources as $resourceName => $details) {
if (isset($this->data[$service][$resourceName])) {
$records = $this->data[$service][$resourceName];
foreach ($records as $i => $record) {
$api = $service . '/' . $resourceName;
switch ($api) {
case 'system/user':
case 'system/admin':
$manifest['service'][$service][$resourceName][] =
array_get($record, 'email', array_get($record, 'id', array_get($details, $i, [])));
break;
default:
$manifest['service'][$service][$resourceName][] =
array_get($record, 'name', array_get($record, 'id', array_get($details, $i, [])));
break;
}
}
} else {
$manifest['service'][$service][$resourceName] = $details;
}
}
}
return $manifest;
} | Generates the package manifest.
@return array | entailment |
protected function setDefaultRelations($service, $resource, &$params)
{
$api = $service . '/' . $resource;
$relations = array_get($this->defaultRelation, $api);
if (!empty($relations)) {
$this->fixDefaultRelations($relations);
if (!isset($params['related'])) {
$params['related'] = implode(',', $relations);
} else {
foreach ($relations as $relation) {
if (strpos($params['related'], $relation) === false) {
$params['related'] .= ',' . $relation;
}
}
}
}
} | Sets the default relations to extract for some resources.
@param string $service
@param string $resource
@param array $params | entailment |
protected function fixDefaultRelations(array & $relations)
{
foreach ($relations as $key => $relation) {
if ('role_adldap_by_role_id' === $relation && !class_exists(LDAP::class)) {
unset($relations[$key]);
}
}
} | Removes any relation where related service is not installed.
@param array $relations | entailment |
protected function getResource($service, $resource, $params = [], $payload = null, $checkPermission = true)
{
try {
$result = ServiceManager::handleRequest(
$service, Verbs::GET, $resource, $params, [], $payload, null, $checkPermission
);
if ($result->getStatusCode() >= 300) {
throw ResponseFactory::createExceptionFromResponse($result);
}
$result = $result->getContent();
if ($result instanceof Arrayable) {
$result = $result->toArray();
}
if (is_string($result)) {
$result = ['value' => $result];
} elseif (Arr::isAssoc($result) &&
config('df.always_wrap_resources') === true &&
isset($result[config('df.resources_wrapper')])
) {
$result = $result[config('df.resources_wrapper')];
}
// Special response handling
$rSeg = explode('/', $resource);
$api = $service . '/' . $rSeg[0];
if (isset($rSeg[1]) && in_array($api, ['system/custom', 'user/custom'])) {
$result = ['name' => $rSeg[1], 'value' => $result];
} elseif (isset($rSeg[1]) && $api === $service . '/_table') {
$result = ['name' => $rSeg[1], 'record' => $result];
}
if (in_array($api, ['system/user', 'system/admin'])) {
$this->setUserPassword($result);
}
return $result;
} catch (NotFoundException $e) {
$e->setMessage('Resource not found for ' . $service . '/' . $resource);
throw $e;
}
} | Extracts a resource
@param string $service
@param string $resource
@param array $params
@param null $payload
@param bool $checkPermission
@return array|\DreamFactory\Core\Contracts\ServiceResponseInterface|mixed
@throws \DreamFactory\Core\Exceptions\NotFoundException
@throws \Exception | entailment |
protected function setUserPassword(array & $users)
{
if (!empty($users)) {
if (Arr::isAssoc($users)) {
$users = [$users];
}
foreach ($users as $i => $user) {
/** @noinspection PhpUndefinedMethodInspection */
$model = User::find($user['id']);
if (!empty($model)) {
$users[$i]['password'] = $model->password;
}
}
}
} | Sets user password encrypted when package is secured with a password.
@param array $users
@throws \DreamFactory\Core\Exceptions\BadRequestException | entailment |
protected function getSelectionCriteria()
{
$options = $this->request->getParameters();
$payload = $this->getPayloadData();
$options = array_merge($options, $payload);
$this->request->setParameters($options);
$criteria = [
'params' => []
];
if (null !== ($value = $this->request->getParameter(ApiOptions::FIELDS))) {
$criteria['select'] = explode(',', $value);
} else {
$criteria['select'] = ['*'];
}
if (null !== ($value = $this->request->getPayloadData(ApiOptions::PARAMS))) {
$criteria['params'] = $value;
}
if (null !== ($value = $this->request->getParameter(ApiOptions::FILTER))) {
/** @type TableSchema $schema */
/** @noinspection PhpUndefinedMethodInspection */
$schema = $this->getModel()->getTableSchema();
$native = $this->convertFilterToNative($value, $criteria['params'], [], $schema->getColumns());
$criteria['condition'] = $native['where'];
if (is_array($native['params'])) {
if (is_array($criteria['params'])) {
$criteria['params'] = array_merge($criteria['params'], $native['params']);
} else {
$criteria['params'] = $native['params'];
}
}
// Add current user ID into parameter array if in condition, but not specified.
if (false !== stripos($value, ':user_id')) {
if (!isset($criteria['params'][':user_id'])) {
$criteria['params'][':user_id'] = SessionUtility::getCurrentUserId();
}
}
}
$value = intval($this->request->getParameter(ApiOptions::LIMIT));
$maxAllowed = $this->getMaxRecordsReturnedLimit();
if (($value < 1) || ($value > $maxAllowed)) {
// impose a limit to protect server
$value = $maxAllowed;
}
$criteria['limit'] = $value;
// merge in possible payload options
$optionNames = [
ApiOptions::OFFSET,
ApiOptions::ORDER,
ApiOptions::GROUP,
];
foreach ($optionNames as $option) {
if (null !== $value = $this->request->getParameter($option)) {
$criteria[$option] = $value;
} elseif (!empty($otherNames = ApiOptions::getAliases($option))) {
foreach ($otherNames as $other) {
if (null !== $value = $this->request->getParameter($other)) {
$criteria[$option] = $value;
} elseif (null !== $value = $this->request->getPayloadData($other)) {
$criteria[$option] = $value;
}
}
}
if (!isset($criteria[$option]) && ((null !== $value = $this->request->getPayloadData($option)))) {
$criteria[$option] = $value;
}
}
return $criteria;
} | Builds the selection criteria from request and returns it.
@return array | entailment |
protected function convertFilterToNative($filter, $params = [], $ss_filters = [], $avail_fields = [])
{
// interpret any parameter values as lookups
$params = (is_array($params) ? static::interpretRecordValues($params) : []);
$serverFilter = $this->buildQueryStringFromData($ss_filters);
$outParams = [];
if (empty($filter)) {
$filter = $serverFilter;
} elseif (is_string($filter)) {
if (!empty($serverFilter)) {
$filter = '(' . $filter . ') ' . DbLogicalOperators::AND_STR . ' (' . $serverFilter . ')';
}
} elseif (is_array($filter)) {
// todo parse client filter?
$filter = '';
if (!empty($serverFilter)) {
$filter = '(' . $filter . ') ' . DbLogicalOperators::AND_STR . ' (' . $serverFilter . ')';
}
}
SessionUtility::replaceLookups($filter);
$filterString = $this->parseFilterString($filter, $outParams, $avail_fields, $params);
return ['where' => $filterString, 'params' => $outParams];
} | Take in a ANSI SQL filter string (WHERE clause)
or our generic NoSQL filter array or partial record
and parse it to the service's native filter criteria.
The filter string can have substitution parameters such as
':name', in which case an associative array is expected,
for value substitution.
@param string | array $filter SQL WHERE clause filter string
@param array $params Array of substitution values
@param array $ss_filters Server-side filters to apply
@param array $avail_fields All available fields for the table
@return mixed | entailment |
protected function parseFilterValue($value, ColumnSchema $info, array &$out_params, array $in_params = [])
{
// if a named replacement parameter, un-name it because Laravel can't handle named parameters
if (is_array($in_params) && (0 === strpos($value, ':'))) {
if (array_key_exists($value, $in_params)) {
$value = $in_params[$value];
}
}
// remove quoting on strings if used, i.e. 1.x required them
if (is_string($value)) {
if ((0 === strcmp("'" . trim($value, "'") . "'", $value)) ||
(0 === strcmp('"' . trim($value, '"') . '"', $value))
) {
$value = substr($value, 1, -1);
} elseif ((0 === strpos($value, '(')) && ((strlen($value) - 1) === strrpos($value, ')'))) {
// function call
return $value;
}
}
// if not already a replacement parameter, evaluate it
// $value = $this->dbConn->getSchema()->parseValueForSet($value, $info);
switch ($info->type) {
case DbSimpleTypes::TYPE_BOOLEAN:
break;
case DbSimpleTypes::TYPE_INTEGER:
case DbSimpleTypes::TYPE_ID:
case DbSimpleTypes::TYPE_REF:
case DbSimpleTypes::TYPE_USER_ID:
case DbSimpleTypes::TYPE_USER_ID_ON_CREATE:
case DbSimpleTypes::TYPE_USER_ID_ON_UPDATE:
if (!is_int($value)) {
if (!(ctype_digit($value))) {
throw new BadRequestException("Field '{$info->getName(true)}' must be a valid integer.");
} else {
$value = intval($value);
}
}
break;
case DbSimpleTypes::TYPE_DECIMAL:
case DbSimpleTypes::TYPE_DOUBLE:
case DbSimpleTypes::TYPE_FLOAT:
break;
case DbSimpleTypes::TYPE_STRING:
case DbSimpleTypes::TYPE_TEXT:
break;
// special checks
case DbSimpleTypes::TYPE_DATE:
$cfgFormat = Config::get('df.db.date_format');
$outFormat = 'Y-m-d';
$value = DataFormatter::formatDateTime($outFormat, $value, $cfgFormat);
break;
case DbSimpleTypes::TYPE_TIME:
$cfgFormat = Config::get('df.db.time_format');
$outFormat = 'H:i:s.u';
$value = DataFormatter::formatDateTime($outFormat, $value, $cfgFormat);
break;
case DbSimpleTypes::TYPE_DATETIME:
$cfgFormat = Config::get('df.db.datetime_format');
$outFormat = 'Y-m-d H:i:s';
$value = DataFormatter::formatDateTime($outFormat, $value, $cfgFormat);
break;
case DbSimpleTypes::TYPE_TIMESTAMP:
case DbSimpleTypes::TYPE_TIMESTAMP_ON_CREATE:
case DbSimpleTypes::TYPE_TIMESTAMP_ON_UPDATE:
$cfgFormat = Config::get('df.db.timestamp_format');
$outFormat = 'Y-m-d H:i:s';
$value = DataFormatter::formatDateTime($outFormat, $value, $cfgFormat);
break;
default:
break;
}
$out_params[] = $value;
$value = '?';
return $value;
} | @param mixed $value
@param ColumnSchema $info
@param array $out_params
@param array $in_params
@return int|null|string
@throws BadRequestException | entailment |
public function getManifest($key = null, $default = null)
{
if (empty($key)) {
return $this->manifest;
}
return array_get($this->manifest, $key, $default);
} | Get package manifest.
@param null $key
@param null $default
@return array|string | entailment |
public function getExportStorageService($default = null)
{
$storage = array_get($this->manifest, 'storage', $default);
if (is_array($storage)) {
$name = array_get($storage, 'name', array_get($storage, 'id', $default));
if (is_numeric($name)) {
return ServiceManager::getServiceNameById($name);
}
return $name;
}
return $storage;
} | Gets the storage service from the manifest
to use for storing the exported zip file.
@param $default
@return mixed | entailment |
public function getExportStorageFolder($default = null)
{
$folder = array_get($this->manifest, 'storage.folder', array_get($this->manifest, 'storage.path', $default));
return (empty($folder)) ? $default : $folder;
} | Gets the storage folder from the manifest
to use for storing the exported zip file in.
@param $default
@return string | entailment |
public function getExportFilename()
{
$host = php_uname('n');
$default = $host . '_' . date('Y-m-d_H.i.s', time());
$filename = array_get(
$this->manifest,
'storage.filename',
array_get($this->manifest, 'storage.file', $default)
);
$filename = (empty($filename)) ? $default : $filename;
if (strpos($filename, static::FILE_EXTENSION) === false) {
$filename .= '.' . static::FILE_EXTENSION;
}
return $filename;
} | Returns the filename for export file.
@return string | entailment |
public function getPassword()
{
$password = array_get($this->manifest, 'password', $this->password);
if ($this->isSecured()) {
if (empty($password)) {
throw new BadRequestException('Password is required for secured package.');
} elseif (strlen($password) < static::PASSWORD_LENGTH) {
throw new BadRequestException(
'Password must be at least ' . static::PASSWORD_LENGTH . ' characters long for secured package.'
);
}
}
return $password;
} | Returns the password to use for encrypting/decrypting package.
@return string|null
@throws BadRequestException | entailment |
public function isFileService($serviceName, $resources = null)
{
$service = Service::whereName($serviceName)->first();
if (!empty($service)) {
if (null === $type = ServiceManager::getServiceType($service->type)) {
return false;
}
return (ServiceTypeGroups::FILE === $type->getGroup());
} elseif (!empty($resources)) {
if (is_string($resources)) {
$resources = explode(',', $resources);
}
foreach ($resources as $resource) {
if (is_string($resource)) {
if (false !== $this->zip->locateName(
$serviceName .
'/' .
rtrim($resource, '/') .
'/' .
md5($resource) .
'.' .
static::FILE_EXTENSION
)
) {
return true;
}
}
}
}
return false;
} | Checks to see if a service is a file/storage service.
@param $serviceName
@param $resources
@return bool | entailment |
protected function isUploadedFile($package)
{
if (isset($package['name'], $package['tmp_name'], $package['type'], $package['size'])) {
if (in_array($package['type'], ['application/zip', 'application/x-zip-compressed'])) {
return true;
}
}
return false;
} | Checks for valid uploaded file.
@param array $package
@return bool | entailment |
protected function getManifestFromUrlImport($url)
{
$extension = strtolower(pathinfo($url, PATHINFO_EXTENSION));
if (static::FILE_EXTENSION != $extension) {
throw new BadRequestException(
"Only package files ending with '" .
static::FILE_EXTENSION .
"' are allowed for import."
);
}
try {
$this->zipFile = FileUtilities::importUrlFileToTemp($url);
} catch (\Exception $ex) {
throw new InternalServerErrorException("Failed to import package from $url. " . $ex->getMessage());
}
return $this->getManifestFromZipFile();
} | Returns the manifest from url imported package file.
@param $url
@return array|string
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function getManifestFromLocalFile($file)
{
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (static::FILE_EXTENSION != $extension) {
throw new BadRequestException(
"Only package files ending with '" .
static::FILE_EXTENSION .
"' are allowed for import."
);
}
if (file_exists($file)) {
$this->zipFile = $file;
} else {
throw new InternalServerErrorException("Failed to import. File not found $file");
}
return $this->getManifestFromZipFile();
} | Retrieves manifest from a local zip file.
@param $file
@return array|string
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function getManifestFromZipFile()
{
$this->zip = new \ZipArchive();
if (true !== $this->zip->open($this->zipFile)) {
throw new InternalServerErrorException('Failed to open imported zip file.');
}
$password = $this->getPassword();
if (!empty($password)) {
$this->zip->setPassword($password);
}
$manifest = $this->zip->getFromName('package.json');
if (false === $manifest) {
throw new BadRequestException('Cannot read package manifest. A valid password is required if this is a secured package.');
}
$manifest = DataFormatter::jsonToArray($manifest);
return $manifest;
} | Retrieves the manifest file from package file.
@return array|string
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException
@throws \DreamFactory\Core\Exceptions\BadRequestException | entailment |
protected function setManifestItems()
{
$m = $this->manifest;
if (!empty($m)) {
if (isset($m['service']) && is_array($m['service'])) {
foreach ($m['service'] as $item => $value) {
if ($this->isFileService($item, $value)) {
$this->storageItems[$item] = $value;
} else {
$this->nonStorageItems[$item] = $value;
}
}
}
if (count($this->getServices()) == 0) {
throw new InternalServerErrorException('No items found in package manifest.');
}
}
} | Sets manifest items as class property.
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
public function initZipFile()
{
$filename = $this->getExportFilename();
$zip = new \ZipArchive();
$tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$zipFileName = $tmpDir . $filename;
$this->zip = $zip;
$this->zipFile = $zipFileName;
if (true !== $this->zip->open($zipFileName, \ZipArchive::CREATE)) {
throw new InternalServerErrorException('Failed to initiate package Zip Archive.');
}
return true;
} | Initialize export zip file.
@return bool
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
public function zipResourceFile($file, $resource)
{
if (!$this->zip->addFromString($file, json_encode($resource, JSON_UNESCAPED_SLASHES))) {
throw new InternalServerErrorException("Failed to add $file to the Zip Archive.");
}
} | Adds resource file to ZipArchive.
@param $file
@param $resource
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
public function getResourceFromZip($resourceFile)
{
$data = [];
$json = $this->zip->getFromName($resourceFile);
if (false !== $json) {
$data = json_decode($json, JSON_UNESCAPED_SLASHES);
}
return $data;
} | Retrieves resource data from ZipArchive.
@param $resourceFile
@return array | entailment |
public function getZipFromZip($file)
{
$fh = $this->zip->getStream($file);
if (false !== $fh) {
$contents = null;
while (!feof($fh)) {
$contents .= fread($fh, 2);
}
$tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$zipFile = $tmpDir . md5($file) . time() . '.' . static::FILE_EXTENSION;
file_put_contents($zipFile, $contents);
$zip = new \ZipArchive();
if (true !== $zip->open($zipFile)) {
throw new InternalServerErrorException('Error opening zip file ' . $file . '.');
}
$this->destructible[] = $zipFile;
return $zip;
}
return null;
} | Retrieves zipped folder from ZipArchive.
@param $file
@return null|\ZipArchive
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
public function getFileFromZip($file)
{
if (false !== $content = $this->zip->getFromName($file)) {
$tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$fileName = $tmpDir . md5($file) . time() . '.' . pathinfo($file, PATHINFO_EXTENSION);
file_put_contents($fileName, $content);
$this->destructible[] = $fileName;
return $fileName;
}
return null;
} | Retrieves a file from ZipArchive.
@param $file
@return null|string | entailment |
public function saveZipFile($storageService, $storageFolder)
{
try {
$this->zip->close();
if ($this->isSecured()) {
$password = $this->getPassword();
$tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$extractDir = $tmpDir . substr(basename($this->zipFile), 0, strlen(basename($this->zipFile)) - 4);
$tmpZip = new \ZipArchive();
$tmpZip->open($this->zipFile);
$tmpZip->extractTo($extractDir);
$tmpZip->close();
@unlink($this->zipFile);
$server = strtolower(php_uname('s'));
$commandSeparator = ';';
if (strpos($server, 'windows') !== false) {
$commandSeparator = '&';
}
@exec("cd $extractDir $commandSeparator zip -r -P $password $this->zipFile .", $output);
\Log::info('Encrypting zip file with a password.', $output);
@FileUtilities::deleteTree($extractDir, true);
}
/** @type FileServiceInterface $storage */
$storage = ServiceManager::getService($storageService);
if (!$storage->folderExists($storageFolder)) {
$storage->createFolder($storageFolder);
}
$storage->moveFile($storageFolder . '/' . basename($this->zipFile), $this->zipFile);
$url = Environment::getURI() .
'/api/v2/' .
$storageService .
'/' .
$storageFolder .
'/' .
basename($this->zipFile);
return $url;
} catch (\Exception $e) {
throw new InternalServerErrorException(
'Failed to save the exported package using storage service ' .
$storageService . '. ' .
$e->getMessage()
);
}
} | Saves ZipArchive.
@param $storageService
@param $storageFolder
@return string
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
public function show(Request $request)
{
$post = $this->api('post.fetch', $request->route('post'))->parameters(['with' => ['thread', 'thread.category', 'parent']])->get();
event(new UserViewingPost($post));
$thread = $post->thread;
$category = $thread->category;
return view('forum::post.show', compact('category', 'thread', 'post'));
} | GET: Return a post view.
@param Request $request
@return \Illuminate\Http\Response | entailment |
public function create(Request $request)
{
$thread = $this->api('thread.fetch', $request->route('thread'))->parameters(['with' => ['posts']])->get();
$this->authorize('reply', $thread);
event(new UserCreatingPost($thread));
$post = null;
if ($request->has('post')) {
$post = $thread->posts->find($request->input('post'));
}
return view('forum::post.create', compact('thread', 'post'));
} | GET: Return a 'create post' (thread reply) view.
@param Request $request
@return \Illuminate\Http\Response | entailment |
public function store(Request $request)
{
$thread = $this->api('thread.fetch', $request->route('thread'))->parameters(['with' => ['posts']])->get();
$this->authorize('reply', $thread);
$post = null;
if ($request->has('post')) {
$post = $thread->posts->find($request->input('post'));
}
$post = $this->api('post.store')->parameters([
'thread_id' => $thread->id,
'author_id' => auth()->user()->getKey(),
'post_id' => is_null($post) ? 0 : $post->id,
'content' => $request->input('content')
])->post();
$post->thread->touch();
Forum::alert('success', 'general.reply_added');
return redirect(Forum::route('thread.show', $post));
} | POST: Create a post.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function edit(Request $request)
{
$post = $this->api('post.fetch', $request->route('post'))->get();
event(new UserEditingPost($post));
if ($post->trashed()) {
return abort(404);
}
$this->authorize('edit', $post);
$thread = $post->thread;
$category = $post->thread->category;
return view('forum::post.edit', compact('category', 'thread', 'post'));
} | GET: Return an 'edit post' view.
@param Request $request
@return \Illuminate\Http\Response | entailment |
public function update(Request $request)
{
$post = $this->api('post.fetch', $request->route('post'))->get();
$this->authorize('edit', $post);
$post = $this->api('post.update', $request->route('post'))->parameters($request->only('content'))->patch();
Forum::alert('success', 'posts.updated');
return redirect(Forum::route('thread.show', $post));
} | PATCH: Update an existing post.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function destroy(Request $request)
{
$permanent = !config('forum.preferences.soft_deletes');
$parameters = $request->all();
$parameters['force'] = $permanent ? 1 : 0;
$post = $this->api('post.delete', $request->route('post'))->parameters($parameters)->delete();
Forum::alert('success', 'posts.deleted', 1);
return redirect(Forum::route('thread.show', $post->thread));
} | DELETE: Delete a post.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function bulkDestroy(Request $request)
{
$this->validate($request, ['action' => 'in:delete,permadelete']);
$parameters = $request->all();
$parameters['force'] = 0;
if (!config('forum.preferences.soft_deletes') || ($request->input('action') == 'permadelete')) {
$parameters['force'] = 1;
}
$posts = $this->api('bulk.post.delete')->parameters($parameters)->delete();
return $this->bulkActionResponse($posts, 'posts.deleted');
} | DELETE: Delete posts in bulk.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function bulkUpdate(Request $request)
{
$this->validate($request, ['action' => 'in:restore']);
$action = $request->input('action');
$threads = $this->api("bulk.post.{$action}")->parameters($request->all())->patch();
return $this->bulkActionResponse($threads, 'posts.updated');
} | PATCH: Update posts in bulk.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function setDescriptionAttribute($value)
{
if (strlen($value) > 255) {
$value = substr($value, 0, 255);
}
$this->attributes['description'] = $value;
} | Making sure description is no longer than 255 characters.
@param $value | entailment |
public static function getCachedInfo($id, $key = null, $default = null)
{
$cacheKey = 'role:' . $id;
try {
$result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use ($id){
$role = Role::with(
[
'role_service_access_by_role_id',
'service_by_role_service_access'
]
)->whereId($id)->first();
if (empty($role)) {
throw new NotFoundException("Role not found.");
}
$roleInfo = $role->toArray();
$services = array_get($roleInfo, 'service_by_role_service_access');
unset($roleInfo['service_by_role_service_access']);
foreach ($roleInfo['role_service_access_by_role_id'] as $key => $value) {
$serviceName = array_by_key_value(
$services,
'id',
array_get($value, 'service_id'), 'name'
);
$component = array_get($value, 'component');
$roleInfo['role_service_access_by_role_id'][$key]['service'] = $serviceName;
$roleInfo['role_service_access_by_role_id'][$key]['component'] = trim($component, '/');
}
return $roleInfo;
});
if (is_null($result)) {
return $default;
}
} catch (ModelNotFoundException $ex) {
return $default;
}
if (is_null($key)) {
return $result;
}
return (isset($result[$key]) ? $result[$key] : $default);
} | Returns role info cached, or reads from db if not present.
Pass in a key to return a portion/index of the cached data.
@param int $id
@param null|string $key
@param null $default
@return mixed|null | entailment |
final public function check() : bool
{
if(empty($this->getTimestamp())){
throw new InvalidTimestampException('请设置参数:' . $this->input_timestamp);
}
if(date("Y-m-d H:i:s", strtotime($this->getTimestamp())) != $this->getTimestamp()){
throw new InvalidTimestampException('参数格式错误:' . $this->input_timestamp);
}
if(strtotime($this->getTimestamp()) < time() - $this->lifetime){
throw new InvalidTimestampException('生成的请求参数已经超过有效期');
}
return true;
} | 在isSupport方法返回false的情况下,不应该调用check方法
{@inheritDoc}
@see \asbamboo\api\apiStore\validator\CheckerInterface::check() | entailment |
public function handle()
{
try {
$data = $this->argument('data');
if (filter_var($data, FILTER_VALIDATE_URL)) {
// need to download file
$data = FileUtilities::importUrlFileToTemp($data);
}
if (is_file($data)) {
$data = file_get_contents($data);
}
$format = $this->option('format');
$format = DataFormats::toNumeric($format);
$this->comment($format);
$service = $this->option('service');
$resource = $this->option('resource');
$result = ServiceManager::handleRequest($service, Verbs::POST, $resource, [], [], $data, $format, false);
if ($result->getStatusCode() >= 300) {
$this->error(print_r($result->getContent(), true));
} else {
$this->info('Import complete!');
}
} catch (\Exception $e) {
$this->error($e->getMessage());
}
} | Execute the console command.
@return mixed | entailment |
public function quoteName($name)
{
if (strpos($name, '.') === false) {
return $this->quoteSimpleName($name);
}
$parts = explode('.', $name);
foreach ($parts as $i => $part) {
if ('*' !== $part) { // last part may be wildcard, i.e. select table.*
$parts[$i] = $this->quoteSimpleName($part);
}
}
return implode('.', $parts);
} | Quotes a resource name for use in a query.
If the resource name contains schema prefix, the prefix will also be properly quoted.
@param string $name resource name
@return string the properly quoted resource name | entailment |
public function authorizeRequest(Http\HapiClient $hapiClient, Http\Request $request)
{
if ($this->isRequestAuthorized($request)) {
return $request;
}
// Request a new access token if needed
if (!$this->isTokenStillValid()) {
$this->getAccessToken($hapiClient);
}
// Rebuild the request with the new Authorization header
$headers = $request->getHeaders();
unset($headers['Authorization']);
$headers['Authorization'] = 'Bearer ' . $this->token->getValue();
return new Http\Request(
$request->getUrl(),
$request->getMethod(),
$request->getUrlVariables(),
$request->getMessageBody(),
$headers
);
} | Adds the authorization header to the request with a valid token.
If we do not have a valid token yet, we send a request for one.
@param $hapiClient The client used to send the request.
@param $request The request before it is sent.
@return Request The same Request with the authorization Headers.
@throws HttpException | entailment |
private function getAccessToken(Http\HapiClient $hapiClient)
{
$urlEncodedBody = new Http\UrlEncodedBody([
'grant_type' => $this->grantType,
'scope' => $this->scope
]);
$basic = base64_encode($this->userid . ':' . $this->password);
$authorizationHeader = [
'Accept' => 'application/json',
'Authorization' => 'Basic ' . $basic
];
$request = new Http\Request(
$this->tokenEndPointUrl,
'POST',
null,
$urlEncodedBody,
$authorizationHeader
);
// Send the request
$state = $hapiClient->sendRequest($request)->getState();
// Check the response
if (!isset($state['access_token']) || !isset($state['expires_in'])) {
throw new \Exception('The authentication was a success but the response did not contain the token or its validity limit.');
}
// We update the token
$this->token = new ExpirableToken($state['access_token'], $this->getTime() + $state['expires_in']);
} | Sends a request for an access token.
@param $hapiClient The client used to send the request.
@throws HttpException | entailment |
public function handle($request, Closure $next)
{
if (!in_array($method = \Request::getMethod(), Verbs::getDefinedConstants())) {
throw new MethodNotAllowedHttpException(Verbs::getDefinedConstants(),
"Invalid or unsupported verb '$method' used in request.");
}
// Allow console requests through
if (env('DF_IS_VALID_CONSOLE_REQUEST', false)) {
return $next($request);
}
try {
// if the request provides a JWT and it is bad, throw reason first
if (Session::getBool('token_expired')) {
throw new UnauthorizedException(Session::get('token_expired_msg'));
} elseif (Session::getBool('token_blacklisted')) {
throw new ForbiddenException(Session::get('token_blacklisted_msg'));
} elseif (Session::getBool('token_invalid')) {
throw new UnauthorizedException(Session::get('token_invalid_msg'));
}
/** @var Router $router */
$router = app('router');
// root of API gives available service listing
if (empty($service = strtolower($router->input('service')))) {
return $next($request);
}
$component = strtolower($router->input('resource'));
$requestor = Session::getRequestor();
$permException = null;
try {
Session::checkServicePermission($method, $service, $component, $requestor);
return $next($request);
} catch (RestException $e) {
$permException = $e;
}
// No access allowed, figure out the best error response
$apiKey = Session::getApiKey();
$token = Session::getSessionToken();
$roleId = Session::getRoleId();
$callFromLocalScript = (ServiceRequestorTypes::SCRIPT == $requestor);
if (!$callFromLocalScript && empty($apiKey) && empty($token)) {
$msg = 'No session token (JWT) or API Key detected in request. ' .
'Please send in X-DreamFactory-Session-Token and/or X-DreamFactory-API-Key request header. ' .
'You can also use URL query parameters session_token and/or api_key.';
throw new BadRequestException($msg);
} elseif (empty($roleId)) {
if (empty($apiKey)) {
throw new BadRequestException(
"No API Key provided. Please provide a valid API Key using X-DreamFactory-API-Key request header or 'api_key' url query parameter."
);
} elseif (empty($token)) {
throw new BadRequestException(
"No session token (JWT) provided. Please provide a valid JWT using X-DreamFactory-Session-Token request header or 'session_token' url query parameter."
);
} else {
throw new ForbiddenException(
"Role not found. A role may not be assigned to you or your application."
);
}
} elseif (!Role::getCachedInfo($roleId, 'is_active')) {
throw new ForbiddenException("Access Forbidden. The role assigned to you or your application or the default role of your application is not active.");
} elseif (!Session::isAuthenticated()) {
throw new UnauthorizedException('Unauthorized. User is not authenticated.');
} else {
if ($permException) {
// Try to get a detail error message if possible.
$permException->setMessage('Access Forbidden. ' . $permException->getMessage());
throw $permException;
}
$msg = 'Access Forbidden. You do not have enough privileges to access this resource.';
throw new ForbiddenException($msg);
}
} catch (\Exception $e) {
return ResponseFactory::sendException($e);
}
} | @param Request $request
@param Closure $next
@return array|mixed|string | entailment |
public static function reformatData($data, $sourceFormat = null, $targetFormat = null)
{
if (is_null($data) || ($sourceFormat == $targetFormat)) {
return $data;
}
switch ($sourceFormat) {
case DataFormats::JSON:
if (is_array($data)) {
$data = self::jsonEncode($data);
}
switch ($targetFormat) {
case DataFormats::XML:
return static::jsonToXml($data);
case DataFormats::CSV:
return static::jsonToCsv($data);
case DataFormats::PHP_ARRAY:
return static::jsonToArray($data);
}
break;
case DataFormats::XML:
switch ($targetFormat) {
case DataFormats::JSON:
return static::xmlToJson($data);
case DataFormats::CSV:
return static::xmlToCsv($data);
case DataFormats::PHP_ARRAY:
return static::xmlToArray($data);
}
break;
case DataFormats::CSV:
switch ($targetFormat) {
case DataFormats::JSON:
return static::csvToJson($data);
case DataFormats::XML:
return static::csvToXml($data);
case DataFormats::PHP_ARRAY:
return static::csvToArray($data);
}
break;
case DataFormats::PHP_ARRAY:
switch ($targetFormat) {
case DataFormats::JSON:
// Symfony Response object automatically converts this.
return $data;
// return static::arrayToJson( $data );
case DataFormats::XML:
return static::arrayToXml($data);
case DataFormats::CSV:
return static::arrayToCsv($data);
case DataFormats::TEXT:
return json_encode($data);
case DataFormats::PHP_ARRAY:
return $data;
}
break;
case DataFormats::PHP_OBJECT:
switch ($targetFormat) {
case DataFormats::JSON:
// Symfony Response object automatically converts this.
return $data;
// return static::arrayToJson( $data );
case DataFormats::XML:
return static::arrayToXml($data);
case DataFormats::CSV:
return static::arrayToCsv($data);
case DataFormats::TEXT:
return json_encode($data);
case DataFormats::PHP_ARRAY:
return $data;
}
break;
case DataFormats::RAW:
case DataFormats::TEXT:
// treat as string for the most part
switch ($targetFormat) {
case DataFormats::JSON:
return json_encode($data);
case DataFormats::XML:
$root = config('df.xml_response_root', 'dfapi');
return '<?xml version="1.0" ?>' . "<$root>$data</$root>";
case DataFormats::CSV:
case DataFormats::TEXT:
return $data;
case DataFormats::PHP_ARRAY:
return [$data];
}
break;
}
return false;
} | @param mixed $data
@param string $sourceFormat
@param string $targetFormat
@return array|mixed|null|string|boolean false if not successful | entailment |
public static function xmlToArray($contents, $get_attributes = 0, $priority = 'tag')
{
if (empty($contents)) {
return null;
}
if (!function_exists('xml_parser_create')) {
//print "'xml_parser_create()' function not found!";
return null;
}
//Get the XML parser of PHP - PHP must have this module for the parser to work
$parser = xml_parser_create('');
xml_parser_set_option(
$parser,
XML_OPTION_TARGET_ENCODING,
"UTF-8"
); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);
if (!$xml_values) {
return null;
} //Hmm...
//Initializations
$xml_array = [];
$current = &$xml_array; //Reference
//Go through the tags.
$repeated_tag_index = []; //Multiple tags with same name will be turned into an array
foreach ($xml_values as $data) {
unset($attributes, $value); //Remove existing values, or there will be trouble
//This command will extract these variables into the foreach scope
// tag(string) , type(string) , level(int) , attributes(array) .
extract($data); //We could use the array by itself, but this cooler.
$result = [];
$attributes_data = [];
if (isset($value)) {
if ($priority == 'tag') {
$result = $value;
} else {
$result['value'] = $value;
} //Put the value in a assoc array if we are in the 'Attribute' mode
}
//Set the attributes too.
if (isset($attributes) and $get_attributes) {
foreach ($attributes as $attr => $val) {
if ($priority == 'tag') {
$attributes_data[$attr] = $val;
} else {
$result['attr'][$attr] = $val;
} //Set all the attributes in a array called 'attr'
}
}
//See tag status and do the needed.
/** @var string $type */
/** @var string $tag */
/** @var string $level */
if ($type == "open") { //The starting of the tag '<tag>'
$parent[$level - 1] = &$current;
if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
$current[$tag] = $result;
if ($attributes_data) {
$current[$tag . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level] = 1;
$current = &$current[$tag];
} else { //There was another element with the same tag name
if (isset($current[$tag][0])) { //If there is a 0th element it is already an array
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
$repeated_tag_index[$tag . '_' . $level]++;
} else { //This section will make the value an array if multiple tags with the same name appear together
$current[$tag] = [
$current[$tag],
$result
]; //This will combine the existing item and the new item together to make an array
$repeated_tag_index[$tag . '_' . $level] = 2;
if (isset($current[$tag .
'_attr'])) { //The attribute of the last(0th) tag must be moved as well
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
}
$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
$current = &$current[$tag][$last_item_index];
}
} elseif ($type == "complete") { //Tags that ends in 1 line '<tag />'
//See if the key is already taken.
if (!isset($current[$tag])) { //New Key
$current[$tag] = (is_array($result) && empty($result)) ? '' : $result;
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $attributes_data) {
$current[$tag . '_attr'] = $attributes_data;
}
} else { //If taken, put all things inside a list(array)
if (isset($current[$tag][0]) and is_array($current[$tag])) { //If it is already an array...
// ...push the new element into that array.
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
if ($priority == 'tag' and $get_attributes and $attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level]++;
} else { //If it is not an array...
$current[$tag] = [
$current[$tag],
$result
]; //...Make it an array using using the existing value and the new value
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $get_attributes) {
if (isset($current[$tag .
'_attr'])) { //The attribute of the last(0th) tag must be moved as well
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
if ($attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
}
$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
}
}
} elseif ($type == 'close') { //End of tag '</tag>'
$current = &$parent[$level - 1];
}
}
return $xml_array;
} | xml2array() will convert the given XML text to an array in the XML structure.
Link: http://www.bin-co.com/php/scripts/xml2array/
Arguments : $contents - The XML text
$get_attributes - 1 or 0. If this is 1 the function will
get the attributes as well as the tag values
- this results in a different array structure in the return value.
$priority - Can be 'tag' or 'attribute'. This will change the way the resulting array structure.
For 'tag', the tags are given more importance.
Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
Examples: $array = xml2array(file_get_contents('feed.xml'));
$array = xml2array(file_get_contents('feed.xml', 1, 'attribute')); | entailment |
public static function xmlToObject($xml_string)
{
if (empty($xml_string)) {
return null;
}
libxml_use_internal_errors(true);
try {
if (false === $xml = simplexml_load_string($xml_string)) {
throw new \Exception("Invalid XML Data: ");
}
// check for namespace
$namespaces = $xml->getNamespaces();
if (0 === $xml->count() && !empty($namespaces)) {
$perNamespace = [];
foreach ($namespaces as $prefix => $uri) {
if (false === $nsXml = simplexml_load_string($xml_string, null, 0, $prefix, true)) {
throw new \Exception("Invalid XML Namespace ($prefix) Data: ");
}
$perNamespace[$prefix] = $nsXml;
}
if (1 === count($perNamespace)) {
return current($perNamespace);
}
return $perNamespace;
}
return $xml;
} catch (\Exception $ex) {
$xmlstr = explode("\n", $xml_string);
$errstr = "[INVALIDREQUEST]: Invalid XML Data: ";
foreach (libxml_get_errors() as $error) {
$errstr .= static::displayXmlError($error, $xmlstr) . "\n";
}
libxml_clear_errors();
throw new \Exception($errstr);
}
} | @param string $xml_string
@return null|\SimpleXMLElement
@throws \Exception | entailment |
public static function jsonToArray($json)
{
if (empty($json)) {
return null;
}
$array = json_decode($json, true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
$message = null;
break;
case JSON_ERROR_STATE_MISMATCH:
$message = 'Invalid or malformed JSON';
break;
case JSON_ERROR_UTF8:
$message = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
case JSON_ERROR_DEPTH:
$message = 'The maximum stack depth has been exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
$message = 'Control character error, possibly incorrectly encoded';
break;
case JSON_ERROR_SYNTAX:
$message = 'Syntax error, malformed JSON';
break;
default:
$message = 'Unknown error';
break;
}
if (!empty($message)) {
throw new \InvalidArgumentException('JSON Error: ' . $message);
}
return $array;
} | @param string $json
@return array
@throws \Exception | entailment |
public static function csvToArray($csv)
{
// currently need to write out to file to use parser
$tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$filename = $tmpDir . 'csv_import' . time() . '.csv';
file_put_contents($filename, $csv);
// assume first row is field header
$result = [];
ini_set('auto_detect_line_endings', true);
if (($handle = fopen($filename, "r")) !== false) {
$headers = fgetcsv($handle, null, ",");
while (false !== ($row = fgetcsv($handle))) {
$new = [];
foreach ($headers as $key => $value) {
$new[$value] = array_get($row, $key);
}
$result[] = $new;
}
fclose($handle);
unlink($filename);
}
return $result;
} | @param string $csv
@return array | entailment |
public static function simpleArrayToXml($array, $suppress_empty = false)
{
$xml = '';
foreach ($array as $key => $value) {
$value = trim($value, " ");
if (empty($value) and (bool)$suppress_empty) {
continue;
}
$htmlValue = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
if ($htmlValue != $value) {
$xml .= "\t" . "<$key>$htmlValue</$key>\n";
} else {
$xml .= "\t" . "<$key>$value</$key>\n";
}
}
return $xml;
} | @param array $array
@param bool $suppress_empty
@return string | entailment |
protected static function arrayToXmlInternal($data, $root = null, $level = 1, $format = true)
{
$xml = null;
if (is_array($data)) {
if (!Arr::isAssoc($data)) {
foreach ($data as $value) {
$xml .= self::arrayToXmlInternal($value, $root, $level, $format);
}
} else {
if (Arr::isAssoc($data)) {
if (!empty($root)) {
if ($format) {
$xml .= str_repeat("\t", $level - 1);
}
$xml .= "<$root>";
if ($format) {
$xml .= "\n";
}
}
foreach ($data as $key => $value) {
$xml .= self::arrayToXmlInternal($value, $key, $level + 1, $format);
}
if (!empty($root)) {
if ($format) {
$xml .= str_repeat("\t", $level - 1);
}
$xml .= "</$root>";
if ($format) {
$xml .= "\n";
}
}
} else {
// empty array
if (!empty($root)) {
if ($format) {
$xml .= str_repeat("\t", $level - 1);
}
$xml .= "<$root></$root>";
if ($format) {
$xml .= "\n";
}
}
}
}
} elseif (is_object($data)) {
if ($data instanceof Arrayable) {
$xml .= self::arrayToXmlInternal($data->toArray(), $root, $level, $format);
} else {
$dataString = (string)$data;
if (!empty($root)) {
if ($format) {
$xml .= str_repeat("\t", $level - 1);
}
$xml .= "<$root>$dataString</$root>";
if ($format) {
$xml .= "\n";
}
}
}
} else {
// not an array or object
if (!empty($root)) {
if ($format) {
$xml .= str_repeat("\t", $level - 1);
}
$xml .= "<$root>";
if (!is_null($data)) {
if (is_bool($data)) {
$xml .= ($data) ? 'true' : 'false';
} else {
if (is_int($data) || is_float($data)) {
$xml .= $data;
} else {
if (is_string($data)) {
$htmlValue = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
$xml .= $htmlValue;
}
}
}
}
$xml .= "</$root>";
if ($format) {
$xml .= "\n";
}
}
}
return $xml;
} | @param mixed $data
@param string $root
@param int $level
@param bool $format
@return string | entailment |
public static function arrayToXml($data, $root = null, $level = 1, $format = true)
{
if (empty($root)) {
$root = config('df.xml_root', 'dfapi');
}
return '<?xml version="1.0" ?>' . static::arrayToXmlInternal($data, $root, $level, $format);
} | @param mixed $data
@param string $root
@param int $level
@param bool $format
@return string | entailment |
public static function arrayToCsv($array)
{
if (!is_array($array) || empty($array)) {
return '';
}
$array = array_get($array, ResourcesWrapper::getWrapper(), array_get($array, 'error', $array));
$data = [];
if (!isset($array[0])) {
$data[] = $array;
} else {
$data = $array;
}
$keys = array_keys(array_get($data, 0, []));
// currently need to write out to file to use parser
$tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$filename = $tmpDir . 'csv_export' . time() . '.csv';
$handle = fopen($filename, 'w');
// build header row
fputcsv($handle, $keys);
foreach ($data as $row) {
foreach ($row as $key => $value) {
// handle objects and array non-conformist to csv output
if (is_array($value) || is_object($value)) {
$row[$key] = json_encode($value);
}
}
fputcsv($handle, $row);
}
fclose($handle);
$csv = file_get_contents($filename);
unlink($filename);
return $csv;
} | @param array $array
@return string | entailment |
public static function jsonEncode($data, $prettyPrint = false)
{
$data = static::export($data);
if (version_compare(PHP_VERSION, '5.4', '>=')) {
$options = JSON_UNESCAPED_SLASHES | (false !== $prettyPrint ? JSON_PRETTY_PRINT : 0) | JSON_NUMERIC_CHECK;
return json_encode($data, $options);
}
$json = str_replace('\/', '/', json_encode($data));
return $prettyPrint ? static::pretty_json($json) : $json;
} | @param mixed $data Could be object, array, or simple type
@param bool $prettyPrint
@return null|string | entailment |
public static function export($data)
{
if (is_object($data)) {
// Allow embedded export method for specific export
if ($data instanceof Arrayable || method_exists($data, 'toArray')) {
$data = $data->toArray();
} else {
$data = get_object_vars($data);
}
}
if (!is_array($data)) {
return $data;
}
$output = [];
foreach ($data as $key => $value) {
$output[$key] = static::export($value);
}
return $output;
} | Build the array from data.
@param mixed $data
@return mixed | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.