sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function set($key, $value): void
{
$this->start();
// check storage
if (!isset($_SESSION[$this->getNamespace()])) {
$_SESSION[$this->getNamespace()] = [];
}
$_SESSION[$this->namespace][$key] = $value;
} | Set key/value pair
@param string $key
@param mixed $value
@return void
@throws ComponentException | entailment |
public function contains($key): bool
{
if ($this->cookieExists()) {
$this->start();
} elseif (!$this->sessionExists()) {
return false;
}
return isset($_SESSION[$this->namespace][$key]);
} | Isset
@param string $key
@return bool
@throws ComponentException | entailment |
public function readOne($primary)
{
if (!$primary) {
return $this->getTable()::create();
}
$row = $this->getTable()::findRow($primary);
if (!$row) {
throw new NotFoundException('Record not found');
}
$row = $this->filterRow($row);
r... | Get record from Db or create new object
@param mixed $primary
@return Db\RowInterface
@throws TableNotFoundException
@throws NotFoundException | entailment |
public function readSet($offset = 0, $limit = 10, $params = [])
{
$select = $this->getTable()::select();
// select only required fields
if (\count($this->getFields())) {
$fields = $this->getFields();
$name = $this->getTable()->getName();
$fields = array_m... | Get set of records
@param int $offset
@param int $limit
@param array $params
@return array[Row[], integer]
@throws TableNotFoundException | entailment |
public function createOne($data)
{
$row = $this->getTable()::create();
$data = $this->filterData($data);
$row->setFromArray($data);
return $row->save();
} | Create item
@param array $data
@return mixed
@throws TableNotFoundException | entailment |
public function updateOne($primary, $data)
{
$row = $this->getTable()::findRow($primary);
if (!$row) {
throw new NotFoundException('Record not found');
}
$data = $this->filterData($data);
$row->setFromArray($data);
return $row->save();
} | Update item
@param mixed $primary
@param array $data
@return integer
@throws NotFoundException
@throws TableNotFoundException | entailment |
public function deleteOne($primary)
{
$row = $this->getTable()::findRow($primary);
if (!$row) {
throw new NotFoundException('Record not found');
}
return $row->delete();
} | Delete item
@param mixed $primary
@return integer
@throws NotFoundException
@throws TableNotFoundException | entailment |
public function run(): Data
{
if (!$this->loadData()) {
$this->process();
$this->saveData();
}
return $this->data;
} | Run controller logic
@return Data
@throws ComponentException
@throws ControllerException
@throws \ReflectionException | entailment |
protected function process(): Data
{
// initial variables for use inside controller
$module = $this->module;
$controller = $this->controller;
$params = $this->params;
/**
* @var \closure $controllerClosure
*/
$controllerClosure = include $this->getF... | Controller run
@return Data
@throws ComponentException
@throws ControllerException
@throws \ReflectionException | entailment |
protected function findFile(): void
{
$path = Application::getInstance()->getPath();
$file = "$path/modules/{$this->module}/controllers/{$this->controller}.php";
if (!file_exists($file)) {
throw new ControllerException("Controller file not found '{$this->module}/{$this->controll... | Setup controller file
@return void
@throws ControllerException
@throws \ReflectionException | entailment |
protected function initMeta(): void
{
// cache for reflection data
$cacheKey = "meta.{$this->module}.{$this->controller}";
if (!$meta = Cache::get($cacheKey)) {
$meta = new Meta($this->getFile());
$meta->process();
Cache::set(
$cacheKey,
... | Retrieve reflection for anonymous function
@return void
@throws ComponentException
@throws ControllerException
@throws \ReflectionException | entailment |
private function loadData(): bool
{
$cacheTime = $this->getMeta()->getCache();
if ($cacheTime && $cached = Cache::get($this->key)) {
$this->data = $cached;
return true;
}
return false;
} | Load Data from cache
@return bool
@throws ComponentException
@throws ControllerException
@throws \ReflectionException | entailment |
private function saveData(): bool
{
if ($cacheTime = $this->getMeta()->getCache()) {
return Cache::set(
$this->key,
$this->getData(),
$cacheTime,
['system', 'data']
);
}
return false;
} | Save Data to cache
@return bool
@throws ComponentException
@throws ControllerException
@throws \ReflectionException | entailment |
public function addMap($method, $module, $controller): Link
{
return $this->map[strtoupper($method)] = new Link($module, $controller);
} | Add mapping data
@param string $method
@param string $module
@param string $controller
@return Link | entailment |
public function head($module, $controller): Link
{
return $this->addMap(RequestMethod::HEAD, $module, $controller);
} | Add mapping for HEAD method
@param string $module
@param string $controller
@return Link | entailment |
public function get(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::GET, $module, $controller);
} | Add mapping for GET method
@param string $module
@param string $controller
@return Link | entailment |
public function post(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::POST, $module, $controller);
} | Add mapping for POST method
@param string $module
@param string $controller
@return Link | entailment |
public function patch(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::PATCH, $module, $controller);
} | Add mapping for PATCH method
@param string $module
@param string $controller
@return Link | entailment |
public function put(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::PUT, $module, $controller);
} | Add mapping for PUT method
@param string $module
@param string $controller
@return Link | entailment |
public function delete(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::DELETE, $module, $controller);
} | Add mapping for DELETE method
@param string $module
@param string $controller
@return Link | entailment |
public function options(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::OPTIONS, $module, $controller);
} | Add mapping for OPTIONS method
@param string $module
@param string $controller
@return Link | entailment |
protected function prepareRequest(): void
{
// HTTP method
$method = Request::getMethod();
$this->method = strtoupper($method);
// get path
// %module% / %controller% / %id% / %relation% / %id%
$path = Router::getCleanUri();
$this->params = explode('/', rtri... | Prepare request for processing
@throws ControllerException | entailment |
private static function initInstance(): Instance
{
$instance = new Instance();
if ($data = Config::get('registry')) {
$instance->setFromArray($data);
}
return $instance;
} | Init instance
@return Instance | entailment |
public function setRelation(Row $row): void
{
$modelName = $row->getTable()->getModel();
$this->relations[$modelName] = [$row];
} | Set relation
@param Row $row
@return void
@throws TableNotFoundException | entailment |
public function getRelation($modelName): ?RowInterface
{
$relations = $this->getRelations($modelName);
return empty($relations) ? null : current($relations);
} | Get relation by model name
@param string $modelName
@return RowInterface
@throws RelationNotFoundException
@throws TableNotFoundException | entailment |
public function getRelations($modelName): array
{
if (!isset($this->relations[$modelName])) {
$this->relations[$modelName] = Relations::findRelation($this, $modelName);
}
return $this->relations[$modelName];
} | Get relations by model name
@param string $modelName
@return RowInterface[]
@throws RelationNotFoundException
@throws TableNotFoundException | entailment |
public function addParts($parts): CompositeBuilder
{
foreach ($parts as $part) {
$this->addPart($part);
}
return $this;
} | Adds a set of expressions to composite expression
@param array $parts
@return CompositeBuilder | entailment |
public function addPart($part): CompositeBuilder
{
if (!empty($part) || ($part instanceof self && $part->count() > 0)) {
$this->parts[] = $part;
}
return $this;
} | Adds an expression to composite expression
@param mixed $part
@return CompositeBuilder | entailment |
private function prepareRouterData()
{
$routers = [];
$reverse = [];
$path = Application::getInstance()->getPath() . '/modules/*/controllers/*.php';
foreach (new \GlobIterator($path) as $file) {
/* @var \SplFileInfo $file */
$module = $file->getPathInfo()->get... | Initial routers data from controllers
@return array[]
@throws \Bluz\Common\Exception\CommonException
@throws \Bluz\Common\Exception\ComponentException
@throws \Bluz\Controller\ControllerException
@throws \ReflectionException | entailment |
public function setParam($key, $value): void
{
$key = (string)$key;
if ((null === $value) && isset($this->params[$key])) {
unset($this->params[$key]);
} elseif (null !== $value) {
$this->params[$key] = $value;
}
} | Set an action parameter
A $value of null will unset the $key if it exists
@param string $key
@param mixed $value
@return void | entailment |
public function getCleanUri(): string
{
if ($this->cleanUri === null) {
$uri = Request::getUri()->getPath();
if ($this->getBaseUrl() && strpos($uri, $this->getBaseUrl()) === 0) {
$uri = substr($uri, \strlen($this->getBaseUrl()));
}
$this->clean... | Get the request URI without baseUrl
@return string | entailment |
public function getUrl(
$module = self::DEFAULT_MODULE,
$controller = self::DEFAULT_CONTROLLER,
array $params = []
): string {
$module = $module ?? Request::getModule();
$controller = $controller ?? Request::getController();
if (isset($this->reverse[$module], $this->... | Build URL to controller
@param string $module
@param string $controller
@param array $params
@return string | entailment |
public function getFullUrl(
$module = self::DEFAULT_MODULE,
$controller = self::DEFAULT_CONTROLLER,
array $params = []
): string {
$scheme = Request::getUri()->getScheme() . '://';
$host = Request::getUri()->getHost();
$port = Request::getUri()->getPort();
if ... | Build full URL to controller
@param string $module
@param string $controller
@param array $params
@return string | entailment |
protected function urlCustom($module, $controller, $params): string
{
$url = $this->reverse[$module][$controller]['route'];
$getParams = [];
foreach ($params as $key => $value) {
// sub-array as GET params
if (\is_array($value)) {
$getParams[$key] = $... | Build URL by custom route
@param string $module
@param string $controller
@param array $params
@return string | entailment |
protected function urlRoute($module, $controller, $params): string
{
$url = $this->getBaseUrl();
if (empty($params) && $controller === self::DEFAULT_CONTROLLER) {
if ($module === self::DEFAULT_MODULE) {
return $url;
}
return $url . $module;
... | Build URL by default route
@param string $module
@param string $controller
@param array $params
@return string | entailment |
public function process()
{
$this->processDefault() || // try to process default router (homepage)
$this->processCustom() || // or custom routers
$this->processRoute(); // or default router schema
$this->resetRequest();
return $this;
} | Process routing
@return \Bluz\Router\Router | entailment |
protected function processCustom(): bool
{
$uri = '/' . $this->getCleanUri();
foreach ($this->routers as $router) {
if (preg_match($router['pattern'], $uri, $matches)) {
$this->setParam('_module', $router['module']);
$this->setParam('_controller', $router[... | Process custom router
@return bool | entailment |
protected function processRoute(): bool
{
$uri = $this->getCleanUri();
$uri = trim($uri, '/');
$raw = explode('/', $uri);
// rewrite module from request
if (\count($raw)) {
$this->setParam('_module', array_shift($raw));
}
// rewrite module from co... | Process router by default rules
Default routers examples
/
/:module/
/:module/:controller/
/:module/:controller/:key1/:value1/:key2/:value2...
@return bool | entailment |
protected function resetRequest(): void
{
$request = Request::getInstance();
// priority:
// - default values
// - from GET query
// - from path
$request = $request->withQueryParams(
array_merge(
[
'_module' => $this... | Reset Request
@return void | entailment |
public function execute($fetchType = null)
{
if (!$fetchType) {
$fetchType = $this->fetchType;
}
switch ($fetchType) {
case (!\is_int($fetchType)):
return Db::fetchObjects($this->getSql(), $this->params, $fetchType);
case \PDO::FETCH_CLASS... | {@inheritdoc}
@param integer|string|object $fetchType
@return integer|string|array | entailment |
public function getSql(): string
{
return $this->prepareSelect()
. $this->prepareFrom()
. $this->prepareWhere()
. $this->prepareGroupBy()
. $this->prepareHaving()
. $this->prepareOrderBy()
. $this->prepareLimit();
} | {@inheritdoc} | entailment |
public function addSelect(string ...$select): Select
{
$this->select = array_merge($this->select, $select);
return $this;
} | Adds an item that is to be returned in the query result.
Example
<code>
$sb = new Select();
$sb
->select('u.id')
->addSelect('p.id')
->from('users', 'u')
->leftJoin('u', 'phone', 'u.id = p.user_id');
</code>
@param string[] $select the selection expression
@return Select instance | entailment |
public function addGroupBy(string ...$groupBy): Select
{
$this->groupBy = array_merge($this->groupBy, $groupBy);
return $this;
} | Adds a grouping expression to the query.
Example
<code>
$sb = new Select();
$sb
->select('u.name')
->from('users', 'u')
->groupBy('u.lastLogin');
->addGroupBy('u.createdAt')
</code>
@param string[] $groupBy the grouping expression
@return Select instance | entailment |
public function andHaving(...$conditions): Select
{
$condition = $this->prepareCondition($conditions);
if ($this->having instanceof CompositeBuilder
&& $this->having->getType() === 'AND') {
$this->having->addPart($condition);
} else {
$this->having = new ... | Adds a restriction over the groups of the query, forming a logical
conjunction with any existing having restrictions
@param string[] $conditions the query restriction predicates
@return Select | entailment |
public function setPage(int $page = 1): Select
{
if (!$this->limit) {
throw new DbException('Please setup limit for use method `setPage`');
}
$this->offset = $this->limit * ($page - 1);
return $this;
} | Setup offset like a page number, start from 1
@param integer $page
@return Select
@throws DbException | entailment |
public function from(string $from, string $alias): self
{
$this->aliases[] = $alias;
$this->from[] = [
'table' => $from,
'alias' => $alias
];
return $this;
} | Set FROM
Create and add a query root corresponding to the table identified by the
given alias, forming a cartesian product with any existing query roots
<code>
$sb = new SelectBuilder();
$sb
->select('u.id')
->from('users', 'u')
</code>
@param string $from The table
@param string $alias The alias of the table
@r... | entailment |
public function join(string $fromAlias, string $join, string $alias, string $condition = null): self
{
return $this->innerJoin($fromAlias, $join, $alias, $condition);
} | Creates and adds a join to the query
Example
<code>
$sb = new Select();
$sb
->select('u.name')
->from('users', 'u')
->join('u', 'phone', 'p', 'p.is_primary = 1');
</code>
@param string $fromAlias The alias that points to a from clause
@param string $join The table name to join
@param string $alias The ali... | entailment |
protected function addJoin(
string $type,
string $fromAlias,
string $join,
string $alias,
string $condition = null
): self {
$this->aliases[] = $alias;
$this->join[$fromAlias][] = [
'joinType' => $type,
'joinTable' => $join,
... | addJoin()
@param string $type The type of join
@param string $fromAlias The alias that points to a from clause
@param string $join The table name to join
@param string $alias The alias of the join table
@param string $condition The condition for the join
@return $this | entailment |
protected function prepareFrom(): string
{
$fromClauses = [];
// Loop through all FROM clauses
foreach ($this->from as $from) {
$fromClause = Db::quoteIdentifier($from['table']) . ' AS ' . Db::quoteIdentifier($from['alias'])
. $this->prepareJoins($from['alias']);
... | Prepare From query part
@return string | entailment |
protected function prepareJoins($fromAlias): string
{
if (!isset($this->join[$fromAlias])) {
return '';
}
$query = '';
foreach ($this->join[$fromAlias] as $join) {
$query .= ' ' . strtoupper($join['joinType'])
. ' JOIN ' . Db::quoteIdentifier... | Generate SQL string for JOINs
@param string $fromAlias The alias of the table
@return string | entailment |
public function isRequired(): bool
{
foreach ($this->rules as $rule) {
if ($rule instanceof RequiredRule) {
return true;
}
}
return false;
} | Get required flag
@return bool | entailment |
public function callback($callable, $description = null): ValidatorChain
{
$rule = Validator::rule('callback', [$callable]);
if (null !== $description) {
$rule->setDescription($description);
}
$this->addRule($rule);
return $this;
} | Add Callback Rule to ValidatorChain
@param mixed $callable
@param string|null $description
@return ValidatorChain
@throws \Bluz\Validator\Exception\ComponentException | entailment |
public function regexp($expression, $description = null): ValidatorChain
{
$rule = Validator::rule('regexp', [$expression]);
if (null !== $description) {
$rule->setDescription($description);
}
$this->addRule($rule);
return $this;
} | Add Regexp Rule to ValidatorChain
@param string $expression
@param string|null $description
@return ValidatorChain
@throws \Bluz\Validator\Exception\ComponentException | entailment |
public function validate($input): bool
{
$this->error = null; // clean
foreach ($this->rules as $rule) {
if (!$rule->validate($input)) {
// apply custom description or use description from rule
$this->setError($this->description ?? $rule->getDescription())... | Validate chain of rules
@param mixed $input
@return bool | entailment |
public function info($message, array $context = []): void
{
$message = $this->interpolate($message, $context);
if (!$this->startTime) {
$this->startTime = $this->timer = $_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true);
}
$curTimer = microtime(true);
$curMemory... | Log info message
@param string $message
@param array $context
@return void | entailment |
public function log($level, $message, array $context = []): void
{
$this->{$level}[] = $this->interpolate($message, $context);
} | Logs with an arbitrary level
@param mixed $level
@param string $message
@param array $context
@return void | entailment |
public function send(): void
{
$body = $this->getBody();
$this->sendCookies();
switch (true) {
case 'CLI' === $this->type:
// no CLI response
return;
case null === $body:
case StatusCode::NO_CONTENT === $this->getStatusCod... | send
@throws NotAcceptableException
@throws \InvalidArgumentException | entailment |
public function getHeader($header): string
{
if ($this->hasHeader($header)) {
return implode(', ', $this->headers[$header]);
}
return '';
} | Retrieve a header by the given case-insensitive name as a string
This method returns all of the header values of the given
case-insensitive header name as a string concatenated together using
a comma.
@param string $header case-insensitive header name.
@return string | entailment |
public function addHeader($header, $value): void
{
if ($this->hasHeader($header)) {
$this->headers[$header][] = $value;
} else {
$this->setHeader($header, $value);
}
} | Appends a header value for the specified header
Existing values for the specified header will be maintained. The new
value will be appended to the existing list.
@param string $header header name to add
@param string $value value of the header
@return void | entailment |
public function setCookie(
$name,
$value = '',
$expire = 0,
$path = '/',
$domain = '',
$secure = false,
$httpOnly = false
): void {
// from PHP source code
if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
throw new \InvalidArgumen... | Set Cookie
@param string $name
@param string $value
@param int|string|\DateTime $expire
@param string $path
@param string $domain
@param bool $secure
@param bool $httpOnly
@return void
@throws \InvalidArgumentException | entailment |
public function validate($input): bool
{
return $this->less($this->minValue, $input)
&& $this->less($input, $this->maxValue);
} | Check input data
@param NumericRule $input
@return bool | entailment |
public function add($name): ValidatorChain
{
$this->validators[$name] = $this->validators[$name] ?? Validator::create();
return $this->validators[$name];
} | Add chain to form
@param string $name
@return ValidatorChain | entailment |
public function validate($input): bool
{
$this->exception = new ValidatorException();
// run chains
foreach ($this->validators as $key => $validators) {
// skip validation for non required elements
if (!isset($input[$key]) && !$validators->isRequired()) {
... | Validate chain of rules
@param array $input
@return bool | entailment |
protected function validateItem($key, $value): bool
{
// run validators chain
$result = $this->validators[$key]->validate($value);
if (!$result) {
$this->exception->setError($key, $this->validators[$key]->getError());
}
return $result;
} | Validate chain of rules for single item
@param string $key
@param mixed $value
@return bool | entailment |
public function setFromArray(array $data): void
{
foreach ($data as $key => $value) {
$this->container[$key] = $value;
}
} | Sets all data in the row from an array
@param array $data
@return void | entailment |
public function init(): void
{
// Setup locale
putenv('LC_ALL=' . $this->locale);
putenv('LANG=' . $this->locale);
putenv('LANGUAGE=' . $this->locale);
// Windows workaround
\defined('LC_MESSAGES') ?: \define('LC_MESSAGES', 6);
setlocale(LC_MESSAGES, $this->... | Initialization
@return void
@throws ConfigurationException
@throw \Bluz\Config\ConfigException | entailment |
public function addTextDomain($domain, $path): void
{
// check path
if (!is_dir($path)) {
throw new ConfigurationException("Translator configuration path `$path` not found");
}
bindtextdomain($domain, $path);
// @todo: hardcoded codeset
bind_textdomain_c... | Add text domain for gettext
@param string $domain of text for gettext setup
@param string $path on filesystem
@return void
@throws ConfigurationException | entailment |
public static function translate(string $message, ...$text): string
{
if (empty($message)) {
return $message;
}
if (\function_exists('gettext')) {
$message = gettext($message);
}
if (\func_num_args() > 1) {
$message = vsprintf($message, $... | Translate message
Simple example of usage
equal to gettext('Message')
Translator::translate('Message');
Simple replace of one or more argument(s)
equal to sprintf(gettext('Message to %s'), 'Username')
Translator::translate('Message to %s', 'Username');
@param string $message
@param string[] ...$text
@return s... | entailment |
public static function translatePlural(string $singular, string $plural, $number, ...$text): string
{
if (\function_exists('ngettext')) {
$message = ngettext($singular, $plural, $number);
} else {
$message = $singular;
}
if (\func_num_args() > 3) {
... | Translate plural form
Example of usage plural form + sprintf
equal to sprintf(ngettext('%d comment', '%d comments', 4), 4)
Translator::translatePlural('%d comment', '%d comments', 4)
Example of usage plural form + sprintf
equal to sprintf(ngettext('%d comment', '%d comments', 4), 4, 'Topic')
Translator::translatePlur... | entailment |
protected function filter($input): string
{
$input = parent::filter((string)$input);
return preg_replace('/\s/', '', $input);
} | Filter input data
@param string $input
@return string | entailment |
public function getDescription(): string
{
if (!empty($this->networkRange)) {
$message = $this->networkRange['min'];
if (isset($this->networkRange['max'])) {
$message .= '-' . $this->networkRange['max'];
} else {
$message .= '/' . long2ip((... | Get error template
@return string | entailment |
protected function parseRange($input): ?array
{
if ($input === null || $input === '*' || $input === '*.*.*.*'
|| $input === '0.0.0.0-255.255.255.255'
) {
return null;
}
$range = ['min' => null, 'max' => null, 'mask' => null];
if (strpos($input, '-') ... | Parse IP range
@param string $input
@return array|null
@throws \Bluz\Validator\Exception\ComponentException | entailment |
protected function parseRangeUsingWildcards($input, &$range): void
{
$this->fillAddress($input);
$range['min'] = str_replace('*', '0', $input);
$range['max'] = str_replace('*', '255', $input);
} | Parse range using wildcards
@param string $input
@param array $range | entailment |
protected function parseRangeUsingCidr($input, &$range): void
{
$input = explode('/', $input);
$this->fillAddress($input[0], '0');
$range['min'] = $input[0];
$isAddressMask = strpos($input[1], '.') !== false;
if ($isAddressMask && $this->verifyAddress($input[1])) {
... | Parse range using Classless Inter-Domain Routing (CIDR)
@param string $input
@param array $range
@throws \Bluz\Validator\Exception\ComponentException
@link http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing | entailment |
protected function verifyNetwork($input): bool
{
if ($this->networkRange === null) {
return true;
}
if (isset($this->networkRange['mask'])) {
return $this->belongsToSubnet($input);
}
$input = sprintf('%u', ip2long($input));
$min = sprintf('%... | Verify Network by mask
@param string $input
@return bool | entailment |
protected function belongsToSubnet($input): bool
{
$range = $this->networkRange;
$min = sprintf('%032b', ip2long($range['min']));
$input = sprintf('%032b', ip2long($input));
return ($input & $range['mask']) === ($min & $range['mask']);
} | Check subnet
@param string $input
@return bool | entailment |
protected function initTable(): void
{
$tableClass = class_namespace(static::class) . '\\Table';
// check class initialization
if (!class_exists($tableClass) || !is_subclass_of($tableClass, TableInterface::class)) {
throw new TableNotFoundException('`Table` class is not exists o... | Init table instance for manipulation
@return void
@throws TableNotFoundException | entailment |
public function getPath(): string
{
if (!$this->path) {
if (\defined('PATH_APPLICATION')) {
$this->path = PATH_APPLICATION;
} else {
$reflection = new \ReflectionClass($this);
// 3 level up
$this->path = \dirname($reflec... | Get path to Application
@return string
@throws \ReflectionException | entailment |
public function useLayout($flag = null): bool
{
if (\is_bool($flag)) {
$this->layoutFlag = $flag;
}
return $this->layoutFlag;
} | Return/setup Layout Flag
@param bool|null $flag
@return bool | entailment |
public function init($environment = 'production'): void
{
$this->environment = $environment;
try {
// initial default helper path
$this->addHelperPath(__DIR__ . '/Helper/');
// init Config
$this->initConfig();
// first log message
... | Initialize system packages
@param string $environment
@throws ApplicationException
@return void | entailment |
protected function initConfig(): void
{
$loader = new ConfigLoader();
$loader->setPath($this->getPath());
$loader->setEnvironment($this->getEnvironment());
$loader->load();
$config = new \Bluz\Config\Config();
$config->setFromArray($loader->getConfig());
Con... | Initial Request instance
@return void
@throws \Bluz\Config\ConfigException
@throws \ReflectionException | entailment |
protected function initRouter(): void
{
$router = new \Bluz\Router\Router();
$router->setOptions(Config::get('router'));
Router::setInstance($router);
} | Initial Router instance
@return void | entailment |
protected function initTranslator(): void
{
$translator = new \Bluz\Translator\Translator();
$translator->setOptions(Config::get('translator'));
$translator->init();
Translator::setInstance($translator);
} | Initial Translator instance
@return void
@throws Common\Exception\ConfigurationException | entailment |
protected function preProcess(): void
{
Router::process();
// disable Layout for XmlHttpRequests
if (Request::isXmlHttpRequest()) {
$this->layoutFlag = false;
}
// switch to JSON response based on Accept header
if (Request::checkAccept([Request::TYPE_HTM... | Extension point: pre process
- Router processing
- Analyse request headers
@return void | entailment |
protected function doProcess(): void
{
$module = Request::getModule();
$controller = Request::getController();
$params = Request::getParams();
try {
// try to dispatch controller
$result = $this->dispatch($module, $controller, $params);
} catch (Forbi... | Do process
- Dispatch controller
- Exceptions handling
- Setup layout
- Setup response body
@return void | entailment |
public function dispatch($module, $controller, array $params = []): Controller
{
$instance = new Controller($module, $controller, $params);
Logger::info("app:dispatch:>>>: $module/$controller");
$this->preDispatch($instance);
Logger::info("app:dispatch:===: $module/$controller");
... | Dispatch controller with params
Call dispatch from any \Bluz\Package
Application::getInstance()->dispatch($module, $controller, array $params);
@param string $module
@param string $controller
@param array $params
@return Controller
@throws ComponentException
@throws CommonException
@throws ControllerException
@t... | entailment |
public function andWhere(...$conditions): self
{
$condition = $this->prepareCondition($conditions);
if ($this->where instanceof CompositeBuilder
&& $this->where->getType() === 'AND') {
$this->where->addPart($condition);
} else {
$this->where = new Composi... | Add WHERE .. AND .. condition
Adds one or more restrictions to the query results, forming a logical
conjunction with any previously specified restrictions.
<code>
$sb = new SelectBuilder();
$sb
->select('u')
->from('users', 'u')
->where('u.username LIKE ?', '%Smith%')
->andWhere('u.is_active = ?', 1);
</code>
@param ... | entailment |
public static function redirectTo($module, $controller = 'index', array $params = []): void
{
$url = Router::getFullUrl($module, $controller, $params);
self::redirect($url);
} | Redirect to controller
@param string $module
@param string $controller
@param array $params
@return void
@throws RedirectException | entailment |
public static function bootTranslatable(): void
{
static::created(function (Model $model) {
$model->translations()->saveMany($model->translationCache);
});
static::updating(function (Model $model) {
$model->translations()->saveMany($model->translationCache);
... | Boot the translatable trait.
@return void | entailment |
public function translate(string $locale = null, bool $fallback = true): ?Model
{
$locale = $locale ?: $this->getLocale();
$translation = $this->getTranslation($locale);
if (!$translation && $fallback) {
$translation = $this->getTranslation($this->getFallback());
}
... | Get a translation.
@param string|null $locale
@param bool $fallback
@return \Illuminate\Database\Eloquent\Model|null | entailment |
public function scopeWithTranslations(Builder $query, string $locale = null): Builder
{
$locale = $locale ?: $this->getLocale();
return $query->with(['translations' => function (HasMany $query) use ($locale) {
$query->where('locale', $locale);
}]);
} | Query scope for eager-loading the translations for current (or a given) locale.
@param \Illuminate\Database\Eloquent\Builder $query
@param string|null $locale
@return \Illuminate\Database\Eloquent\Builder | entailment |
protected function translateOrNew(string $locale): Model
{
if (isset($this->translationCache[$locale])) {
return $this->translationCache[$locale];
}
if (!$this->exists) {
return $this->translations()->newModelInstance(['locale' => $locale]);
}
return... | Get a translation or create new.
@param string $locale
@return \Illuminate\Database\Eloquent\Model | entailment |
protected function getTranslation(string $locale): ?Model
{
if (isset($this->translationCache[$locale])) {
return $this->translationCache[$locale];
}
if (!$this->exists) {
return null;
}
$translation = $this->translations
->where('locale'... | Get a translation from cache, loaded relation, or database.
@param string $locale
@return \Illuminate\Database\Eloquent\Model|null | entailment |
protected function getEmptyTranslation(string $locale): Model
{
$appLocale = $this->getLocale();
$this->setLocale($locale);
foreach ($this->getTranslatable() as $attribute) {
$translation = $this->setAttribute($attribute, null);
}
$this->setLocale($appLocale);
... | Get an empty translation.
@param string $locale
@return \Illuminate\Database\Eloquent\Model | entailment |
public function getAttribute($key)
{
if (in_array($key, $this->getTranslatable())) {
return $this->translate() ? $this->translate()->$key : null;
}
return parent::getAttribute($key);
} | Get an attribute from the model or translation.
@param string $key
@return mixed | entailment |
public function setAttribute($key, $value)
{
if (in_array($key, $this->getTranslatable())) {
$translation = $this->translateOrNew($this->getLocale());
$translation->$key = $value;
$this->translationCache[$this->getLocale()] = $translation;
return $translati... | Set a given attribute on the model or translation.
@param string $key
@param mixed $value
@return $this | entailment |
public function isDirty($attributes = null): bool
{
$attributes = is_array($attributes) ? $attributes : func_get_args();
if (parent::isDirty($attributes)) {
return true;
}
foreach ($this->translationCache as $translation) {
if ($translation->isDirty($attribu... | Determine if the model or given attribute(s) have been modified.
@param array|string|null $attributes
@return bool | entailment |
public static function getAdapter($adapter)
{
$config = Config::get('cache');
if ($config && $adapter && isset($config['enabled']) && $config['enabled']) {
if (!isset($config['pools'][$adapter])) {
throw new ComponentException("Class `Proxy\\Cache` required configuration... | Get Cache Adapter
@param string $adapter
@return Instance|false
@throws ComponentException | entailment |
public static function get($key)
{
if (!$cache = self::getInstance()) {
return false;
}
$key = self::prepare($key);
try {
if ($cache->hasItem($key)) {
$item = $cache->getItem($key);
if ($item->isHit()) {
re... | Get value of cache item
@param string $key
@return mixed | entailment |
public static function set($key, $data, $ttl = self::TTL_NO_EXPIRY, $tags = [])
{
if (!$cache = self::getInstance()) {
return false;
}
$key = self::prepare($key);
try {
$item = $cache->getItem($key);
$item->set($data);
if (self::TTL_N... | Set value of cache item
@param string $key
@param mixed $data
@param int $ttl
@param string[] $tags
@return bool | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.