sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function handleServiceRequest(
ServiceRequestInterface $request,
$service,
$resource = null,
$check_permission = true,
$throw_exception = true
) {
if ($check_permission) {
if (false === Session::checkServicePermission($request->getMethod(), $service, $resource,
$request->getRequestorType(), $throw_exception)) {
return new ServiceResponse([]);
}
}
return $this->getService($service)->handleRequest($request, $resource);
} | @param ServiceRequestInterface $request
@param string $service
@param string|null $resource
@param bool $check_permission
@param bool $throw_exception
@return \DreamFactory\Core\Contracts\ServiceResponseInterface
@throws \Exception | entailment |
public function handleRequest(
$service,
$verb = Verbs::GET,
$resource = null,
$query = [],
$header = [],
$payload = null,
$format = null,
$check_permission = true,
$throw_exception = false
) {
if ($check_permission === true) {
if (false === Session::checkServicePermission($verb, $service, $resource, Session::getRequestor(),
$throw_exception)) {
return new ServiceResponse([]);
}
}
$_FILES = []; // reset so that internal calls can handle other files.
$request = new ServiceRequest();
$request->setMethod($verb);
$request->setParameters($query);
$request->setHeaders($header);
if (!empty($payload)) {
if (is_array($payload)) {
$request->setContent($payload);
} elseif (empty($format)) {
throw new BadRequestException('Payload with undeclared format.');
} else {
$request->setContent($payload, $format);
}
}
return $this->getService($service)->handleRequest($request, $resource);
} | @param string $service
@param string $verb
@param string|null $resource
@param array $query
@param array $header
@param null $payload
@param string|null $format
@param bool $check_permission
@param bool $throw_exception
@return \DreamFactory\Core\Contracts\ServiceResponseInterface
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
protected function makeService($name)
{
$config = $this->getConfig($name);
// First we will check by the service name to see if an extension has been
// registered specifically for that service. If it has we will call the
// Closure and pass it the config allowing it to resolve the service.
if (isset($this->extensions[$name])) {
return call_user_func($this->extensions[$name], $config, $name);
}
$config = $this->getDbConfig($name);
$type = $config['type'];
// Next we will check to see if a type extension has been registered for a service type
// and will call the factory Closure if so, which allows us to have a more generic
// resolver for the service types themselves which applies to all services.
if (isset($this->types[$type])) {
return $this->types[$type]->make($name, $config);
}
throw new InvalidArgumentException("Unsupported service type '$type'.");
} | Make the service instance.
@param string $name
@return \DreamFactory\Core\Contracts\ServiceInterface
@throws \DreamFactory\Core\Exceptions\NotFoundException | entailment |
protected function getConfig($name)
{
if (empty($name)) {
throw new InvalidArgumentException("Service 'name' can not be empty.");
}
$services = $this->app['config']['df.service'];
return array_get($services, $name);
} | Get the configuration for a service.
@param string $name
@return array
@throws \InvalidArgumentException | entailment |
protected function getDbConfig($name)
{
if (empty($name)) {
throw new InvalidArgumentException("Service 'name' can not be empty.");
}
return \Cache::rememberForever('service_mgr:' . $name, function () use ($name) {
/** @var Service $service */
if (empty($service = Service::whereName($name)->first())) {
throw new NotFoundException("Could not find a service for $name");
}
$service->protectedView = false;
return $service->toArray();
});
} | Get the configuration for a service.
@param string $name
@return array
@throws \DreamFactory\Core\Exceptions\NotFoundException | entailment |
public function up()
{
$driver = Schema::getConnection()->getDriverName();
// Even though we take care of this scenario in the code,
// SQL Server does not allow potential cascading loops,
// so set the default no action and clear out created/modified by another user when deleting a user.
$onDelete = (('sqlsrv' === $driver) ? 'no action' : 'set null');
if (Schema::hasColumn('system_config', 'db_version')) {
Schema::table('system_config', function (Blueprint $t) use ($onDelete) {
// delete the old stuff and create the new config
$t->dropPrimary('system_config_db_version_primary');
$t->dropColumn('db_version');
$t->dropColumn('created_date');
$t->dropColumn('last_modified_date');
// $t->dropColumn('created_by_id');
// $t->dropColumn('last_modified_by_id');
$t->integer('service_id')->unsigned()->primary();
$t->foreign('service_id')->references('id')->on('service')->onDelete('cascade');
$t->integer('invite_email_service_id')->unsigned()->nullable();
$t->foreign('invite_email_service_id')->references('id')->on('service')->onDelete($onDelete);
$t->integer('invite_email_template_id')->unsigned()->nullable();
$t->foreign('invite_email_template_id')->references('id')->on('email_template')->onDelete($onDelete);
$t->integer('password_email_service_id')->unsigned()->nullable();
$t->foreign('password_email_service_id')->references('id')->on('service')->onDelete($onDelete);
$t->integer('password_email_template_id')->unsigned()->nullable();
$t->foreign('password_email_template_id')->references('id')->on('email_template')->onDelete($onDelete);
});
}
} | Run the migrations.
@return void | entailment |
public function boot(Router $router, DispatcherContract $events)
{
$this->baseDir = __DIR__.'/../';
$this->setPublishables();
$this->loadStaticFiles();
$this->registerAliases();
$this->namespace = config('forum.frontend.controllers.namespace');
$this->registerListeners($events);
if (config('forum.frontend.routes')) {
$this->loadRoutes($router);
}
} | Perform post-registration booting of services.
@param Router $router
@param DispatcherContract $events
@return void | entailment |
public function registerListeners(DispatcherContract $events)
{
foreach ($this->listen as $event => $listeners) {
foreach ($listeners as $listener) {
$events->listen($event, $listener);
}
}
} | Register event listeners.
@param DispatcherContract $events
@return void | entailment |
protected function loadRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace,
'middleware' => config('forum.frontend.middleware'),
'as' => config('forum.routing.as'),
'prefix' => config('forum.routing.prefix')
], function ($router) {
Forum::routes($router);
});
} | Load routes.
@param Router $router
@return void | entailment |
public function import()
{
switch ($this->serviceGroupType) {
case ServiceTypeGroups::DATABASE:
$header = $this->getHeader();
if ($this->createDbTableFromHeader($header)) {
try {
$this->importData();
return true;
} catch (\Exception $e) {
$this->revert();
throw $e;
}
}
break;
default:
throw new BadRequestException(
'Importing resource(s) to service type group [' . $this->serviceGroupType . '] ' .
'is not currently supported.'
);
}
} | Imports CSV data
@return bool
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
public function revert()
{
switch ($this->serviceGroupType) {
case ServiceTypeGroups::DATABASE:
if ($this->resourceExists('_schema/' . $this->resource)) {
/** @var \DreamFactory\Core\Contracts\ServiceResponseInterface $rs */
$rs = ServiceManager::handleRequest(
$this->service->getName(),
Verbs::DELETE,
'_schema/' . $this->resource
);
if ($rs->getStatusCode() === HttpStatusCodes::HTTP_OK) {
return true;
}
$content = $rs->getContent();
Log::error(
'Failed to delete table on import failure: ' .
(is_array($content) ? print_r($content, true) : $content)
);
throw new InternalServerErrorException('Failed to delete table on import failure. See log for details.');
}
break;
default:
throw new InternalServerErrorException('An Unexpected error occurred.');
}
} | Reverts partial import after failure
@return bool
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function setService($serviceName)
{
if (empty($serviceName)) {
throw new InternalServerErrorException('No target service name provided for CSV import.');
}
$this->service = ServiceManager::getService($serviceName);
$this->serviceGroupType = $this->service->getServiceTypeInfo()->getGroup();
} | Sets the target service
@param $serviceName
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function getHeader()
{
ini_set('auto_detect_line_endings', true);
if (($handle = fopen($this->file, "r")) !== false) {
$header = fgetcsv($handle, 0, ',');
static::isHeader($header);
return $header;
} else {
throw new InternalServerErrorException('Could not open uploaded CSV file.');
}
} | Fetches CSV header
@return array
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function createDbTableFromHeader($header)
{
if (empty($this->resource)) {
$this->resource = 'import_' . time();
}
if (!$this->resourceExists('_schema/' . $this->resource)) {
$schema = $this->createSchemaFromHeader($header);
$this->createTable($schema);
return true;
} else {
throw new BadRequestException(
'Importing CSV data into existing DB table [' . $this->resource . '] is not supported.'
);
}
} | Creates DB table based on CSV header row
@param $header
@return bool
@throws \DreamFactory\Core\Exceptions\BadRequestException | entailment |
protected function createSchemaFromHeader($header)
{
$schema = [
'name' => $this->resource,
'label' => ucfirst($this->resource),
'description' => 'Table created from CSV data import',
'plural' => ucfirst(str_plural($this->resource)),
'field' => []
];
foreach ($header as $h) {
$schema['field'][] = [
'name' => $h,
'type' => 'string',
'default' => null,
'required' => false,
'allow_null' => true
];
}
return $schema;
} | Creates table schema definition based on CSV header
@param array $header
@return array | entailment |
protected function resourceExists($resource)
{
/** @var \DreamFactory\Core\Contracts\ServiceResponseInterface $rs */
$rs = ServiceManager::handleRequest($this->service->getName(), Verbs::GET, $resource);
if ($rs->getStatusCode() === HttpStatusCodes::HTTP_NOT_FOUND) {
return false;
}
return true;
} | Checks to see if target resource already exists or not
@param $resource
@return bool | entailment |
protected function createTable($schema)
{
/** @var \DreamFactory\Core\Contracts\ServiceResponseInterface $rs */
$rs = ServiceManager::handleRequest(
$this->service->getName(),
Verbs::POST,
'_schema',
[],
[],
ResourcesWrapper::wrapResources($schema)
);
if (in_array($rs->getStatusCode(), [HttpStatusCodes::HTTP_OK, HttpStatusCodes::HTTP_CREATED])) {
return true;
}
$content = $rs->getContent();
Log::error(
'Failed to create table for importing CSV data: ' .
(is_array($content) ? print_r($content, true) : $content)
);
throw new InternalServerErrorException('Failed to create table for importing CSV data. See log for details.');
} | Creates import table
@param $schema
@return bool
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function importData()
{
if (($handle = fopen($this->file, "r")) !== false) {
$header = fgetcsv($handle, 0, ',');
$result = [];
while (false !== ($row = fgetcsv($handle))) {
$new = [];
foreach ($header as $key => $value) {
$new[$value] = array_get($row, $key);
}
$result[] = $new;
if (count($result) === 500) {
$this->insertTableData($result);
}
}
if (count($result) > 0) {
$this->insertTableData($result, false);
}
fclose($handle);
unlink($this->file);
} else {
throw new InternalServerErrorException('Could not open uploaded CSV file.');
}
} | Imports CSV data
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function insertTableData(& $data, $useQueue = true)
{
$job = new DBInsert($this->service->getName(), $this->resource, $data);
if ($useQueue !== true) {
$job->onConnection('sync');
}
dispatch($job);
$data = [];
} | Inserts data into table
@param $data
@param bool $useQueue | entailment |
protected function setImporter($file, $service, $resource)
{
switch ($this->extension) {
case CSV::FILE_EXTENSION:
$this->importer = new CSV($file, $service, $resource);
break;
default:
throw new BadRequestException('Importing file type [' . $this->extension . '] is not supported.');
}
} | @param string $file
@param string $service
@param null|string $resource
@throws \DreamFactory\Core\Exceptions\BadRequestException | entailment |
protected function verifyUploadedFile(array $file)
{
if (is_array($file['error'])) {
throw new BadRequestException("Only a single file is allowed for import.");
}
if (UPLOAD_ERR_OK !== ($error = $file['error'])) {
throw new InternalServerErrorException(
"Failed to upload '" . $file['name'] . "': " . $error
);
}
$this->checkFileExtension($file['name']);
return $file['tmp_name'];
} | Verifies the uploaed file for importing process.
@param array $file
@return string
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function verifyImportFromUrl($url)
{
$this->checkFileExtension($url);
try {
// need to download and extract zip file and move contents to storage
$file = FileUtilities::importUrlFileToTemp($url);
} catch (\Exception $ex) {
throw new InternalServerErrorException("Failed to import file from $url. {$ex->getMessage()}");
}
return $file;
} | Verifies file import from url.
@param $url
@return string
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
protected function checkFileExtension($filename)
{
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($extension, static::FILE_EXTENSION)) {
throw new BadRequestException(
"Unsupported file type. Supported types are " . implode(', ', static::FILE_EXTENSION)
);
}
$this->extension = $extension;
} | @param $filename
@throws \DreamFactory\Core\Exceptions\BadRequestException | entailment |
public function getSchemaExtension($name, ConnectionInterface $conn)
{
if (isset($this->extensions[$name])) {
return call_user_func($this->extensions[$name], $conn);
}
return null;
} | Return the schema extension object.
@param string $name
@param ConnectionInterface $conn
@return DbSchemaInterface | entailment |
public static function create(
$content,
$content_type = null,
$status = ServiceResponseInterface::HTTP_OK,
$headers = []
) {
return new ServiceResponse($content, $content_type, $status, $headers);
} | @param mixed $content
@param string|null $content_type
@param int $status
@param array|null $headers
@return ServiceResponse | entailment |
public static function sendResponse(
ServiceResponseInterface $response,
ServiceRequestInterface $request = null,
$asFile = null,
$resource = 'resource'
) {
$accepts = static::getAcceptedTypes($request);
if (empty($asFile)) {
$asFile = \Request::input('file');
if (true === filter_var($asFile, FILTER_VALIDATE_BOOLEAN)) {
$asFile = $resource . '.json';
}
if (is_string($asFile) && strpos($asFile, '.') !== false) {
$format = strtolower(pathinfo($asFile, PATHINFO_EXTENSION));
if (!empty($format)) {
if ($format === 'csv') {
$accepts = ['text/csv'];
} else {
if ($format === 'xml') {
$accepts = ['application/xml'];
} else {
if ($format === 'json') {
$accepts = ['application/json'];
}
}
}
}
} else {
$asFile = null;
}
}
// If no accepts header supplied or a blank is supplied for
// accept header (clients like bench-rest) then use default response type from config.
if (empty($accepts) || (isset($accepts[0]) && empty($accepts[0]))) {
$accepts[] = config('df.default_response_type');
}
$status = $response->getStatusCode();
$content = $response->getContent();
$format = $response->getDataFormat();
$headers = $response->getHeaders();
if (is_null($content) && is_null($status)) {
// No content and type specified. (File stream already handled by service)
\Log::info('[RESPONSE] File stream');
return null;
}
// In case the status code is not a valid HTTP Status code
if (!in_array($status, HttpStatusCodes::getDefinedConstants())) {
// Do necessary translation here. Default is Internal server error.
$status = HttpStatusCodeInterface::HTTP_INTERNAL_SERVER_ERROR;
}
if ($content instanceof \Exception) {
$status =
($content instanceof RestException) ? $content->getStatusCode()
: ServiceResponseInterface::HTTP_INTERNAL_SERVER_ERROR;
$content = ['error' => self::exceptionToArray($content)];
$format = DataFormats::PHP_ARRAY;
}
// check if the current content type is acceptable for return
$contentType = $response->getContentType();
if (empty($contentType) && is_numeric($format)) {
$contentType = DataFormats::toMimeType($format, null);
}
// see if we match an accepts type, if so, go with it.
$accepts = (array)$accepts;
if (!empty($contentType) && static::acceptedContentType($accepts, $contentType)) {
\Log::info('[RESPONSE]', ['Status Code' => $status, 'Content-Type' => $contentType]);
$headers['Content-Type'] = $contentType;
return DfResponse::create($content, $status, $headers);
}
// we don't have an acceptable content type, see if we can convert the content.
$acceptsAny = false;
$reformatted = false;
foreach ($accepts as $acceptType) {
$acceptFormat = DataFormats::fromMimeType($acceptType, null);
$mimeType = (false !== strpos($acceptType, ';')) ? trim(strstr($acceptType, ';', true)) : $acceptType;
if (is_null($acceptFormat)) {
if ('*/*' === $mimeType) {
$acceptsAny = true;
}
continue;
} else {
$contentType = $mimeType;
}
$reformatted = DataFormatter::reformatData($content, $format, $acceptFormat);
}
$headers['Content-Type'] = $contentType;
if (!empty($asFile)) {
$headers['Content-Disposition'] = 'attachment; filename="' . $asFile . '";';
}
if ($acceptsAny) {
$contentType =
(empty($contentType)) ? DataFormats::toMimeType($format, config('df.default_response_type'))
: $contentType;
$headers['Content-Type'] = $contentType;
\Log::info('[RESPONSE]', ['Status Code' => $status, 'Content-Type' => $contentType]);
return DfResponse::create($content, $status, $headers);
} else {
if (false !== $reformatted) {
\Log::info('[RESPONSE]', ['Status Code' => $status, 'Content-Type' => $contentType]);
return DfResponse::create($reformatted, $status, $headers);
}
}
if ($status >= 400) {
return DfResponse::create($content, $status, $headers);
}
$content = (is_array($content)) ? print_r($content, true) : $content;
return DfResponse::create(
'Content in response can not be resolved to acceptable content type. Original content: ' . $content,
HttpStatusCodes::HTTP_BAD_REQUEST,
$headers
);
} | @param ServiceResponseInterface $response
@param ServiceRequestInterface|null $request
@param null $asFile
@param string $resource
@return \Symfony\Component\HttpFoundation\Response
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
public static function sendScriptResponse(ServiceResponseInterface $response)
{
$content = $response->getContent();
$contentType = $response->getContentType();
$format = $response->getDataFormat();
$headers = $response->getHeaders();
$status = $response->getStatusCode();
// In case the status code is not a valid HTTP Status code
if (!in_array($status, HttpStatusCodes::getDefinedConstants())) {
// Do necessary translation here. Default is Internal server error.
$status = HttpStatusCodeInterface::HTTP_INTERNAL_SERVER_ERROR;
}
if ($content instanceof \Exception) {
$status =
($content instanceof RestException) ? $content->getStatusCode()
: ServiceResponseInterface::HTTP_INTERNAL_SERVER_ERROR;
$content = ['error' => self::exceptionToArray($content)];
$format = DataFormats::PHP_ARRAY;
}
return [
'status_code' => $status,
'content' => $content,
'content_type' => $contentType,
'format' => $format,
'headers' => $headers
];
} | @param ServiceResponseInterface $response
@return array|mixed|string | entailment |
public static function sendException(\Exception $e, ServiceRequestInterface $request = null)
{
$response = static::exceptionToServiceResponse($e);
return ResponseFactory::sendResponse($response, $request);
} | @param \Exception $e
@param ServiceRequestInterface $request
@return array|mixed|string
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
protected static function makeExceptionContent(\Exception $exception)
{
if ($exception instanceof DfException) {
return ['error' => $exception->toArray()];
}
$errorInfo['code'] = ($exception->getCode()) ?: ServiceResponseInterface::HTTP_INTERNAL_SERVER_ERROR;
$errorInfo['message'] = htmlentities($exception->getMessage());
if (config('app.debug', false)) {
$trace = $exception->getTraceAsString();
$trace = str_replace(["\n", "#"], ["", "<br>"], $trace);
$traceArray = explode("<br>", $trace);
$cleanTrace = [];
foreach ($traceArray as $k => $v) {
if (!empty($v)) {
$cleanTrace[] = $v;
}
}
$errorInfo['trace'] = $cleanTrace;
}
return ['error' => $errorInfo];
} | @param \Exception $exception
@return array | entailment |
public function setMethod($verb)
{
if (!Verbs::contains($verb)) {
throw new \Exception("Invalid method '$verb'");
}
$this->method = $verb;
return $this;
} | @param $verb
@return $this
@throws \Exception | entailment |
public function getParameter($key = null, $default = null)
{
if (is_null($this->parameters)) {
return $default;
}
if (null === $key) {
return $this->parameters;
} else {
return array_get($this->parameters, $key, $default);
}
} | {@inheritdoc} | entailment |
public function getParameterAsBool($key, $default = false)
{
if (is_null($this->parameters)) {
return $default;
}
return array_get_bool($this->parameters, $key, $default);
} | @param mixed $key
@param bool $default
@return mixed | entailment |
public function setContent($data, $type = DataFormats::PHP_ARRAY)
{
$this->content = $data;
switch ($type) {
case DataFormats::PHP_ARRAY:
$this->contentAsArray = $data;
$this->contentType = ''; // this could be null, but may cause issues with clients
break;
case DataFormats::JSON:
$this->contentAsArray = json_decode($data, true);
$this->contentType = DataFormats::toMimeType($type);
break;
}
return $this;
} | @param mixed $data
@param int $type
@return $this
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
public function getPayloadData($key = null, $default = null)
{
if (null === $key) {
return $this->contentAsArray;
} else {
return array_get($this->contentAsArray, $key, $default);
}
} | {@inheritdoc} | entailment |
public function getHeader($key = null, $default = null)
{
if (is_null($this->headers)) {
return $default;
}
if (null === $key) {
return $this->headers;
} else {
return array_get($this->headers, $key, $default);
}
} | {@inheritdoc} | entailment |
public function getApiKey()
{
//Check for API key in request parameters.
$apiKey = $this->getParameter('api_key');
if (empty($apiKey)) {
//Check for API key in request HEADER.
$apiKey = $this->getHeader('X_DREAMFACTORY_API_KEY');
}
return $apiKey;
} | {@inheritdoc} | entailment |
public function input($key = null, $default = null)
{
return $this->getParameter($key, $this->getPayloadData($key, $default));
} | Returns request input.
@param null $key
@param null $default
@return array|string | entailment |
public function up()
{
if (Schema::hasColumn('system_config', 'login_with_user_name')) {
if ('sqlsrv' == DB::connection()->getDriverName()) {
$defaultContraint = DB::selectOne("SELECT OBJECT_NAME([default_object_id]) AS name FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID('[dbo].[system_config]') AND [name] = 'login_with_user_name'");
DB::statement("ALTER TABLE [dbo].[system_config] DROP CONSTRAINT $defaultContraint->name");
}
Schema::table('system_config', function (Blueprint $t) {
$t->dropColumn('login_with_user_name');
});
}
} | Run the migrations.
@return void | entailment |
public function getValueAttribute($value)
{
if (!is_array($value)) {
$decodedValue = json_decode($value, true);
}
//Not a JSON string.
if (!empty($value) && empty($decodedValue)) {
$decodedValue = $value;
}
return $decodedValue;
} | @param $value
@return mixed | entailment |
public function count(): int
{
if (gmp_cmp($this->nb_blocks, PHP_INT_MAX) > 0) {
throw new \RuntimeException('The number of address blocks is bigger than PHP_INT_MAX, use getNbBlocks() instead');
}
return gmp_intval($this->nb_blocks);
} | {@inheritdoc} | entailment |
public function next()
{
$this->position = gmp_add($this->position, 1);
$this->current_block = $this->current_block->plus(1);
} | {@inheritdoc} | entailment |
public function valid(): bool
{
return gmp_cmp($this->position, 0) >= 0 && gmp_cmp($this->position, $this->nb_blocks) < 0;
} | {@inheritdoc} | entailment |
public static function arrayToMask($array)
{
$mask = self::NONE_MASK;
if (empty($array) || !is_array($array)) {
return $mask;
}
foreach ($array as $verb) {
switch ($verb) {
case self::GET:
$mask |= self::GET_MASK;
break;
case self::POST:
$mask |= self::POST_MASK;
break;
case self::PUT:
$mask |= self::PUT_MASK;
break;
case self::PATCH:
$mask |= self::PATCH_MASK;
break;
case self::DELETE:
$mask |= self::DELETE_MASK;
break;
case self::OPTIONS:
$mask |= self::OPTIONS_MASK;
break;
case self::HEAD:
$mask |= self::HEAD_MASK;
break;
case self::COPY:
$mask |= self::COPY_MASK;
break;
case self::TRACE:
$mask |= self::TRACE_MASK;
break;
case self::CONNECT:
$mask |= self::CONNECT_MASK;
break;
}
}
return $mask;
} | @param array $array
@return int | entailment |
public static function maskToArray($mask)
{
$array = array();
if (empty($mask) || !is_int($mask)) {
return $array;
}
if ($mask & self::GET_MASK) {
$array[] = self::GET;
}
if ($mask & self::POST_MASK) {
$array[] = self::POST;
}
if ($mask & self::PUT_MASK) {
$array[] = self::PUT;
}
if ($mask & self::PATCH_MASK) {
$array[] = self::PATCH;
}
if ($mask & self::DELETE_MASK) {
$array[] = self::DELETE;
}
if ($mask & self::OPTIONS_MASK) {
$array[] = self::OPTIONS;
}
if ($mask & self::HEAD_MASK) {
$array[] = self::HEAD;
}
if ($mask & self::COPY_MASK) {
$array[] = self::COPY;
}
if ($mask & self::TRACE_MASK) {
$array[] = self::TRACE;
}
if ($mask & self::CONNECT_MASK) {
$array[] = self::CONNECT;
}
return $array;
} | @param int $mask
@return string | entailment |
public function setSource($source): void
{
if (!\is_string($source)) {
throw new Grid\GridException('Source of `SqlSource` should be string with SQL query');
}
parent::setSource($source);
} | Set SQL source
@param string $source
@return void
@throws \Bluz\Grid\GridException | entailment |
public function process(int $page, int $limit, array $filters = [], array $orders = []): Data
{
// process filters
$filters = $this->applyFilters($filters);
// process orders
$orders = $this->applyOrders($orders);
// prepare query
$type = Proxy\Db::getOption('connect', 'type');
if (strtolower($type) === 'mysql') {
// MySQL
$dataSql = preg_replace('/SELECT\s(.*?)\sFROM/is', 'SELECT SQL_CALC_FOUND_ROWS $1 FROM', $this->source, 1);
$totalSql = 'SELECT FOUND_ROWS()';
} else {
// other
$dataSql = $this->source;
$totalSql = preg_replace('/SELECT\s(.*?)\sFROM/is', 'SELECT COUNT(*) FROM', $this->source, 1);
if (\count($filters)) {
$totalSql .= ' WHERE ' . implode(' AND ', $filters);
}
}
if (\count($filters)) {
$dataSql .= ' WHERE ' . implode(' AND ', $filters);
}
if (\count($orders)) {
$dataSql .= ' ORDER BY ' . implode(', ', $orders);
}
// process pages
$dataSql .= ' LIMIT ' . ($page - 1) * $limit . ', ' . $limit;
// run queries
// use transaction to avoid errors
Proxy\Db::transaction(
function () use (&$data, &$total, $dataSql, $totalSql) {
$data = Proxy\Db::fetchAll($dataSql);
$total = (int)Proxy\Db::fetchOne($totalSql);
}
);
$gridData = new Data($data);
$gridData->setTotal($total);
return $gridData;
} | {@inheritdoc} | entailment |
private function applyFilters(array $settings): array
{
$where = [];
foreach ($settings as $column => $filters) {
foreach ($filters as $filter => $value) {
if ($filter === Grid\Grid::FILTER_LIKE) {
$value = '%' . $value . '%';
}
$where[] = $column . ' ' .
$this->filters[$filter] . ' ' .
Proxy\Db::quote((string)$value);
}
}
return $where;
} | Apply filters to SQL query
@param array[] $settings
@return array | entailment |
private function applyOrders(array $settings): array
{
$orders = [];
// Obtain a list of columns
foreach ($settings as $column => $order) {
$column = Proxy\Db::quoteIdentifier($column);
$orders[] = $column . ' ' . $order;
}
return $orders;
} | Apply order to SQL query
@param array $settings
@return array | entailment |
public function setFoo($arg1, $arg2 = 0)
{
/*
* This is a "Block Comment." The format is the same as
* Docblock Comments except there is only one asterisk at the
* top. phpDocumentor doesn't parse these.
*/
if (is_int($arg1)) {
throw new \Exception("First argument should be string");
}
if ($arg1 == 'good' || $arg1 == 'fair') {
$this->foo = $arg1;
return 1;
} elseif ($arg1 == 'poor' && $arg2 > 1) {
$this->foo = 'poor';
return 2;
} else {
return false;
}
} | Registers the status of foo's universe
Summaries for methods should use 3rd person declarative rather
than 2nd person imperative, beginning with a verb phrase.
Summaries should add description beyond the method's name. The
best method names are "self-documenting", meaning they tell you
basically what the method does. If the summary merely repeats
the method name in sentence form, it is not providing more
information.
Below are the tags commonly used for methods. A `param` tag is
required for each parameter the method has. The `return` tag are
mandatory. The `throws` tag is required if the method uses exceptions.
The remainder should only be used when necessary.
Please use them in the order they appear here. phpDocumentor has
several other tags available, feel free to use them.
The `param` tag contains the data type, then the parameter's
name, followed by a description. By convention, the first noun in
the description is the data type of the parameter. Articles like
"a", "an", and "the" can precede the noun. The descriptions
should start with a phrase. If further description is necessary,
follow with sentences. Having two spaces between the name and the
description aids readability.
When writing a phrase, do not capitalize and do not end with a period.
When writing a phrase followed by a sentence, do not capitalize the
phrase, but end it with a period to distinguish it from the start
of the next sentence
Return tags should contain the data type then a description of
the data returned. The data type can be any of PHP's data types
(int, float, bool, string, array, object, resource, mixed)
and should contain the type primarily returned. For example, if
a method returns an object when things work correctly but false
when an error happens, say 'object' rather than 'mixed'.
Use 'void' if nothing is returned.
Here's an example of how to format examples:
<code>
try {
$dockBlock = new DockBlock();
$dockBlock->setFoo('Bar');
} catch (\Exception $e) {
echo $e->getMessage();
}
</code>
Syntax and order of tags:
@.param [Type] [name] [<description>]
@.return [Type] [<description>]
@.throws [Type] [<description>]
@.see [URI | FQSEN] [<description>]
@.since [version] [<description>]
@.deprecated [version] [<description>]
@param string $arg1 the string to quote
@param int $arg2 an integer of how many problems happened.
Indent to the description's starting point
for long ones.
@return int the integer of the set mode used. FALSE if foo
foo could not be set.
@throws \Exception if first argument is not a string
@see DockBlock::$foo, DockBlock::setFoo()
@since 1.3.0 Added the $arg2
@since 1.2.0
@deprecated 2.0.0 | entailment |
public static function toCamelCase($subject): string
{
$subject = str_replace(['_', '-'], ' ', strtolower($subject));
return str_replace(' ', '', ucwords($subject));
} | Convert string to CamelCase
@param string $subject
@return string | entailment |
public function save()
{
$this->beforeSave();
/**
* If the primary key is empty, this is an INSERT of a new row.
* Otherwise check primary key updated or not, if it changed - INSERT
* otherwise UPDATE
*/
if (!\count(\array_filter($this->getPrimaryKey()))) {
$result = $this->doInsert();
} elseif (\count(\array_diff_assoc($this->getPrimaryKey(), $this->clean))) {
$result = $this->doInsert();
} else {
$result = $this->doUpdate();
}
$this->afterSave();
return $result;
} | Saves the properties to the database.
This performs an intelligent insert/update, and reloads the
properties with fresh data from the table on success.
@return mixed The primary key value(s), as an associative array if the
key is compound, or a scalar if the key is single-column
@throws DbException
@throws InvalidPrimaryKeyException
@throws TableNotFoundException | entailment |
protected function doInsert()
{
/**
* Run pre-INSERT logic
*/
$this->beforeInsert();
$data = $this->toArray();
/**
* Execute validator logic
* Can throw ValidatorException
*/
$this->assert($data);
$table = $this->getTable();
/**
* Execute the INSERT (this may throw an exception)
*/
$primaryKey = $table::insert($data);
/**
* Normalize the result to an array indexed by primary key column(s)
*/
$tempPrimaryKey = $table->getPrimaryKey();
$newPrimaryKey = [current($tempPrimaryKey) => $primaryKey];
/**
* Save the new primary key value in object. The primary key may have
* been generated by a sequence or auto-increment mechanism, and this
* merge should be done before the afterInsert() method is run, so the
* new values are available for logging, etc.
*/
$this->setFromArray($newPrimaryKey);
/**
* Run post-INSERT logic
*/
$this->afterInsert();
/**
* Update the "clean" to reflect that the data has been inserted.
*/
$this->clean = $this->toArray();
return $newPrimaryKey;
} | Insert row to Db
@return mixed The primary key value(s), as an associative array if the
key is compound, or a scalar if the key is single-column
@throws InvalidPrimaryKeyException
@throws TableNotFoundException | entailment |
protected function doUpdate(): int
{
/**
* Run pre-UPDATE logic
*/
$this->beforeUpdate();
$data = $this->toArray();
/**
* Execute validator logic
* Can throw ValidatorException
*/
$this->assert($data);
$primaryKey = $this->getPrimaryKey();
/**
* Compare the data to the modified fields array to discover
* which columns have been changed.
*/
$diffData = array_diff_assoc($data, $this->clean);
$table = $this->getTable();
$diffData = $table::filterColumns($diffData);
/**
* Execute the UPDATE (this may throw an exception)
* Do this only if data values were changed.
* Use the $diffData variable, so the UPDATE statement
* includes SET terms only for data values that changed.
*/
$result = 0;
if (\count($diffData) > 0) {
$result = $table::update($diffData, $primaryKey);
}
/**
* Run post-UPDATE logic. Do this before the _refresh()
* so the _afterUpdate() function can tell the difference
* between changed data and clean (pre-changed) data.
*/
$this->afterUpdate();
/**
* Refresh the data just in case triggers in the RDBMS changed
* any columns. Also this resets the "clean".
*/
$this->clean = $this->toArray();
return $result;
} | Update row
@return integer The number of rows updated
@throws InvalidPrimaryKeyException
@throws TableNotFoundException | entailment |
public function delete(): bool
{
/**
* Execute pre-DELETE logic
*/
$this->beforeDelete();
$primaryKey = $this->getPrimaryKey();
/**
* Execute the DELETE (this may throw an exception)
*/
$table = $this->getTable();
$result = $table::delete($primaryKey);
/**
* Execute post-DELETE logic
*/
$this->afterDelete();
/**
* Reset all fields to null to indicate that the row is not there
*/
$this->resetArray();
return $result > 0;
} | Delete existing row
@return bool Removed or not
@throws InvalidPrimaryKeyException
@throws TableNotFoundException | entailment |
protected function getPrimaryKey(): array
{
$primary = array_flip($this->getTable()->getPrimaryKey());
return array_intersect_key($this->toArray(), $primary);
} | Retrieves an associative array of primary keys, if it exists
@return array
@throws InvalidPrimaryKeyException
@throws TableNotFoundException | entailment |
public function execute($sequence = null)
{
$result = Db::query($this->getSql(), $this->params, $this->types);
if ($result) {
return Db::handler()->lastInsertId($sequence);
}
return $result;
} | {@inheritdoc}
@param null $sequence
@return integer|string|array | entailment |
public function process(): void
{
/** @var \Closure|object $closure */
$closure = include $this->file;
if (!\is_callable($closure)) {
throw new ComponentException("There is no callable structure in file `{$this->file}`");
}
$reflection = new \ReflectionFunction($closure);
// check and normalize params by doc comment
$docComment = $reflection->getDocComment();
// get all options by one regular expression
if (preg_match_all('/\s*\*\s*\@([a-z0-9-_]+)\s+(.*).*\s+/i', $docComment, $matches)) {
foreach ($matches[1] as $i => $key) {
$this->setOption($key, trim($matches[2][$i]));
}
}
// init routes
$this->initRoute();
// get params and convert it to simple array
$reflectionParams = $reflection->getParameters();
// setup params and optional params
foreach ($reflectionParams as $param) {
$name = $param->getName();
// if some function params is missed in description
if (!isset($this->params[$name])) {
$this->params[$name] = null;
}
if ($param->isOptional()) {
$this->values[$name] = $param->getDefaultValue();
}
}
} | Process to get reflection from file
@return void
@throws ComponentException
@throws \ReflectionException | entailment |
public function params($requestParams): array
{
// apply type and default value for request params
$params = [];
foreach ($this->params as $param => $type) {
if (isset($requestParams[$param])) {
switch ($type) {
case 'bool':
case 'boolean':
$params[] = (bool)$requestParams[$param];
break;
case 'int':
case 'integer':
$params[] = (int)$requestParams[$param];
break;
case 'float':
$params[] = (float)$requestParams[$param];
break;
case 'string':
$params[] = (string)$requestParams[$param];
break;
case 'array':
$params[] = (array)$requestParams[$param];
break;
default:
$params[] = $requestParams[$param];
break;
}
} elseif (isset($this->values[$param])) {
$params[] = $this->values[$param];
} else {
$params[] = null;
}
}
return $params;
} | Process request params
- type conversion
- set default value
@param array $requestParams
@return array | entailment |
protected function prepareCache($cache): int
{
$num = (int)$cache;
$time = 'min';
if ($pos = strpos($cache, ' ')) {
$time = substr($cache, $pos);
}
switch ($time) {
case 'day':
case 'days':
return $num * 86400;
case 'hour':
case 'hours':
return $num * 3600;
case 'min':
default:
return $num * 60;
}
} | Prepare Cache
@param string $cache
@return integer | entailment |
public function setAccept($accept): void
{
// allow accept map
$acceptMap = [
'ANY' => Request::TYPE_ANY,
'HTML' => Request::TYPE_HTML,
'JSON' => Request::TYPE_JSON
];
$accept = strtoupper($accept);
if (isset($acceptMap[$accept])) {
$this->accept[] = $acceptMap[$accept];
}
} | Set accepted types
@param string $accept
@return void | entailment |
public function setParam($param): void
{
// prepare params data
// setup param types
if (strpos($param, '$') === false) {
return;
}
[$type, $key] = preg_split('/[ $]+/', $param);
$this->params[$key] = trim($type);
} | Set param types
@param string $param
@return void | entailment |
protected function initRoute(): void
{
foreach ($this->route as $route => &$pattern) {
$pattern = $this->prepareRoutePattern($route);
}
} | Init Route
@return void | entailment |
protected function prepareRoutePattern($route): string
{
$pattern = str_replace('/', '\/', $route);
foreach ($this->getParams() as $param => $type) {
switch ($type) {
case 'int':
case 'integer':
$pattern = str_replace("{\$$param}", "(?P<$param>[0-9]+)", $pattern);
break;
case 'float':
$pattern = str_replace("{\$$param}", "(?P<$param>[0-9.,]+)", $pattern);
break;
case 'string':
case 'module':
case 'controller':
$pattern = str_replace(
"{\$$param}",
"(?P<$param>[a-zA-Z0-9-_.]+)",
$pattern
);
break;
}
}
return '/^' . $pattern . '/i';
} | Prepare Route pattern
@param string $route
@return string | entailment |
public static function getHeader($header, $default = null)
{
$header = strtolower($header);
$headers = self::getInstance()->getHeaders();
$headers = array_change_key_case($headers, CASE_LOWER);
if (array_key_exists($header, $headers)) {
$value = \is_array($headers[$header]) ? implode(', ', $headers[$header]) : $headers[$header];
return $value;
}
return $default;
} | Search for a header value
@param string $header
@param mixed $default
@return string | entailment |
public static function getParams(): array
{
$body = (array)self::getInstance()->getParsedBody();
$query = (array)self::getInstance()->getQueryParams();
return array_merge([], $body, $query);
} | Get all params from GET and POST or PUT
@return array | entailment |
public static function getClientIp($checkProxy = true)
{
$result = null;
if ($checkProxy) {
$result = self::getServer('HTTP_CLIENT_IP') ?? self::getServer('HTTP_X_FORWARDED_FOR') ?? null;
}
return $result ?? self::getServer('REMOTE_ADDR');
} | Get the client's IP address
@param bool $checkProxy
@return string | entailment |
public static function getAccept(): array
{
if (!self::$accept) {
// get header from request
self::$accept = self::parseAcceptHeader(self::getHeader('Accept'));
}
return self::$accept;
} | Get Accept MIME Type
@return array | entailment |
public static function getAcceptLanguage(): array
{
if (!self::$language) {
// get header from request
self::$language = self::parseAcceptHeader(self::getHeader('Accept-Language'));
}
return self::$language;
} | Get Accept MIME Type
@return array | entailment |
private static function parseAcceptHeader($header): array
{
// empty array
$accept = [];
// check empty
if (!$header || $header === '') {
return $accept;
}
// make array from header
$values = explode(',', $header);
$values = array_map('trim', $values);
foreach ($values as $a) {
// the default quality is 1.
$q = 1;
// check if there is a different quality
if (strpos($a, ';q=') || strpos($a, '; q=')) {
// divide "mime/type;q=X" into two parts: "mime/type" i "X"
[$a, $q] = preg_split('/;([ ]?)q=/', $a);
}
// remove other extension
if (strpos($a, ';')) {
$a = substr($a, 0, strpos($a, ';'));
}
// mime-type $a is accepted with the quality $q
// WARNING: $q == 0 means, that isn’t supported!
$accept[$a] = (float)$q;
}
arsort($accept);
return $accept;
} | parseAcceptHeader
@param string $header
@return array | entailment |
public static function checkAccept(array $allowTypes = [])
{
$accept = self::getAccept();
// if no parameter was passed, just return first mime type from parsed data
if (empty($allowTypes)) {
return current(array_keys($accept));
}
$allowTypes = array_map('strtolower', $allowTypes);
// let’s check our supported types:
foreach ($accept as $mime => $quality) {
if ($quality && \in_array($mime, $allowTypes, true)) {
return $mime;
}
}
// no mime-type found
return false;
} | Check Accept header
@param array $allowTypes
@return string|false | entailment |
public function addHelperPath(string $path): void
{
$class = static::class;
$realPath = realpath($path);
if (false === $realPath) {
throw new CommonException("Invalid Helper path `$path` for class `$class`");
}
// create store of helpers
if (!isset(static::$helpersPath[$class])) {
static::$helpersPath[$class] = [];
}
if (!\in_array($realPath, static::$helpersPath[$class], true)) {
static::$helpersPath[$class][] = $realPath;
}
} | Add helper path
@param string $path
@return void
@throws CommonException | entailment |
private function loadHelper(string $name): void
{
$class = static::class;
// Somebody forgot to call `addHelperPath`
if (!isset(static::$helpersPath[$class])) {
throw new CommonException("Helper path not found for class `$class`");
}
// Try to find helper file
foreach (static::$helpersPath[$class] as $path) {
if ($helperPath = realpath($path . '/' . ucfirst($name) . '.php')) {
$this->addHelper($name, $helperPath);
return;
}
}
throw new CommonException("Helper `$name` not found for class `$class`");
} | Call helper
@param string $name
@return void
@throws CommonException | entailment |
private function addHelper(string $name, string $path): void
{
$class = static::class;
// create store of helpers for this class
if (!isset(static::$helpers[$class])) {
static::$helpers[$class] = [];
}
$helper = include $path;
if (\is_callable($helper)) {
static::$helpers[$class][$name] = $helper;
} else {
throw new CommonException("Helper `$name` not found in file `$path`");
}
} | Add helper callable
@param string $name
@param string $path
@return void
@throws CommonException | entailment |
public function offsetSet($offset, $value): void
{
if (null === $offset) {
throw new \InvalidArgumentException('Class `Common\Container\ArrayAccess` support only associative arrays');
}
$this->doSetContainer($offset, $value);
} | Offset to set
@param mixed $offset
@param mixed $value
@throws \InvalidArgumentException | entailment |
public function setIdentity(IdentityInterface $identity): void
{
// save identity to Auth
$this->identity = $identity;
// regenerate session
if (PHP_SAPI !== 'cli') {
Session::regenerateId();
}
// save identity to session
Session::set('auth:identity', $identity);
// save user agent to session
Session::set('auth:agent', Request::getServer('HTTP_USER_AGENT'));
} | Setup identity
@param IdentityInterface $identity
@return void | entailment |
public function getIdentity(): ?IdentityInterface
{
if (!$this->identity) {
// check user agent
if (Session::get('auth:agent') === Request::getServer('HTTP_USER_AGENT')) {
$this->identity = Session::get('auth:identity');
} else {
$this->clearIdentity();
}
}
return $this->identity;
} | Return identity if user agent is correct
@return IdentityInterface|null | entailment |
public function validate($input): bool
{
if (\is_array($this->haystack)) {
return \in_array($input, $this->haystack, false);
}
if (!\is_string($this->haystack)) {
return false;
}
if (empty($input)) {
return false;
}
$enc = mb_detect_encoding($input);
return mb_stripos($this->haystack, $input, 0, $enc) !== false;
} | Check input data
@param string $input
@return bool | entailment |
public function getDescription(): string
{
if (\is_array($this->haystack)) {
$haystack = implode(', ', $this->haystack);
} else {
$haystack = $this->haystack;
}
return __('must be in "%s"', $haystack);
} | Get error template
@return string | entailment |
public function processRequest(): void
{
$this->module = Request::getModule();
$this->controller = Request::getController();
$page = (int)Request::getParam($this->prefix . 'page', 1);
$this->setPage($page);
$limit = (int)Request::getParam($this->prefix . 'limit', $this->limit);
$this->setLimit($limit);
foreach ($this->allowOrders as $column) {
$alias = $this->applyAlias($column);
$order = Request::getParam($this->prefix . 'order-' . $alias);
if (is_array($order)) {
$order = current($order);
}
if (null !== $order) {
$this->addOrder($column, $order);
}
}
foreach ($this->allowFilters as $column) {
$alias = $this->applyAlias($column);
$filters = (array)Request::getParam($this->prefix . 'filter-' . $alias, []);
foreach ($filters as $filter) {
$filter = trim($filter, ' _-');
if (strpos($filter, '-')) {
/**
* Example of filters
* - http://domain.com/users/grid/users-filter-roleId/gt-2 - roleId greater than 2
* - http://domain.com/users/grid/users-filter-roleId/gt-1_lt-4 - 1 < roleId < 4
* - http://domain.com/users/grid/users-filter-login/eq-admin - login == admin
* - http://domain.com/users/grid/users-filter-login/like-adm - login LIKE `adm`
* - http://domain.com/users/grid/users-filter-login/like-od- - login LIKE `od-`
*/
$filters = explode('_', $filter);
foreach ($filters as $rawFilter) {
[$filterName, $filterValue] = explode('-', $rawFilter, 2);
$this->addFilter($column, $filterName, urldecode($filterValue));
}
} else {
/**
* Example of filters
* - http://domain.com/users/grid/users-filter-roleId/2
* - http://domain.com/users/grid/users-filter-login/admin
*/
$this->addFilter($column, self::FILTER_EQ, $filter);
}
}
}
} | Process request
Example of request url
- http://domain.com/pages/grid/
- http://domain.com/pages/grid/page/2/
- http://domain.com/pages/grid/page/2/order-alias/desc/
- http://domain.com/pages/grid/page/2/order-created/desc/order-alias/asc/
with prefix for support more than one grid on page
- http://domain.com/users/grid/users-page/2/users-order-created/desc/
- http://domain.com/users/grid/users-page/2/users-filter-status/active/
hash support
- http://domain.com/pages/grid/#/page/2/order-created/desc/order-alias/asc/
@return void
@throws GridException | entailment |
public function processSource(): void
{
if (null === $this->adapter) {
throw new GridException('Grid Adapter is not initiated, please update method `init()` and try again');
}
try {
$this->data = $this->getAdapter()->process(
$this->getPage(),
$this->getLimit(),
$this->getFilters(),
$this->getOrders()
);
} catch (\Exception $e) {
throw new GridException('Grid Adapter can\'t process request: '. $e->getMessage());
}
} | Process source
@return void
@throws GridException | entailment |
public function getParams(array $rewrite = []): array
{
$params = $this->params;
// change page to first for each new grid (with new filters or orders, or other stuff)
$page = $rewrite['page'] ?? 1;
if ($page > 1) {
$params[$this->prefix . 'page'] = $page;
}
// change limit
$limit = $rewrite['limit'] ?? $this->getLimit();
if ($limit !== $this->defaultLimit) {
$params[$this->prefix . 'limit'] = $limit;
}
// change orders
$orders = $rewrite['orders'] ?? $this->getOrders();
foreach ($orders as $column => $order) {
$column = $this->applyAlias($column);
$params[$this->prefix . 'order-' . $column] = $order;
}
// change filters
$filters = $rewrite['filters'] ?? $this->getFilters();
foreach ($filters as $column => $columnFilters) {
/** @var array $columnFilters */
$column = $this->applyAlias($column);
if (\count($columnFilters) === 1 && isset($columnFilters[self::FILTER_EQ])) {
$params[$this->prefix . 'filter-' . $column] = $columnFilters[self::FILTER_EQ];
continue;
}
$columnFilter = [];
foreach ($columnFilters as $filterName => $filterValue) {
$columnFilter[] = $filterName . '-' . $filterValue;
}
$params[$this->prefix . 'filter-' . $column] = implode('_', $columnFilter);
}
return $params;
} | Return params prepared for url builder
@param array $rewrite
@return array | entailment |
public function getUrl($params): string
{
// prepare params
$params = $this->getParams($params);
// retrieve URL
return Router::getUrl(
$this->getModule(),
$this->getController(),
$params
);
} | Get Url
@param array $params
@return string | entailment |
public function setAllowOrders(array $orders = []): void
{
$this->allowOrders = [];
foreach ($orders as $column) {
$this->addAllowOrder($column);
}
} | Set allow orders
@param string[] $orders
@return void | entailment |
public function addOrder($column, $order = self::ORDER_ASC): void
{
if (!$this->checkOrderColumn($column)) {
throw new GridException("Order for column `$column` is not allowed");
}
if (!$this->checkOrderName($order)) {
throw new GridException("Order name for column `$column` is incorrect");
}
$this->orders[$column] = $order;
} | Add order rule
@param string $column
@param string $order
@return void
@throws GridException | entailment |
public function addOrders(array $orders): void
{
foreach ($orders as $column => $order) {
$this->addOrder($column, $order);
}
} | Add order rules
@param array $orders
@return void
@throws GridException | entailment |
public function setOrder($column, $order = self::ORDER_ASC): void
{
$this->orders = [];
$this->addOrder($column, $order);
} | Set order
@param string $column
@param string $order ASC or DESC
@return void
@throws GridException | entailment |
public function setAllowFilters(array $filters = []): void
{
$this->allowFilters = [];
foreach ($filters as $column) {
$this->addAllowFilter($column);
}
} | Set allowed filters
@param string[] $filters
@return void | entailment |
protected function checkFilterColumn($column): bool
{
return array_key_exists($column, $this->getAllowFilters()) ||
\in_array($column, $this->getAllowFilters(), false);
} | Check filter column
@param string $column
@return bool | entailment |
public function addFilter($column, $filter, $value): void
{
if (!$this->checkFilterColumn($column)) {
throw new GridException("Filter for column `$column` is not allowed");
}
if (!$this->checkFilterName($filter)) {
throw new GridException('Filter name is incorrect');
}
if (!isset($this->filters[$column])) {
$this->filters[$column] = [];
}
$this->filters[$column][$filter] = $value;
} | Add filter
@param string $column name
@param string $filter
@param string $value
@return void
@throws GridException | entailment |
public function getFilter($column, $filter = null)
{
if (null === $filter) {
return $this->filters[$column] ?? null;
}
return $this->filters[$column][$filter] ?? null;
} | Get filter
@param string $column
@param string $filter
@return mixed | entailment |
public function setDefaultLimit(int $limit): void
{
if ($limit < 1) {
throw new GridException('Wrong default limit value, should be greater than zero');
}
$this->setLimit($limit);
$this->defaultLimit = $limit;
} | Set default limit
@param integer $limit
@return void
@throws GridException | entailment |
public function setDefaultOrder($column, $order = self::ORDER_ASC): void
{
$this->defaultOrder = [$column => $order];
} | Set default order
@param string $column
@param string $order ASC or DESC
@return void | entailment |
public function validate($input): bool
{
if (\is_string($input)) {
$input = trim($input);
}
return (false !== $input) && (null !== $input) && ('' !== $input);
} | Check input data
@param mixed $input
@return bool | entailment |
public function setName($name): void
{
if ($this->sessionExists()) {
throw new SessionException(
'Cannot set session name after a session has already started'
);
}
if (!preg_match('/^[a-zA-Z0-9]+$/', $name)) {
throw new SessionException(
'Name provided contains invalid characters; must be alphanumeric only'
);
}
$this->name = $name;
session_name($name);
} | Attempt to set the session name
If the session has already been started, or if the name provided fails
validation, an exception will be raised.
@param string $name
@throws SessionException
@return void | entailment |
public function getName(): string
{
if (null === $this->name) {
// If we're grabbing via session_name(), we don't need our
// validation routine; additionally, calling setName() after
// session_start() can lead to issues, and often we just need the name
// in order to do things such as setting cookies.
$this->name = session_name();
}
return $this->name;
} | Get session name
Proxies to {@link session_name()}.
@return string | entailment |
public function regenerateId($deleteOldSession = true): bool
{
if ($this->sessionExists() && session_id() !== '') {
return session_regenerate_id((bool)$deleteOldSession);
}
return false;
} | Regenerate id
Regenerate the session ID, using session save handler's
native ID generation Can safely be called in the middle of a session.
@param bool $deleteOldSession
@return bool | entailment |
public function destroy(): void
{
if (!$this->cookieExists() || !$this->sessionExists()) {
return;
}
session_destroy();
// send expire cookies
$this->expireSessionCookie();
// clear session data
unset($_SESSION[$this->getNamespace()]);
} | Destroy/end a session
@return void | entailment |
protected function initAdapter(): bool
{
if (null === $this->adapter || 'files' === $this->adapter) {
// try to apply settings
if ($settings = $this->getOption('settings', 'files')) {
$this->setSavePath($settings['save_path']);
}
return true;
}
if (\is_string($this->adapter)) {
$adapterClass = '\\Bluz\\Session\\Adapter\\' . ucfirst($this->adapter);
if (!class_exists($adapterClass) || !is_subclass_of($adapterClass, \SessionHandlerInterface::class)) {
throw new ComponentException("Class for session adapter `{$this->adapter}` not found");
}
$settings = $this->getOption('settings', $this->adapter) ?: [];
$this->adapter = new $adapterClass($settings);
return session_set_save_handler($this->adapter);
}
return true;
} | Register Save Handler with ext/session
Since ext/session is coupled to this particular session manager
register the save handler with ext/session.
@return bool
@throws ComponentException | entailment |
public function expireSessionCookie(): void
{
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(
$this->getName(),
'',
$_SERVER['REQUEST_TIME'] - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
} | Expire the session cookie
Sends a session cookie with no value, and with an expiry in the past.
@return void | entailment |
protected function setSavePath($savePath): void
{
if (!is_dir($savePath)
|| !is_writable($savePath)
) {
throw new ComponentException('Session path is not writable');
}
session_save_path($savePath);
} | Set session save path
@param string $savePath
@return void
@throws ComponentException | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.