sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function clearTag($tag): bool { if (self::getInstance() instanceof HierarchicalPoolInterface) { return self::getInstance()->invalidateTag($tag); } return false; }
Clear cache items by tag @see TaggableCacheItemPoolInterface::invalidateTag() @param string $tag @return bool
entailment
public static function clearTags(array $tags): bool { if (self::getInstance() instanceof HierarchicalPoolInterface) { return self::getInstance()->invalidateTags($tags); } return false; }
Clear cache items by tags @see TaggableCacheItemPoolInterface::invalidateTags() @param array $tags @return bool
entailment
private function queryTableSchemas() { $tableSchemas = []; if (count($this->cachingSchemas) === 0) { $tableSchemas = $this->findTableSchemas(); } else { //Find tables from given schemas foreach ($this->cachingSchemas as $shemaName) { $tableSchemas = array_merge($tableSchemas, $this->findTableSchemas($shemaName)); } } return $tableSchemas; }
Searching table names in a default schema or in [[cachingSchemas]] @return array
entailment
private function findTableSchemas($schema = null) { $tableNames = $this->getTableNames($schema, true); if (is_callable($this->tableNameFilter)) { $tableNames = array_filter($tableNames, function($tableName) use ($schema) { return call_user_func($this->tableNameFilter, $tableName, $schema); } ); } $tableSchemas = array_map( function($tableName) use ($schema) { $tableSchema = new TableSchema(); $tableNameFull = $schema === null ? $tableName : "$schema.$tableName"; $this->resolveTableNames($tableSchema, $tableNameFull); return $tableSchema; }, $tableNames); return $tableSchemas; }
Searching table schemas in a default or specified schema @param string|null $schema @return array
entailment
public function buildSchemaCache() { $this->cleanupCache(); $tableSchemas = $this->queryTableSchemas(); foreach ($tableSchemas as $tableSchema) { if ($this->findColumns($tableSchema)) { $this->findConstraints($tableSchema); $key = $this->getTableCacheKey($tableSchema); //Yii::$app->cache->delete($key); $result = Yii::$app->cache->set( $key, $tableSchema, $this->schemaCacheDuration, new TagDependency(['tags' => $this->cacheTagName]) ); if (YII_ENV == 'dev') { if ($result === true) Yii::info("Table \"$tableSchema->fullName\" has been cached", 'Schema cache'); else Yii::error("Caching of \"$tableSchema->fullName\" table failed", 'Schema cache'); } } } Yii::$app->cache->set( $this->getCacheCreationTimeKey(), microtime(true), $this->schemaCacheDuration, new TagDependency(['tags' => $this->cacheTagName])); }
Builds schema cache
entailment
private function loadTable($name, $searchInCacheOnly = false) { $table = new TableSchema(); $this->resolveTableNames($table, $name); $tablekey = $this->getTableCacheKey($table); $cachedTableSchema = Yii::$app->cache->get($tablekey); if ($cachedTableSchema !== false) { return [$cachedTableSchema, true]; } else { if ($searchInCacheOnly !== true) return [parent::loadTableSchema($name), false]; else return [null, false]; } }
Returns table from cache. if $searchInCacheOnly is `false` then call [[loadTableSchema()]].
entailment
public function isAllowed($module, $privilege): bool { if ($privilege) { $user = Auth::getIdentity(); return $user && $user->hasPrivilege($module, $privilege); } return true; }
Check user access by pair module-privilege @param string $module @param string $privilege @return bool
entailment
public function set(string $key, $value, $type = \PDO::PARAM_STR): self { $this->setParam(null, $value, $type); $this->set[] = Db::quoteIdentifier($key) . ' = ?'; return $this; }
Set key-value pair Sets a new value for a column in a insert/update query <code> $ub = new UpdateBuilder(); $ub ->update('users') ->set('password', md5('password')) ->where('id = ?'); </code> @param string $key The column to set @param string|integer $value The value, expression, placeholder, etc @param int $type The type of value on of PDO::PARAM_* params @return $this
entailment
protected function less($what, $than): bool { if ($this->inclusive) { return $what <= $than; } return $what < $than; }
Check $what less $than or not @param mixed $what @param mixed $than @return bool
entailment
public function validate($input): bool { // for array if (\is_array($input)) { return \in_array($this->containsValue, $input, true); } // for string if (\is_string($input)) { return false !== mb_strpos($input, $this->containsValue, 0, mb_detect_encoding($input)); } return false; }
Check input data @param string|array $input @return bool
entailment
public function validate($input): bool { if (false !== strpos($input, '--')) { return false; } if (!preg_match('/^[0-9a-z\-]+$/', $input)) { return false; } if (preg_match('/^-|-$/', $input)) { return false; } return true; }
Check input data @param string $input @return bool
entailment
public function orderBy(string $sort, string $order = 'ASC'): self { $order = 'ASC' === strtoupper($order) ? 'ASC' : 'DESC'; $this->orderBy = [$sort => $order]; return $this; }
Specifies an ordering for the query results Replaces any previously specified orderings, if any @param string $sort Sort expression @param string $order Sort direction (ASC or DESC) @return $this
entailment
protected function prepareOrderBy(): string { if (empty($this->orderBy)) { return ''; } $orders = []; foreach ($this->orderBy as $column => $order) { $orders[] = $column . ' ' . $order; } return ' ORDER BY ' . implode(', ', $orders); }
Prepare string to apply it inside SQL query @return string
entailment
public function validate($input): bool { $input = (string)$input; // check by regular expression if (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $input) && preg_match("/^.{1,253}$/", $input) && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $input) ) { // check by DNS record if ($this->checkDns) { return checkdnsrr($input, 'A'); } return true; } return false; }
Check input data @param string $input @return bool
entailment
public function getSql(): string { return 'UPDATE ' . Db::quoteIdentifier($this->table) . $this->prepareSet() . $this->prepareWhere() . $this->prepareLimit(); }
{@inheritdoc}
entailment
public function setConnect(array $connect): void { $this->connect = array_merge($this->connect, $connect); $this->checkConnect(); }
Setup connection Just save connection settings <code> $db->setConnect([ 'type' => 'mysql', 'host' => 'localhost', 'name' => 'db name', 'user' => 'root', 'pass' => '' ]); </code> @param array $connect options @throws ConfigurationException @return void
entailment
private function checkConnect(): void { if (empty($this->connect['type']) || empty($this->connect['host']) || empty($this->connect['name']) || empty($this->connect['user']) ) { throw new ConfigurationException( 'Database adapter is not configured. Please check `db` configuration section: required type, host, db name and user' ); } }
Check connection options @return void @throws ConfigurationException
entailment
public function connect(): bool { try { $this->checkConnect(); $this->log('Connect to ' . $this->connect['host']); $this->handler = new \PDO( $this->connect['type'] . ':host=' . $this->connect['host'] . ';dbname=' . $this->connect['name'], $this->connect['user'], $this->connect['pass'], $this->connect['options'] ); foreach ($this->attributes as $attribute => $value) { $this->handler->setAttribute($attribute, $value); } $this->ok(); } catch (\Exception $e) { throw new DbException("Attempt connection to database is failed: {$e->getMessage()}"); } return true; }
Connect to Db @return bool @throws DbException
entailment
protected function prepare(string $sql, array $params = []): \PDOStatement { $stmt = $this->handler()->prepare($sql); $stmt->execute($params); $this->log($sql, $params); return $stmt; }
Prepare SQL query and return PDO Statement @param string $sql SQL query with placeholders @param array $params params for query placeholders @todo Switch to PDO::activeQueryString() when it will be possible @link https://wiki.php.net/rfc/debugging_pdo_prepared_statement_emulation @return \PDOStatement @throws DbException
entailment
public function quote(string $value, int $type = \PDO::PARAM_STR): string { return $this->handler()->quote($value, $type); }
Quotes a string for use in a query Example of usage <code> $db->quote($_GET['id']) </code> @param string $value @param int $type @return string @throws DbException
entailment
public function quoteIdentifier(string $identifier): string { // switch statement for DB type switch ($this->connect['type']) { case 'mysql': return '`' . str_replace('`', '``', $identifier) . '`'; case 'postgresql': case 'sqlite': default: return '"' . str_replace('"', '\\' . '"', $identifier) . '"'; } }
Quote a string so it can be safely used as a table or column name @param string $identifier @return string
entailment
public function query($sql, array $params = [], array $types = []): int { $stmt = $this->handler()->prepare($sql); foreach ($params as $key => &$param) { $stmt->bindParam( (is_int($key) ? $key + 1 : ':' . $key), $param, $types[$key] ?? \PDO::PARAM_STR ); } $this->log($sql, $params); $stmt->execute($params); $this->ok(); return $stmt->rowCount(); }
Execute SQL query Example of usage <code> $db->query("SET NAMES 'utf8'"); </code> @param string $sql SQL query with placeholders "UPDATE users SET name = :name WHERE id = :id" @param array $params params for query placeholders (optional) array (':name' => 'John', ':id' => '123') @param array $types Types of params (optional) array (':name' => \PDO::PARAM_STR, ':id' => \PDO::PARAM_INT) @return integer the number of rows @throws DbException
entailment
public function select(...$select): Query\Select { $query = new Query\Select(); $query->select(...$select); return $query; }
Create new query select builder @param string[] $select The selection expressions @return Query\Select
entailment
public function insert(string $table): Query\Insert { $query = new Query\Insert(); $query->insert($table); return $query; }
Create new query insert builder @param string $table @return Query\Insert
entailment
public function update(string $table): Query\Update { $query = new Query\Update(); $query->update($table); return $query; }
Create new query update builder @param string $table @return Query\Update
entailment
public function delete(string $table): Query\Delete { $query = new Query\Delete(); $query->delete($table); return $query; }
Create new query update builder @param string $table @return Query\Delete
entailment
public function fetchOne(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetch(\PDO::FETCH_COLUMN); $this->ok(); return $result; }
Return first field from first element from the result set Example of usage <code> $db->fetchOne("SELECT COUNT(*) FROM users"); </code> @param string $sql SQL query with placeholders "SELECT * FROM users WHERE name = :name AND pass = :pass" @param array $params params for query placeholders (optional) array (':name' => 'John', ':pass' => '123456') @return string|false @throws DbException
entailment
public function fetchRow(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetch(\PDO::FETCH_ASSOC); $this->ok(); return $result; }
Returns an array containing first row from the result set Example of usage <code> $db->fetchRow("SELECT name, email FROM users WHERE id = ". $db->quote($id)); $db->fetchRow("SELECT name, email FROM users WHERE id = ?", [$id]); $db->fetchRow("SELECT name, email FROM users WHERE id = :id", [':id'=>$id]); </code> @param string $sql SQL query with placeholders "SELECT * FROM users WHERE name = :name AND pass = :pass" @param array $params params for query placeholders (optional) array (':name' => 'John', ':pass' => '123456') @return array|false array ('name' => 'John', 'email' => '[email protected]') @throws DbException
entailment
public function fetchAll(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); $this->ok(); return $result; }
Returns an array containing all of the result set rows Example of usage <code> $db->fetchAll("SELECT * FROM users WHERE ip = ?", ['192.168.1.1']); </code> @param string $sql SQL query with placeholders "SELECT * FROM users WHERE ip = :ip" @param array $params params for query placeholders (optional) array (':ip' => '127.0.0.1') @return array[]|false @throws DbException
entailment
public function fetchColumn(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetchAll(\PDO::FETCH_COLUMN); $this->ok(); return $result; }
Returns an array containing one column from the result set rows @param string $sql SQL query with placeholders "SELECT id FROM users WHERE ip = :ip" @param array $params params for query placeholders (optional) array (':ip' => '127.0.0.1') @return array|false @throws DbException
entailment
public function fetchGroup(string $sql, array $params = [], $object = null) { $stmt = $this->prepare($sql, $params); if ($object) { $result = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_GROUP, $object); } else { $result = $stmt->fetchAll(\PDO::FETCH_ASSOC | \PDO::FETCH_GROUP); } $this->ok(); return $result; }
Returns an array containing all of the result set rows Group by first column <code> $db->fetchGroup("SELECT ip, COUNT(id) FROM users GROUP BY ip", []); </code> @param string $sql SQL query with placeholders "SELECT ip, id FROM users" @param array $params params for query placeholders (optional) @param mixed $object @return array|false @throws DbException
entailment
public function fetchColumnGroup(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetchAll(\PDO::FETCH_COLUMN | \PDO::FETCH_GROUP); $this->ok(); return $result; }
Returns an array containing all of the result set rows Group by first column @param string $sql SQL query with placeholders "SELECT ip, id FROM users" @param array $params params for query placeholders (optional) @return array|false @throws DbException
entailment
public function fetchUniqueGroup(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetchAll(\PDO::FETCH_UNIQUE | \PDO::FETCH_ASSOC | \PDO::FETCH_GROUP); $this->ok(); return $result; }
Returns an array containing all of the result set rows Group by first unique column @param string $sql SQL query with placeholders "SELECT email, name, sex FROM users" @param array $params params for query placeholders (optional) @return array|false @throws DbException
entailment
public function fetchPairs(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); $this->ok(); return $result; }
Returns a key-value array @param string $sql SQL query with placeholders "SELECT id, username FROM users WHERE ip = :ip" @param array $params params for query placeholders (optional) array (':ip' => '127.0.0.1') @return array|false @throws DbException
entailment
public function fetchObject(string $sql, array $params = [], $object = 'stdClass') { $stmt = $this->prepare($sql, $params); if (is_string($object)) { // some class name $result = $stmt->fetchObject($object); } else { // some instance $stmt->setFetchMode(\PDO::FETCH_INTO, $object); $result = $stmt->fetch(\PDO::FETCH_INTO); } $stmt->closeCursor(); $this->ok(); return $result; }
Returns an object containing first row from the result set Example of usage <code> // Fetch object to stdClass $stdClass = $db->fetchObject('SELECT * FROM some_table WHERE id = ?', [$id]); // Fetch object to new Some object $someClass = $db->fetchObject('SELECT * FROM some_table WHERE id = ?', [$id], 'Some'); // Fetch object to exists instance of Some object $someClass = $db->fetchObject('SELECT * FROM some_table WHERE id = ?', [$id], $someClass); </code> @param string $sql SQL query with placeholders "SELECT * FROM users WHERE name = :name AND pass = :pass" @param array $params params for query placeholders (optional) array (':name' => 'John', ':pass' => '123456') @param mixed $object @return mixed @throws DbException
entailment
public function fetchObjects(string $sql, array $params = [], $object = null) { $stmt = $this->prepare($sql, $params); if (\is_string($object)) { // fetch to some class by name $result = $stmt->fetchAll(\PDO::FETCH_CLASS, $object); } else { // fetch to StdClass $result = $stmt->fetchAll(\PDO::FETCH_OBJ); } $stmt->closeCursor(); $this->ok(); return $result; }
Returns an array of objects containing the result set @param string $sql SQL query with placeholders "SELECT * FROM users WHERE name = :name AND pass = :pass" @param array $params params for query placeholders (optional) array (':name' => 'John', ':pass' => '123456') @param mixed $object Class name or instance @return array|false @throws DbException
entailment
public function fetchRelations(string $sql, array $params = []) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); // prepare results $result = Relations::fetch($result); $stmt->closeCursor(); $this->ok(); return $result; }
Returns an array of linked objects containing the result set @param string $sql SQL query with placeholders "SELECT '__users', u.*, '__users_profile', up.* FROM users u LEFT JOIN users_profile up ON up.userId = u.id WHERE u.name = :name" @param array $params params for query placeholders (optional) array (':name' => 'John') @return array|false @throws DbException
entailment
public function transaction(callable $process) { try { $this->handler()->beginTransaction(); $result = $process(); $this->handler()->commit(); return $result ?? true; } catch (\PDOException $e) { $this->handler()->rollBack(); Logger::error($e->getMessage()); return false; } }
Transaction wrapper Example of usage <code> $db->transaction(function() use ($db) { $db->query("INSERT INTO `table` ..."); $db->query("UPDATE `table` ..."); $db->query("DELETE FROM `table` ..."); }) </code> @param callable $process callable structure - closure function or class with __invoke() method @return mixed|bool @throws DbException
entailment
protected function log(string $sql, array $context = []): void { $sql = str_replace('%', '%%', $sql); $sql = preg_replace('/\?/', '"%s"', $sql, \count($context)); // replace mask by data $log = vsprintf($sql, $context); Logger::info($log); }
Log queries by Application @param string $sql SQL query for logs @param array $context @return void
entailment
public function setSource($source): void { if (!\is_array($source) && !($source instanceof \ArrayAccess)) { throw new Grid\GridException('Source of `ArraySource` should be array or implement ArrayAccess interface'); } parent::setSource($source); }
Set array source @param array $source @return void @throws Grid\GridException
entailment
public function process(int $page, int $limit, array $filters = [], array $orders = []): Data { // process filters $this->applyFilters($filters); // process orders $this->applyOrders($orders); $data = $this->getSource(); $total = \count($data); // process pages $data = \array_slice($data, $limit * ($page - 1), $limit); $gridData = new Data($data); $gridData->setTotal($total); return $gridData; }
{@inheritdoc} @throws Grid\GridException
entailment
private function applyFilters(array $settings): void { $data = $this->getSource(); $data = array_filter( $data, function ($row) use ($settings) { foreach ($settings as $column => $filters) { foreach ($filters as $filter => $value) { // switch statement for filter switch ($filter) { case Grid\Grid::FILTER_EQ: if ($row[$column] != $value) { return false; } break; case Grid\Grid::FILTER_NE: if ($row[$column] == $value) { return false; } break; case Grid\Grid::FILTER_GT: if ($row[$column] <= $value) { return false; } break; case Grid\Grid::FILTER_GE: if ($row[$column] < $value) { return false; } break; case Grid\Grid::FILTER_LT: if ($row[$column] >= $value) { return false; } break; case Grid\Grid::FILTER_LE: if ($row[$column] > $value) { return false; } break; case Grid\Grid::FILTER_LIKE: if (!preg_match('/' . $value . '/', $row[$column])) { return false; } break; } } } return true; } ); $this->setSource($data); }
Apply filters to array @param array $settings @return void @throws Grid\GridException
entailment
private function applyOrders(array $settings): void { $data = $this->getSource(); // Create empty column stack $orders = []; foreach ($settings as $column => $order) { $orders[$column] = []; } // Obtain a list of columns foreach ($data as $key => $row) { foreach ($settings as $column => $order) { $orders[$column][$key] = $row[$column]; } } // Prepare array of arguments $funcArgs = []; foreach ($settings as $column => $order) { $funcArgs[] = $orders[$column]; $funcArgs[] = ($order === Grid\Grid::ORDER_ASC) ? SORT_ASC : SORT_DESC; } $funcArgs[] = &$data; // Sort the data with volume descending, edition ascending // Add $data as the last parameter, to sort by the common key array_multisort(...$funcArgs); $this->setSource($data); }
Apply order to array @param array $settings @return void @throws Grid\GridException
entailment
public function setParams($params): void { if (!\is_array($params) && !\is_object($params)) { throw new EventException( 'Event parameters must be an array or object; received `' . \gettype($params) . '`' ); } $this->params = $params; }
Overwrites parameters @param array|object $params @return void @throws EventException
entailment
public function getParam($name, $default = null) { if (\is_array($this->params)) { // Check in params that are arrays or implement array access return $this->params[$name] ?? $default; } elseif (\is_object($this->params)) { // Check in normal objects return $this->params->{$name} ?? $default; } else { // Wrong type, return default value return $default; } }
Get an individual parameter If the parameter does not exist, the $default value will be returned. @param string|int $name @param mixed $default @return mixed
entailment
public function setParam($name, $value): void { if (\is_array($this->params)) { // Arrays or objects implementing array access $this->params[$name] = $value; } else { // Objects $this->params->{$name} = $value; } }
Set an individual parameter to a value @param string|int $name @param mixed $value @return void
entailment
public function validate($input): bool { // for array if (\is_array($input)) { return \in_array($this->containsValue, $input, false); } // for string if (\is_string($input)) { return false !== mb_stripos($input, $this->containsValue, 0, mb_detect_encoding($input)); } // can't compare return false; }
Check input data @param string|array $input @return bool
entailment
public function validate($input): bool { if (\is_string($input)) { $input = trim($input); } return !empty($input); }
Check input data @param mixed $input @return bool
entailment
public function write($id, $data): bool { return Proxy\Cache::set($this->prepareId($id), $data, $this->ttl); }
Write session data @param string $id @param string $data @return bool @throws \Psr\Cache\InvalidArgumentException
entailment
public function open($savePath, $sessionName): bool { parent::open($savePath, $sessionName); $this->handler = new \Redis(); if ($this->settings['persistence']) { $this->handler->pconnect($this->settings['host'], $this->settings['port'], $this->settings['timeout']); } else { $this->handler->connect($this->settings['host'], $this->settings['port'], $this->settings['timeout']); } if (isset($this->settings['options'])) { foreach ($this->settings['options'] as $key => $value) { $this->handler->setOption($key, $value); } } return true; }
Initialize session @param string $savePath @param string $sessionName @return bool
entailment
public function write($id, $data): bool { return $this->handler->set($this->prepareId($id), $data, (int)$this->ttl); }
Write session data @param string $id @param string $data @return bool
entailment
public function destroy($id): bool { $this->handler->del($this->prepareId($id)); return true; }
Destroy a session @param integer $id @return bool
entailment
protected function updateCacheControlHeader(): void { $parts = []; ksort($this->container); foreach ($this->container as $key => $value) { if (true === $value) { $parts[] = $key; } else { if (preg_match('#[^a-zA-Z0-9._-]#', (string)$value)) { $value = '"' . $value . '"'; } $parts[] = "$key=$value"; } } if (\count($parts)) { $this->response->setHeader('Cache-Control', implode(', ', $parts)); } }
Prepare Cache-Control header @return void
entailment
public function getMaxAge(): ?int { if ($this->doContainsContainer('s-maxage')) { return (int)$this->doGetContainer('s-maxage'); } if ($this->doContainsContainer('max-age')) { return (int)$this->doGetContainer('max-age'); } if ($expires = $this->getExpires()) { $expires = \DateTime::createFromFormat(DATE_RFC2822, $expires); return (int) $expires->format('U') - date('U'); } return null; }
Returns the number of seconds after the time specified in the response's Date header when the response should no longer be considered fresh. First, it checks for a s-maxage directive, then a max-age directive, and then it falls back on an expires header. It returns null when no maximum age can be established. @return integer|null Number of seconds
entailment
public function setSharedMaxAge($value): void { $this->setPublic(); $this->doSetContainer('s-maxage', $value); $this->updateCacheControlHeader(); }
Sets the number of seconds after which the response should no longer be considered fresh by shared caches. This methods sets the Cache-Control s-maxage directive. @param integer $value Number of seconds @return void
entailment
public function setEtag($etag, $weak = false): void { $etag = trim($etag, '"'); $this->response->setHeader('ETag', (true === $weak ? 'W/' : '') . '"' . $etag . '"'); }
Sets the ETag value @param string $etag The ETag unique identifier @param bool $weak Whether you want a weak ETag or not @return void
entailment
public function getAge(): int { if ($age = $this->response->getHeader('Age')) { return (int)$age; } return max(time() - date('U'), 0); }
Returns the age of the response @return integer The age of the response in seconds
entailment
public function setExpires($date): void { if ($date instanceof \DateTime) { $date = clone $date; } else { $date = new \DateTime($date); } $date->setTimezone(new \DateTimeZone('UTC')); $this->response->setHeader('Expires', $date->format('D, d M Y H:i:s') . ' GMT'); }
Sets the Expires HTTP header with a DateTime instance @param \DateTime|string $date A \DateTime instance or date as string @return void
entailment
public function getQuery(): string { $sql = $this->getSql(); $sql = str_replace(['%', '?'], ['%%', '"%s"'], $sql); // replace mask by data return vsprintf($sql, $this->getParams()); }
Return the complete SQL string formed for use Example <code> $sb = new SelectBuilder(); $sb ->select('u') ->from('User', 'u') ->where('id = ?', 42); echo $qb->getQuery(); // SELECT u FROM User u WHERE id = "42" </code> @return string
entailment
public function setParam($key, $value, $type = \PDO::PARAM_STR): self { if (null === $key) { $key = \count($this->params); } $this->params[$key] = $value; $this->types[$key] = $type; return $this; }
Sets a query parameter for the query being constructed Example <code> $sb = new SelectBuilder(); $sb ->select('u') ->from('users', 'u') ->where('u.id = :user_id') ->setParameter(':user_id', 1); </code> @param string|int|null $key The parameter position or name @param mixed $value The parameter value @param integer $type PDO::PARAM_* @return self
entailment
public function setParams(array $params, array $types = []): self { $this->types = $types; $this->params = $params; return $this; }
Sets a collection of query parameters for the query being constructed Example <code> $sb = new SelectBuilder(); $sb ->select('u') ->from('users', 'u') ->where('u.id = :user_id1 OR u.id = :user_id2') ->setParameters([ ':user_id1' => 1, ':user_id2' => 2 ]); </code> @param array $params The query parameters to set @param array $types The query parameters types to set @return self
entailment
protected function prepareCondition(array $args = []): string { $condition = array_shift($args); foreach ($args as &$value) { if (\is_array($value)) { $replace = implode(',', array_fill(0, \count($value), ':REPLACE:')); $condition = preg_replace('/\?/', $replace, $condition, 1); foreach ($value as $part) { $this->setParam(null, $part); } } else { $this->setParam(null, $value); } } unset($value); $condition = preg_replace('/(\:REPLACE\:)/', '?', $condition); return $condition; }
Prepare condition <code> $builder->prepareCondition("WHERE id IN (?)", [..,..]); </code> @param array $args @return string
entailment
public function setSource($source): void { if (!$source instanceof Db\Query\Select) { throw new Grid\GridException('Source of `SelectSource` should be `Db\\Query\\Select` object'); } parent::setSource($source); }
Set Select source @param Db\Query\Select $source @throws Grid\GridException @return void
entailment
public function process(int $page, int $limit, array $filters = [], array $orders = []): Data { // process filters $this->applyFilters($filters); // process orders $this->applyOrders($orders); // process pages $this->getSource()->setLimit($limit); $this->getSource()->setPage($page); // prepare query $type = Proxy\Db::getOption('connect', 'type'); if (strtolower($type) === 'mysql') { // MySQL $selectPart = $this->getSource()->getSelect(); $selectPart[0] = 'SQL_CALC_FOUND_ROWS ' . $selectPart[0]; $this->getSource()->select(...$selectPart); $totalSql = 'SELECT FOUND_ROWS()'; } else { // other $totalSource = clone $this->getSource(); $totalSource->select('COUNT(*)'); $totalSql = $totalSource->getSql(); } $data = []; $total = 0; // run queries // use transaction to avoid errors Proxy\Db::transaction( function () use (&$data, &$total, $totalSql) { $data = $this->source->execute(); $total = (int)Proxy\Db::fetchOne($totalSql); } ); $gridData = new Data($data); $gridData->setTotal($total); return $gridData; }
{@inheritdoc}
entailment
private function applyFilters(array $settings): void { foreach ($settings as $column => $filters) { foreach ($filters as $filter => $value) { if ($filter === Grid\Grid::FILTER_LIKE) { $value = '%' . $value . '%'; } $this->getSource()->andWhere($column . ' ' . $this->filters[$filter] . ' ?', $value); } } }
Apply filters to Select @param array $settings @return void @throws Grid\GridException
entailment
private function applyOrders(array $settings): void { // Obtain a list of columns foreach ($settings as $column => $order) { $this->getSource()->addOrderBy($column, $order); } }
Apply order to Select @param array $settings @return void @throws Grid\GridException
entailment
private static function initInstance(): Instance { $instance = new Instance(); $instance->setOptions(Config::get('translator')); $instance->init(); return $instance; }
Init instance @return Instance @throws \Bluz\Common\Exception\ConfigurationException
entailment
public function validate($input): bool { if ($input instanceof DateTime) { return true; } if (!\is_string($input)) { return false; } if (null === $this->format) { return false !== strtotime($input); } $dateFromFormat = DateTime::createFromFormat($this->format, $input); return $dateFromFormat && $input === date($this->format, $dateFromFormat->getTimestamp()); }
Check input data @param mixed $input @return bool
entailment
public function validate($input): bool { $input = preg_replace('([ \.-])', '', $input); if (!is_numeric($input)) { return false; } return $this->verifyMod10($input); }
Check input data @param string $input @return bool
entailment
private function verifyMod10($input): bool { $sum = 0; $input = strrev($input); $inputLen = \strlen($input); for ($i = 0; $i < $inputLen; $i++) { $current = $input[$i]; if ($i % 2 === 1) { $current *= 2; if ($current > 9) { $firstDigit = $current % 10; $secondDigit = ($current - $firstDigit) / 10; $current = $firstDigit + $secondDigit; } } $sum += $current; } return ($sum % 10 === 0); }
Verify by Mod10 @param string $input @return bool
entailment
public function addNotice($message, ...$text): void { $this->add(self::TYPE_NOTICE, $message, ...$text); }
Add notice @param string $message @param string[] $text @return void @since 1.0.0 added $text
entailment
public function addSuccess($message, ...$text): void { $this->add(self::TYPE_SUCCESS, $message, ...$text); }
Add success @param string $message @param string[] $text @return void @since 1.0.0 added $text
entailment
public function addError($message, ...$text): void { $this->add(self::TYPE_ERROR, $message, ...$text); }
Add error @param string $message @param string[] $text @return void @since 1.0.0 added $text
entailment
protected function add($type, $message, ...$text): void { $this->getMessagesStore()[$type][] = Translator::translate($message, ...$text); }
Add message to container @param string $type One of error, notice or success @param string $message @param string[] $text @return void
entailment
public function pop($type): ?\stdClass { $text = array_shift($this->getMessagesStore()[$type]); if ($text) { $message = new \stdClass(); $message->text = $text; $message->type = $type; return $message; } return null; }
Pop a message by type @param string $type @return \stdClass|null
entailment
public function count(): int { $size = 0; if (!$store = $this->getMessagesStore()) { return $size; } foreach ($store as $messages) { $size += \count($messages); } return $size; }
Get size of messages container @return integer
entailment
public static function getMeta(): array { $self = static::getInstance(); if (empty($self->meta)) { $cacheKey = "db.table.{$self->name}"; $meta = Cache::get($cacheKey); if (!$meta) { $schema = DbProxy::getOption('connect', 'name'); $meta = DbProxy::fetchUniqueGroup( ' SELECT COLUMN_NAME AS `name`, DATA_TYPE AS `type`, COLUMN_DEFAULT AS `default`, COLUMN_KEY AS `key` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?', [$schema, $self->getName()] ); Cache::set($cacheKey, $meta, Cache::TTL_NO_EXPIRY, ['system', 'db']); } $self->meta = $meta; } return $self->meta; }
Return information about table columns @return array
entailment
protected static function fetch($sql, $params = []): array { $self = static::getInstance(); return DbProxy::fetchObjects($sql, $params, $self->rowClass); }
Fetching rows by SQL query @param string $sql SQL query with placeholders @param array $params Params for query placeholders @return RowInterface[] of rows results in FETCH_CLASS mode
entailment
public static function find(...$keys): array { $keyNames = array_values(static::getInstance()->getPrimaryKey()); $whereList = []; foreach ($keys as $keyValues) { $keyValues = (array)$keyValues; if (\count($keyValues) !== \count($keyNames)) { throw new InvalidPrimaryKeyException( "Invalid columns for the primary key.\n" . "Please check " . static::class . " initialization or usage.\n" . "Settings described at https://github.com/bluzphp/framework/wiki/Db-Table" ); } if (array_keys($keyValues)[0] === 0) { // for numerical array $whereList[] = array_combine($keyNames, $keyValues); } else { // for assoc array $whereList[] = $keyValues; } } return static::findWhere(...$whereList); }
{@inheritdoc} @throws DbException @throws InvalidPrimaryKeyException if wrong count of values passed @throws \InvalidArgumentException
entailment
public static function findWhere(...$where): array { $self = static::getInstance(); $whereParams = []; if (\count($where) === 2 && \is_string($where[0])) { $whereClause = $where[0]; $whereParams = (array)$where[1]; } elseif (\count($where)) { $whereOrTerms = []; foreach ($where as $keyValueSets) { $whereAndTerms = []; foreach ($keyValueSets as $keyName => $keyValue) { if (\is_array($keyValue)) { $keyValue = array_map( function ($value) { return DbProxy::quote($value); }, $keyValue ); $keyValue = implode(',', $keyValue); $whereAndTerms[] = $self->name . '.' . $keyName . ' IN (' . $keyValue . ')'; } elseif (null === $keyValue) { $whereAndTerms[] = $self->name . '.' . $keyName . ' IS NULL'; } elseif ('%' === $keyValue{0} || '%' === $keyValue{-1}) { $whereAndTerms[] = $self->name . '.' . $keyName . ' LIKE ?'; $whereParams[] = $keyValue; } else { $whereAndTerms[] = $self->name . '.' . $keyName . ' = ?'; $whereParams[] = $keyValue; } if (!is_scalar($keyValue) && !is_null($keyValue)) { throw new \InvalidArgumentException( "Wrong arguments of method 'findWhere'.\n" . "Please use syntax described at https://github.com/bluzphp/framework/wiki/Db-Table" ); } } $whereOrTerms[] = '(' . implode(' AND ', $whereAndTerms) . ')'; } $whereClause = '(' . implode(' OR ', $whereOrTerms) . ')'; } else { throw new DbException( "Method `Table::findWhere()` can't return all records from table" ); } return self::fetch($self->select . ' WHERE ' . $whereClause, $whereParams); }
{@inheritdoc} @throws \InvalidArgumentException @throws Exception\DbException
entailment
private static function prepareStatement(array $where): array { $keys = array_keys($where); foreach ($keys as &$key) { $key = DbProxy::quoteIdentifier($key) . ' = ?'; } return $keys; }
Prepare array for WHERE or SET statements @param array $where @return array
entailment
public static function select(): Query\Select { $self = static::getInstance(); $select = new Query\Select(); $select->select(DbProxy::quoteIdentifier($self->name) . '.*') ->from($self->name, $self->name) ->setFetchType($self->rowClass); return $select; }
Prepare Db\Query\Select for current table: - predefine "select" section as "*" from current table - predefine "from" section as current table name and first letter as alias - predefine fetch type <code> // use default select "*" $select = Users\Table::select(); $arrUsers = $select->where('u.id = ?', $id) ->execute(); // setup custom select "u.id, u.login" $select = Users\Table::select(); $arrUsers = $select->select('u.id, u.login') ->where('u.id = ?', $id) ->execute(); </code> @return Query\Select
entailment
public static function create(array $data = []): RowInterface { $rowClass = static::getInstance()->rowClass; /** @var Row $row */ $row = new $rowClass($data); $row->setTable(static::getInstance()); return $row; }
{@inheritdoc}
entailment
public static function insert(array $data) { $self = static::getInstance(); $data = static::filterColumns($data); if (!\count($data)) { throw new DbException( "Invalid field names of table `{$self->name}`. Please check use of `insert()` method" ); } $table = DbProxy::quoteIdentifier($self->name); $sql = "INSERT INTO $table SET " . implode(',', self::prepareStatement($data)); $result = DbProxy::query($sql, array_values($data)); if (!$result) { return null; } /** * If a sequence name was not specified for the name parameter, PDO::lastInsertId() * returns a string representing the row ID of the last row that was inserted into the database. * * If a sequence name was specified for the name parameter, PDO::lastInsertId() * returns a string representing the last value retrieved from the specified sequence object. * * If the PDO driver does not support this capability, PDO::lastInsertId() triggers an IM001 SQLSTATE. */ return DbProxy::handler()->lastInsertId($self->sequence); }
{@inheritdoc} @throws Exception\DbException
entailment
public static function update(array $data, array $where): int { $self = static::getInstance(); $data = static::filterColumns($data); if (!\count($data)) { throw new DbException( "Invalid field names of table `{$self->name}`. Please check use of `update()` method" ); } $where = static::filterColumns($where); if (!\count($where)) { throw new DbException( "Method `Table::update()` can't update all records in the table `{$self->name}`,\n" . "please use `Db::query()` instead (of cause if you know what are you doing)" ); } $table = DbProxy::quoteIdentifier($self->name); $sql = "UPDATE $table SET " . implode(',', self::prepareStatement($data)) . " WHERE " . implode(' AND ', self::prepareStatement($where)); return DbProxy::query($sql, array_merge(array_values($data), array_values($where))); }
{@inheritdoc} @throws Exception\DbException
entailment
public static function delete(array $where): int { $self = static::getInstance(); if (!\count($where)) { throw new DbException( "Method `Table::delete()` can't delete all records in the table `{$self->name}`,\n" . "please use `Db::query()` instead (of cause if you know what are you doing)" ); } $where = static::filterColumns($where); if (!\count($where)) { throw new DbException( "Invalid field names of table `{$self->name}`. Please check use of `delete()` method" ); } $table = DbProxy::quoteIdentifier($self->name); $sql = "DELETE FROM $table WHERE " . implode(' AND ', self::prepareStatement($where)); return DbProxy::query($sql, array_values($where)); }
{@inheritdoc} @throws \Bluz\Db\Exception\DbException
entailment
public function setPath($path): void { if (!is_dir($path)) { throw new ConfigException('Configuration directory is not exists'); } $this->path = rtrim($path, '/'); }
Set path to configuration files @param string $path @return void @throws ConfigException
entailment
public function load(): void { if (!$this->path) { throw new ConfigException('Configuration directory is not setup'); } $this->config = $this->loadFiles($this->path . '/configs/default'); if ($this->environment) { $customConfig = $this->loadFiles($this->path . '/configs/' . $this->environment); $this->config = array_replace_recursive($this->config, $customConfig); } }
Load configuration @return void @throws ConfigException
entailment
protected function loadFiles($path): array { $config = []; if (!is_dir($path)) { throw new ConfigException("Configuration directory `$path` not found"); } $iterator = new \GlobIterator( $path . '/*.php', \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_PATHNAME ); foreach ($iterator as $name => $file) { $name = substr($name, 0, -4); $config[$name] = $this->loadFile($file); } return $config; }
Load configuration files to array @param string $path @return array @throws ConfigException
entailment
public function getLoginUrl($clientId, $redirectUri, $responseType = "code", $scope = "https://cloud.feedly.com/subscriptions") { return ($this->apiMode->getApiBaseUrl() . $this->authorizePath . "?" . http_build_query(array( "client_id" => $clientId, "redirect_uri" => $redirectUri, "response_type" => $responseType, "scope" => $scope ) ) ); }
Return authorization URL @param string $clientId Client's ID provided by Feedly's Administrators @param string $redirectUri Endpoint to reroute with the results @param string $responseType @param string $scope @return string Authorization URL
entailment
public function getTokens($clientId, $clientSecret, $authCode, $redirectUrl) { $this->client = new HTTPClient(); $this->client->setCustomHeader(array( "Authorization: Basic " . base64_encode($clientId . ":" . $clientSecret), )); $this->client->setPostParams(array( "code" => urlencode($authCode), "client_id" => urlencode($clientId), "client_secret" => urlencode($clientSecret), "redirect_uri" => $redirectUrl, "grant_type" => "authorization_code" ) , false); $response = new AccessTokenResponse( $this->client->post($this->apiMode->getApiBaseUrl() . $this->accessTokenPath) ); $this->accessTokenStorage->store($response); return $response; }
Exchange a `code` from `getLoginUrl` for `Access` and `Refresh` Tokens @param string $clientId Client's ID provided by Feedly's Administrators @param string $clientSecret Client's Secret provided by Feedly's Administrators @param string $authCode Code obtained from `getLoginUrl` @param string $redirectUrl Endpoint to reroute with the results @return AccessTokenResponse
entailment
protected function createPdoInstance() { //Empty attributes property cases exception in Yajra\Pdo\Oci8::__construct() method if (!is_array($this->attributes)) $this->attributes = []; try { return parent::createPdoInstance(); } catch(PDOException $e) { throw $e; } }
Creates the PDO instance from Yajra\Pdo\Oci8 component @exception PDOException @return \PDO the pdo instance
entailment
public function getDbh() { $prop = (new ReflectionClass($this->pdoClass))->getProperty('dbh'); $prop->setAccessible(true); return $prop->getValue($this->masterPdo); }
Returns private database handler from the OCI8 PDO class instance @return resource Oci8 resource handler
entailment
public function getSchema() { if ($this->cachedSchema === null) { return parent::getSchema(); } else { if (is_object($this->cachedSchema)) return $this->cachedSchema; else if (is_array($this->cachedSchema)) { $this->cachedSchema['db'] = $this; $this->cachedSchema = \Yii::createObject($this->cachedSchema); //$this->cachedSchema = new CachedSchema(['db' => $this]); return $this->cachedSchema; } else { throw new ConfigurationException('The "cachedSchema" property must be an configuration array'); } } }
Returns the schema information for the database opened by this connection. @return \yii\db\Schema|\neconix\yii2oci8\CachedSchema Schema the schema information for the database opened by this connection. @throws NotSupportedException NotSupportedException if there is no support for the current driver type @throws ConfigurationException
entailment
public function validate($input): bool { if (\is_string($input) && filter_var($input, FILTER_VALIDATE_EMAIL)) { [, $domain] = explode('@', $input, 2); if ($this->checkDns) { return checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A'); } return true; } return false; }
Check input data @param mixed $input @return bool
entailment
public function hasPrivilege($module, $privilege): bool { $privileges = $this->getPrivileges(); return \in_array("$module:$privilege", $privileges, true); }
{@inheritdoc}
entailment
public static function rule($ruleName, $arguments): RuleInterface { $ruleName = ucfirst($ruleName) . 'Rule'; foreach (static::$rulesNamespaces as $ruleNamespace) { $ruleClass = $ruleNamespace . $ruleName; if (class_exists($ruleClass)) { return new $ruleClass(...$arguments); } } throw new ComponentException("Class for validator `$ruleName` not found"); }
Create new rule by name @param string $ruleName @param array $arguments @return RuleInterface @throws Exception\ComponentException
entailment
public function validate($input): bool { if (!$length = $this->extractLength($input)) { return false; } return (null === $this->minValue || $this->less($this->minValue, $length)) && (null === $this->maxValue || $this->less($length, $this->maxValue)); }
Check input data @param string $input @return bool
entailment
public function getDescription(): string { if (!$this->minValue) { return __('must have a length lower than "%d"', $this->maxValue); } if (!$this->maxValue) { return __('must have a length greater than "%d"', $this->minValue); } if ($this->minValue === $this->maxValue) { return __('must have a length "%d"', $this->minValue); } return __('must have a length between "%d" and "%d"', $this->minValue, $this->maxValue); }
Get error template @return string
entailment
public function attach($eventName, $callback, $priority = 1): void { if (!isset($this->listeners[$eventName])) { $this->listeners[$eventName] = []; } if (!isset($this->listeners[$eventName][$priority])) { $this->listeners[$eventName][$priority] = []; } $this->listeners[$eventName][$priority][] = $callback; }
Attach callback to event @param string $eventName @param callable $callback @param integer $priority @return void
entailment