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); return $row; }
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_map( function ($field) use ($name) { return $name .'.'. $field; }, $fields ); $select->select(implode(', ', $fields)); } // switch statement for DB type $type = Proxy\Db::getOption('connect', 'type'); switch ($type) { case 'mysql': $selectPart = $select->getSelect(); $selectPart[0] = 'SQL_CALC_FOUND_ROWS ' . $selectPart[0]; $select->select(...$selectPart); $totalSQL = 'SELECT FOUND_ROWS()'; break; case 'pgsql': default: $selectTotal = clone $select; $selectTotal->select('COUNT(*)'); $totalSQL = $selectTotal->getSql(); break; } $select->setLimit($limit); $select->setOffset($offset); $result = []; $total = 0; // run queries // use transaction to avoid errors Proxy\Db::transaction( function () use (&$result, &$total, $select, $totalSQL) { $result = $select->execute(); $total = Proxy\Db::fetchOne($totalSQL); } ); return [$result, $total]; }
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->getFile(); if (!\is_callable($controllerClosure)) { throw new ControllerException("Controller is not callable '{$module}/{$controller}'"); } // process params $params = $this->getMeta()->params($params); // call Closure or Controller $result = $controllerClosure(...$params); // switch statement for result of Closure run switch (true) { case ($result === false): // return "false" is equal to disable view and layout $this->disableLayout(); $this->disableView(); break; case \is_string($result): // return string variable is equal to change view template $this->setTemplate($result); break; case \is_array($result): // return associative array is equal to setup view data $this->getData()->setFromArray($result); break; case ($result instanceof self): // return Controller - just extract data from it $this->getData()->setFromArray($result->getData()->toArray()); break; } return $this->getData(); }
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->controller}'", 404); } $this->file = $file; }
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, $meta, Cache::TTL_NO_EXPIRY, ['system', 'meta'] ); } $this->meta = $meta; }
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('/', rtrim($path, '/')); // module $this->module = array_shift($this->params); // controller $this->controller = array_shift($this->params); $data = Request::getParams(); unset($data['_method'], $data['_module'], $data['_controller']); $this->data = array_merge($data, $this->data); $primary = $this->crud->getPrimaryKey(); $this->primary = array_intersect_key($this->data, array_flip($primary)); }
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()->getPathInfo()->getBasename(); $controller = $file->getBasename('.php'); $controllerInstance = new Controller($module, $controller); $meta = $controllerInstance->getMeta(); if ($routes = $meta->getRoute()) { foreach ($routes as $route => $pattern) { if (!isset($reverse[$module])) { $reverse[$module] = []; } $reverse[$module][$controller] = ['route' => $route, 'params' => $meta->getParams()]; $rule = [ $route => [ 'pattern' => $pattern, 'module' => $module, 'controller' => $controller, 'params' => $meta->getParams() ] ]; // static routers should be first, than routes with variables `$...` // all routes begin with slash `/` if (strpos($route, '$')) { $routers[] = $rule; } else { array_unshift($routers, $rule); } } } } $routers = array_merge(...$routers); return [$routers, $reverse]; }
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->cleanUri = $uri; } return $this->cleanUri; }
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->reverse[$module][$controller])) { return $this->urlCustom($module, $controller, $params); } return $this->urlRoute($module, $controller, $params); }
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 ($port && !\in_array($port, [80, 443], true)) { $host .= ':' . $port; } $url = $this->getUrl($module, $controller, $params); return $scheme . $host . $url; }
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] = $value; continue; } $url = str_replace('{$' . $key . '}', $value, $url, $replaced); // if not replaced, setup param as GET if (!$replaced) { $getParams[$key] = $value; } } // clean optional params $url = preg_replace('/\{\$[a-z0-9-_]+\}/i', '', $url); // clean regular expression (.*) $url = preg_replace('/\(\.\*\)/', '', $url); // replace "//" with "/" $url = str_replace('//', '/', $url); if (!empty($getParams)) { $url .= '?' . http_build_query($getParams); } return $this->getBaseUrl() . ltrim($url, '/'); }
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; } $url .= $module . '/' . $controller; $getParams = []; foreach ($params as $key => $value) { // sub-array as GET params if (\is_array($value)) { $getParams[$key] = $value; continue; } $url .= '/' . urlencode((string)$key) . '/' . urlencode((string)$value); } if (!empty($getParams)) { $url .= '?' . http_build_query($getParams); } return $url; }
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['controller']); foreach ($router['params'] as $param => $type) { if (isset($matches[$param])) { $this->setParam($param, $matches[$param]); } } return true; } } return false; }
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 controller if (\count($raw)) { $this->setParam('_controller', array_shift($raw)); } if ($size = \count($raw)) { // save raw $this->rawParams = $raw; // save as index params foreach ($raw as $i => $value) { $this->setParam($i, $value); } // remove tail if ($size % 2 === 1) { array_pop($raw); $size = \count($raw); } // or use array_chunk and run another loop? for ($i = 0; $i < $size; $i += 2) { $this->setParam($raw[$i], $raw[$i + 1]); } } return true; }
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->getDefaultModule(), '_controller' => $this->getDefaultController() ], $request->getQueryParams(), $this->params ) ); Request::setInstance($request); }
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: return Db::fetchObjects($this->getSql(), $this->params); case \PDO::FETCH_ASSOC: default: return Db::fetchAll($this->getSql(), $this->params); } }
{@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 CompositeBuilder([$this->having, $condition]); } return $this; }
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 @return $this
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 alias of the join table @param string $condition The condition for the join @return $this
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, 'joinAlias' => $alias, 'joinCondition' => $condition ]; return $this; }
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']); $fromClauses[$from['alias']] = $fromClause; } return ' FROM ' . implode(', ', $fromClauses); }
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($join['joinTable']) . ' AS ' . Db::quoteIdentifier($join['joinAlias']) . ' ON ' . $join['joinCondition']; $query .= $this->prepareJoins($join['joinAlias']); } return $query; }
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()); return false; } } return true; }
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 = memory_get_usage(); $key = sprintf( '%f :: %f :: %d', $curTimer - $this->startTime, $curTimer - $this->timer, $curMemory - $this->memory ); $this->info[$key] = $message; $this->timer = $curTimer; $this->memory = $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->getStatusCode(): $response = new EmptyResponse($this->getStatusCode(), $this->getHeaders()); break; case StatusCode::MOVED_PERMANENTLY === $this->getStatusCode(): case StatusCode::FOUND === $this->getStatusCode(): $response = new RedirectResponse( $this->getHeader('Location'), $this->getStatusCode(), $this->getHeaders() ); break; case 'JSON' === $this->type: // JSON response // setup messages if (Messages::count()) { $this->setHeader('Bluz-Notify', json_encode(Messages::popAll())); } // encode body data to JSON $response = new JsonResponse( $body, $this->getStatusCode(), $this->getHeaders() ); break; case 'FILE' === $this->type: // File attachment $response = new AttachmentResponse( $this->body->getData()->get('FILE'), $this->getStatusCode(), $this->getHeaders() ); break; case 'HTML' === $this->type: default: // HTML response $response = new HtmlResponse( (string)$body, $this->getStatusCode(), $this->getHeaders() ); break; } $emitter = new SapiEmitter(); $emitter->emit($response); }
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 \InvalidArgumentException('The cookie name contains invalid characters.'); } if (empty($name)) { throw new \InvalidArgumentException('The cookie name cannot be empty.'); } // convert expiration time to a Unix timestamp if ($expire instanceof \DateTime) { $expire = $expire->format('U'); } elseif (!is_numeric($expire)) { $expire = strtotime($expire); if (false === $expire || -1 === $expire) { throw new \InvalidArgumentException('The cookie expiration time is not valid.'); } } $this->cookies[$name] = [ 'name' => $name, 'value' => $value, 'expire' => $expire, 'path' => $path, 'domain' => $domain, 'secure' => (bool)$secure, 'httpOnly' => (bool)$httpOnly ]; }
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()) { continue; } $this->validateItem($key, $input[$key] ?? null); } return !$this->hasErrors(); }
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->locale); // For gettext only if (\function_exists('gettext')) { // Setup domain path $this->addTextDomain($this->domain, $this->path); // Setup default domain textdomain($this->domain); } }
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_codeset($domain, 'UTF-8'); }
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, $text); } return $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 string
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) { // first element is number array_unshift($text, $number); $message = vsprintf($message, $text); } return $message; }
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::translatePlural('%d comment to %s', '%d comments to %s', 4, 'Topic') @param string $singular @param string $plural @param integer $number @param string[] ...$text @return string @link http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
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((string)bindec($this->networkRange['mask'])); } return __('must be an IP address in the "%s" range', $message); } return __('must be an IP address'); }
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, '-') !== false) { [$range['min'], $range['max']] = explode('-', $input); } elseif (strpos($input, '*') !== false) { $this->parseRangeUsingWildcards($input, $range); } elseif (strpos($input, '/') !== false) { $this->parseRangeUsingCidr($input, $range); } else { throw new ComponentException('Invalid network range'); } if (!$this->verifyAddress($range['min'])) { throw new ComponentException('Invalid network range'); } if (isset($range['max']) && !$this->verifyAddress($range['max'])) { throw new ComponentException('Invalid network range'); } return $range; }
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])) { $range['mask'] = sprintf('%032b', ip2long($input[1])); return; } if ($isAddressMask || $input[1] < 8 || $input[1] > 30) { throw new ComponentException('Invalid network mask'); } $range['mask'] = sprintf('%032b', ip2long(long2ip(~(2 ** (32 - $input[1]) - 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('%u', ip2long($this->networkRange['min'])); $max = sprintf('%u', ip2long($this->networkRange['max'])); return ($input >= $min) && ($input <= $max); }
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 or not initialized'); } /** * @var TableInterface $tableClass */ $this->setTable($tableClass::getInstance()); }
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($reflection->getFileName(), 3); } } return $this->path; }
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 Logger::info('app:init'); // init Session, start inside class (if needed) Session::getInstance(); // init Messages Messages::getInstance(); // init Request $this->initRequest(); // init Response $this->initResponse(); // init Translator $this->initTranslator(); // init Router $this->initRouter(); } catch (\Exception $e) { throw new ApplicationException("Application can't be loaded: " . $e->getMessage()); } }
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()); Config::setInstance($config); // setup configuration for current environment if ($debug = Config::get('debug')) { $this->debugFlag = (bool)$debug; } // initial php settings if ($ini = Config::get('php')) { foreach ($ini as $key => $value) { $result = ini_set($key, $value); Logger::info('app:init:php:' . $key . ':' . ($result ?: '---')); } } }
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_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON) { $this->layoutFlag = false; Response::setType('JSON'); } }
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 (ForbiddenException $e) { // dispatch default error controller $result = $this->forbidden($e); } catch (RedirectException $e) { // should return `null` for disable output and setup redirect headers $result = $this->redirect($e); } catch (\Exception $e) { // dispatch default error controller $result = $this->error($e); } // setup layout, if needed if ($this->useLayout()) { // render view to layout // needed for headScript and headStyle helpers Layout::setContent($result->render()); Response::setBody(Layout::getInstance()); } else { Response::setBody($result); } }
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"); $this->doDispatch($instance); Logger::info("app:dispatch:<<<: $module/$controller"); $this->postDispatch($instance); return $instance; }
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 @throws ForbiddenException @throws NotAcceptableException @throws NotAllowedException
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 CompositeBuilder([$this->where, $condition]); } return $this; }
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 string[] $conditions Optional the query restriction predicates @return $this
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()); } if (!$translation && !$fallback) { $translation = $this->getEmptyTranslation($locale); } return $translation; }
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 $this->translations() ->where('locale', $locale) ->firstOrNew(['locale' => $locale]); }
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', $locale) ->first(); if ($translation) { $this->translationCache[$locale] = $translation; } return $translation; }
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); return $translation; }
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 $translation; } return parent::setAttribute($key, $value); }
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($attributes)) { return true; } } return false; }
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 for `$adapter` adapter"); } if (!isset(static::$pools[$adapter])) { static::$pools[$adapter] = $config['pools'][$adapter](); } return static::$pools[$adapter]; } return false; }
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()) { return $item->get(); } } } catch (InvalidArgumentException $e) { // something going wrong Logger::error($e->getMessage()); } return false; }
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_NO_EXPIRY !== $ttl) { $item->expiresAfter($ttl); } if (!empty($tags)) { $item->setTags($tags); } return $cache->save($item); } catch (InvalidArgumentException $e) { // something going wrong Logger::error($e->getMessage()); } return false; }
Set value of cache item @param string $key @param mixed $data @param int $ttl @param string[] $tags @return bool
entailment