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 $... | @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;
... | @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 ... | @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->pic... | @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];
}
... | @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);
... | @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 ... | @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 [... | @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;
... | 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 ... | 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 = ['*'];
}
... | 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
... | 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) {
/** @v... | 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);
}
... | @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);
}
... | @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];
... | 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)) ... | {@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 {
... | 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 (RelationSch... | 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] = ... | @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 $val... | @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->ap... | 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($... | 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) {
$opti... | {@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) {
$r... | {@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())... | 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->stor... | 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\No... | 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, '/') == tri... | 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... | 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');
$s... | 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;
swit... | 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);
... | 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' => $f... | 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];
}
retu... | 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 => $resour... | 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) .... | 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->d... | 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'])) {
... | 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->getS... | 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::... | 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 (n... | 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);
... | 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 $fi... | 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($valu... | @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 ServiceM... | 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)
);
$filena... | 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) < sta... | 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 (ServiceTy... | 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 .
... | 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 .
... | 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)) ... | 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)) {
$thi... | 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;
... | 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_SE... | 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_p... | 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;
$extr... | 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 vie... | 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')) {
... | 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->inp... | 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;
... | 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.... | 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();
Foru... | 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')) {
$p... | 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(
[
... | 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('... | 在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)) {
... | 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.*
... | 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($hap... | 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 HttpExceptio... | 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);
$authorizationHeade... | 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.");
}
//... | @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)) {
... | @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;
}
... | 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... | 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: ");
... | @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_MI... | @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 ... | @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 = htmlspecialch... | @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)... | @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;
... | @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($da... | @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_va... | 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.