code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public static function encode($value, $options = 320)
{
$expressions = [];
$value = static::processData($value, $expressions, uniqid('', true));
set_error_handler(function () {
static::handleJsonError(JSON_ERROR_SYNTAX);
}, E_WARNING);
if (static::$prettyPrint === true) {
$options |= JSON_PRETTY_PRINT;
} elseif (static::$prettyPrint === false) {
$options &= ~JSON_PRETTY_PRINT;
}
$json = json_encode($value, $options);
restore_error_handler();
static::handleJsonError(json_last_error());
return $expressions === [] ? $json : strtr($json, $expressions);
} | Encodes the given value into a JSON string.
The method enhances `json_encode()` by supporting JavaScript expressions.
In particular, the method will not encode a JavaScript expression that is
represented in terms of a [[JsExpression]] object.
Note that data encoded as JSON must be UTF-8 encoded according to the JSON specification.
You must ensure strings passed to this method have proper encoding before passing them.
@param mixed $value the data to be encoded.
@param int $options the encoding options. For more details please refer to
<https://www.php.net/manual/en/function.json-encode.php>. Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
@return string the encoding result.
@throws InvalidArgumentException if there is any encoding error. | encode | php | yiisoft/yii2 | framework/helpers/BaseJson.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseJson.php | BSD-3-Clause |
protected static function handleJsonError($lastError)
{
if ($lastError === JSON_ERROR_NONE) {
return;
}
if (PHP_VERSION_ID >= 50500) {
throw new InvalidArgumentException(json_last_error_msg(), $lastError);
}
foreach (static::$jsonErrorMessages as $const => $message) {
if (defined($const) && constant($const) === $lastError) {
throw new InvalidArgumentException($message, $lastError);
}
}
throw new InvalidArgumentException('Unknown JSON encoding/decoding error.');
} | Handles [[encode()]] and [[decode()]] errors by throwing exceptions with the respective error message.
@param int $lastError error code from [json_last_error()](https://www.php.net/manual/en/function.json-last-error.php).
@throws InvalidArgumentException if there is any encoding/decoding error.
@since 2.0.6 | handleJsonError | php | yiisoft/yii2 | framework/helpers/BaseJson.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseJson.php | BSD-3-Clause |
public static function localize($file, $language = null, $sourceLanguage = null)
{
if ($language === null) {
$language = Yii::$app->language;
}
if ($sourceLanguage === null) {
$sourceLanguage = Yii::$app->sourceLanguage;
}
if ($language === $sourceLanguage) {
return $file;
}
$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
if (is_file($desiredFile)) {
return $desiredFile;
}
$language = substr($language, 0, 2);
if ($language === $sourceLanguage) {
return $file;
}
$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
return is_file($desiredFile) ? $desiredFile : $file;
} | Returns the localized version of a specified file.
The searching is based on the specified language code. In particular,
a file with the same name will be looked for under the subdirectory
whose name is the same as the language code. For example, given the file "path/to/view.php"
and language code "zh-CN", the localized file will be looked for as
"path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
"zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
If the target and the source language codes are the same, the original file will be returned.
@param string $file the original file
@param string|null $language the target language that the file should be localized to.
If not set, the value of [[\yii\base\Application::language]] will be used.
@param string|null $sourceLanguage the language that the original file is in.
If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
@return string the matching localized file, or the original file if the localized version is not found.
If the target and the source language codes are the same, the original file will be returned. | localize | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function getMimeType($file, $magicFile = null, $checkExtension = true)
{
if ($magicFile !== null) {
$magicFile = Yii::getAlias($magicFile);
}
if (!extension_loaded('fileinfo')) {
if ($checkExtension) {
return static::getMimeTypeByExtension($file, $magicFile);
}
throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
}
$info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
if ($info) {
$result = finfo_file($info, $file);
finfo_close($info);
if ($result !== false) {
return $result;
}
}
return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
} | Determines the MIME type of the specified file.
This method will first try to determine the MIME type based on
[finfo_open](https://www.php.net/manual/en/function.finfo-open.php). If the `fileinfo` extension is not installed,
it will fall back to [[getMimeTypeByExtension()]] when `$checkExtension` is true.
@param string $file the file name.
@param string|null $magicFile name of the optional magic database file (or alias), usually something like `/path/to/magic.mime`.
This will be passed as the second parameter to [finfo_open()](https://www.php.net/manual/en/function.finfo-open.php)
when the `fileinfo` extension is installed. If the MIME type is being determined based via [[getMimeTypeByExtension()]]
and this is null, it will use the file specified by [[mimeMagicFile]].
@param bool $checkExtension whether to use the file extension to determine the MIME type in case
`finfo_open()` cannot determine it.
@return string|null the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined.
@throws InvalidConfigException when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`. | getMimeType | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function getMimeTypeByExtension($file, $magicFile = null)
{
$mimeTypes = static::loadMimeTypes($magicFile);
if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
$ext = strtolower($ext);
if (isset($mimeTypes[$ext])) {
return $mimeTypes[$ext];
}
}
return null;
} | Determines the MIME type based on the extension name of the specified file.
This method will use a local map between extension names and MIME types.
@param string $file the file name.
@param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
If this is not set, the file specified by [[mimeMagicFile]] will be used.
@return string|null the MIME type. Null is returned if the MIME type cannot be determined. | getMimeTypeByExtension | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function getExtensionsByMimeType($mimeType, $magicFile = null)
{
$aliases = static::loadMimeAliases(static::$mimeAliasesFile);
if (isset($aliases[$mimeType])) {
$mimeType = $aliases[$mimeType];
}
// Note: For backwards compatibility the "MimeTypes" file is used.
$mimeTypes = static::loadMimeTypes($magicFile);
return array_keys($mimeTypes, mb_strtolower($mimeType, 'UTF-8'), true);
} | Determines the extensions by given MIME type.
This method will use a local map between extension names and MIME types.
@param string $mimeType file MIME type.
@param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
If this is not set, the file specified by [[mimeMagicFile]] will be used.
@return array the extensions corresponding to the specified MIME type | getExtensionsByMimeType | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function getExtensionByMimeType($mimeType, $preferShort = false, $magicFile = null)
{
$aliases = static::loadMimeAliases(static::$mimeAliasesFile);
if (isset($aliases[$mimeType])) {
$mimeType = $aliases[$mimeType];
}
$mimeExtensions = static::loadMimeExtensions($magicFile);
if (!array_key_exists($mimeType, $mimeExtensions)) {
return null;
}
$extensions = $mimeExtensions[$mimeType];
if (is_array($extensions)) {
if ($preferShort) {
foreach ($extensions as $extension) {
if (mb_strlen($extension, 'UTF-8') <= 3) {
return $extension;
}
}
}
return $extensions[0];
} else {
return $extensions;
}
} | Determines the most common extension by given MIME type.
This method will use a local map between MIME types and extension names.
@param string $mimeType file MIME type.
@param bool $preferShort return an extension with a maximum of 3 characters.
@param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
If this is not set, the file specified by [[mimeMagicFile]] will be used.
@return string|null the extensions corresponding to the specified MIME type
@since 2.0.48 | getExtensionByMimeType | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
protected static function loadMimeTypes($magicFile)
{
if ($magicFile === null) {
$magicFile = static::$mimeMagicFile;
}
$magicFile = Yii::getAlias($magicFile);
if (!isset(self::$_mimeTypes[$magicFile])) {
self::$_mimeTypes[$magicFile] = require $magicFile;
}
return self::$_mimeTypes[$magicFile];
} | Loads MIME types from the specified file.
@param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
If this is not set, the file specified by [[mimeMagicFile]] will be used.
@return array the mapping from file extensions to MIME types | loadMimeTypes | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
protected static function loadMimeAliases($aliasesFile)
{
if ($aliasesFile === null) {
$aliasesFile = static::$mimeAliasesFile;
}
$aliasesFile = Yii::getAlias($aliasesFile);
if (!isset(self::$_mimeAliases[$aliasesFile])) {
self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
}
return self::$_mimeAliases[$aliasesFile];
} | Loads MIME aliases from the specified file.
@param string|null $aliasesFile the path (or alias) of the file that contains MIME type aliases.
If this is not set, the file specified by [[mimeAliasesFile]] will be used.
@return array the mapping from file extensions to MIME types
@since 2.0.14 | loadMimeAliases | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
protected static function loadMimeExtensions($extensionsFile)
{
if ($extensionsFile === null) {
$extensionsFile = static::$mimeExtensionsFile;
}
$extensionsFile = Yii::getAlias($extensionsFile);
if (!isset(self::$_mimeExtensions[$extensionsFile])) {
self::$_mimeExtensions[$extensionsFile] = require $extensionsFile;
}
return self::$_mimeExtensions[$extensionsFile];
} | Loads MIME extensions from the specified file.
@param string|null $extensionsFile the path (or alias) of the file that contains MIME type aliases.
If this is not set, the file specified by [[mimeAliasesFile]] will be used.
@return array the mapping from file extensions to MIME types
@since 2.0.48 | loadMimeExtensions | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function removeDirectory($dir, $options = [])
{
if (!is_dir($dir)) {
return;
}
if (!empty($options['traverseSymlinks']) || !is_link($dir)) {
if (!($handle = opendir($dir))) {
return;
}
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
static::removeDirectory($path, $options);
} else {
static::unlink($path);
}
}
closedir($handle);
}
if (is_link($dir)) {
static::unlink($dir);
} else {
rmdir($dir);
}
} | Removes a directory (and all its content) recursively.
@param string $dir the directory to be deleted recursively.
@param array $options options for directory remove. Valid options are:
- traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
Only symlink would be removed in that default case.
@throws ErrorException in case of failure | removeDirectory | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function unlink($path)
{
$isWindows = DIRECTORY_SEPARATOR === '\\';
if (!$isWindows) {
return unlink($path);
}
if (is_link($path) && is_dir($path)) {
return rmdir($path);
}
try {
return unlink($path);
} catch (ErrorException $e) {
// last resort measure for Windows
if (is_dir($path) && count(static::findFiles($path)) !== 0) {
return false;
}
if (function_exists('exec') && file_exists($path)) {
exec('DEL /F/Q ' . escapeshellarg($path));
return !file_exists($path);
}
return false;
}
} | Removes a file or symlink in a cross-platform way
@param string $path
@return bool
@since 2.0.14 | unlink | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function findDirectories($dir, $options = [])
{
$dir = self::clearDir($dir);
$options = self::setBasePath($dir, $options);
$list = [];
$handle = self::openDir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path) && static::filterPath($path, $options)) {
$list[] = $path;
if (!isset($options['recursive']) || $options['recursive']) {
$list = array_merge($list, static::findDirectories($path, $options));
}
}
}
closedir($handle);
return $list;
} | Returns the directories found under the specified directory and subdirectories.
@param string $dir the directory under which the files will be looked for.
@param array $options options for directory searching. Valid options are:
- `filter`: callback, a PHP callback that is called for each directory or file.
The signature of the callback should be: `function (string $path): bool`, where `$path` refers
the full path to be filtered. The callback can return one of the following values:
* `true`: the directory will be returned
* `false`: the directory will NOT be returned
- `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
See [[findFiles()]] for more options.
@return array directories found under the directory, in no particular order. Ordering depends on the files system used.
@throws InvalidArgumentException if the dir is invalid.
@since 2.0.14 | findDirectories | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function filterPath($path, $options)
{
if (isset($options['filter'])) {
$result = call_user_func($options['filter'], $path);
if (is_bool($result)) {
return $result;
}
}
if (empty($options['except']) && empty($options['only'])) {
return true;
}
$path = str_replace('\\', '/', $path);
if (
!empty($options['except'])
&& ($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null
) {
return $except['flags'] & self::PATTERN_NEGATIVE;
}
if (!empty($options['only']) && !is_dir($path)) {
return self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only']) !== null;
}
return true;
} | Checks if the given file path satisfies the filtering options.
@param string $path the path of the file or directory to be checked
@param array $options the filtering options. See [[findFiles()]] for explanations of
the supported options.
@return bool whether the file or directory satisfies the filtering options. | filterPath | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function createDirectory($path, $mode = 0775, $recursive = true)
{
if (is_dir($path)) {
return true;
}
$parentDir = dirname($path);
// recurse if parent dir does not exist and we are not at the root of the file system.
if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
static::createDirectory($parentDir, $mode, true);
}
try {
if (!mkdir($path, $mode)) {
return false;
}
} catch (\Exception $e) {
if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
}
}
try {
return chmod($path, $mode);
} catch (\Exception $e) {
throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
}
} | Creates a new directory.
This method is similar to the PHP `mkdir()` function except that
it uses `chmod()` to set the permission of the created directory
in order to avoid the impact of the `umask` setting.
@param string $path path of the directory to be created.
@param int $mode the permission to be set for the created directory.
@param bool $recursive whether to create parent directories if they do not exist.
@return bool whether the directory is created successfully
@throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes) | createDirectory | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
{
// match with FNM_PATHNAME; the pattern has base implicitly in front of it.
if (strncmp($pattern, '/', 1) === 0) {
$pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
if ($firstWildcard !== false && $firstWildcard !== 0) {
$firstWildcard--;
}
}
$namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
$name = StringHelper::byteSubstr($path, -$namelen, $namelen);
if ($firstWildcard !== 0) {
if ($firstWildcard === false) {
$firstWildcard = StringHelper::byteLength($pattern);
}
// if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
if ($firstWildcard > $namelen) {
return false;
}
if (strncmp($pattern, $name, $firstWildcard)) {
return false;
}
$pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
$name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
// If the whole pattern did not have a wildcard, then our prefix match is all we need; we do not need to call fnmatch at all.
if (empty($pattern) && empty($name)) {
return true;
}
}
$matchOptions = [
'filePath' => true
];
if ($flags & self::PATTERN_CASE_INSENSITIVE) {
$matchOptions['caseSensitive'] = false;
}
return StringHelper::matchWildcard($pattern, $name, $matchOptions);
} | Compares a path part against a pattern with optional wildcards.
Based on match_pathname() from dir.c of git 1.8.5.3 sources.
@param string $path full path to compare
@param string $basePath base of path that will not be compared
@param string $pattern the pattern that path part will be compared against
@param int|bool $firstWildcard location of first wildcard character in the $pattern
@param int $flags pattern flags
@return bool whether the path part matches against pattern | matchPathname | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
{
foreach (array_reverse($excludes) as $exclude) {
if (is_string($exclude)) {
$exclude = self::parseExcludePattern($exclude, false);
}
if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
throw new InvalidArgumentException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
}
if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
continue;
}
if ($exclude['flags'] & self::PATTERN_NODIR) {
if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
return $exclude;
}
continue;
}
if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
return $exclude;
}
}
return null;
} | Scan the given exclude list in reverse to see whether pathname
should be ignored. The first match (i.e. the last on the list), if
any, determines the fate. Returns the element which
matched, or null for undecided.
Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
@param string $basePath
@param string $path
@param array $excludes list of patterns to match $path against
@return array|null null or one of $excludes item as an array with keys: 'pattern', 'flags'
@throws InvalidArgumentException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard. | lastExcludeMatchingFromList | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
private static function parseExcludePattern($pattern, $caseSensitive)
{
if (!is_string($pattern)) {
throw new InvalidArgumentException('Exclude/include pattern must be a string.');
}
$result = [
'pattern' => $pattern,
'flags' => 0,
'firstWildcard' => false,
];
if (!$caseSensitive) {
$result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
}
if (empty($pattern)) {
return $result;
}
if (strncmp($pattern, '!', 1) === 0) {
$result['flags'] |= self::PATTERN_NEGATIVE;
$pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
}
if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
$pattern = StringHelper::byteSubstr($pattern, 0, -1);
$result['flags'] |= self::PATTERN_MUSTBEDIR;
}
if (strpos($pattern, '/') === false) {
$result['flags'] |= self::PATTERN_NODIR;
}
$result['firstWildcard'] = self::firstWildcardInPattern($pattern);
if (strncmp($pattern, '*', 1) === 0 && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
$result['flags'] |= self::PATTERN_ENDSWITH;
}
$result['pattern'] = $pattern;
return $result;
} | Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
@param string $pattern
@param bool $caseSensitive
@return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard
@throws InvalidArgumentException | parseExcludePattern | php | yiisoft/yii2 | framework/helpers/BaseFileHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php | BSD-3-Clause |
public static function byteSubstr($string, $start, $length = null)
{
if ($length === null) {
$length = static::byteLength($string);
}
return mb_substr((string)$string, $start, $length, '8bit');
} | Returns the portion of string specified by the start and length parameters.
This method ensures the string is treated as a byte array by using `mb_substr()`.
@param string $string the input string. Must be one character or longer.
@param int $start the starting position
@param int|null $length the desired portion length. If not specified or `null`, there will be
no limit on length i.e. the output will be until the end of the string.
@return string the extracted part of string, or FALSE on failure or an empty string.
@see https://www.php.net/manual/en/function.substr.php | byteSubstr | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function basename($path, $suffix = '')
{
$path = (string)$path;
$len = mb_strlen($suffix);
if ($len > 0 && mb_substr($path, -$len) === $suffix) {
$path = mb_substr($path, 0, -$len);
}
$path = rtrim(str_replace('\\', '/', $path), '/');
$pos = mb_strrpos($path, '/');
if ($pos !== false) {
return mb_substr($path, $pos + 1);
}
return $path;
} | Returns the trailing name component of a path.
This method is similar to the php function `basename()` except that it will
treat both \ and / as directory separators, independent of the operating system.
This method was mainly created to work on php namespaces. When working with real
file paths, php's `basename()` should work fine for you.
Note: this method is not aware of the actual filesystem, or path components such as "..".
@param string $path A path string.
@param string $suffix If the name component ends in suffix this will also be cut off.
@return string the trailing name component of the given path.
@see https://www.php.net/manual/en/function.basename.php | basename | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function dirname($path)
{
$normalizedPath = rtrim(
str_replace('\\', '/', (string)$path),
'/'
);
$separatorPosition = mb_strrpos($normalizedPath, '/');
if ($separatorPosition !== false) {
return mb_substr($path, 0, $separatorPosition);
}
return '';
} | Returns parent directory's path.
This method is similar to `dirname()` except that it will treat
both \ and / as directory separators, independent of the operating system.
@param string $path A path string.
@return string the parent directory's path.
@see https://www.php.net/manual/en/function.basename.php | dirname | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
{
$string = (string)$string;
if ($encoding === null) {
$encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
}
if ($asHtml) {
return static::truncateHtml($string, $length, $suffix, $encoding);
}
if (mb_strlen($string, $encoding) > $length) {
return rtrim(mb_substr($string, 0, $length, $encoding)) . $suffix;
}
return $string;
} | Truncates a string to the number of characters specified.
In order to truncate for an exact length, the $suffix char length must be counted towards the $length. For example
to have a string which is exactly 255 long with $suffix `...` of 3 chars, then `StringHelper::truncate($string, 252, '...')`
must be used to ensure you have 255 long string afterwards.
@param string $string The string to truncate.
@param int $length How many characters from original string to include into truncated string.
@param string $suffix String to append to the end of truncated string.
@param string|null $encoding The charset to use, defaults to charset currently used by application.
@param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
This parameter is available since version 2.0.1.
@return string the truncated string. | truncate | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function startsWith($string, $with, $caseSensitive = true)
{
$string = (string)$string;
$with = (string)$with;
if (!$bytes = static::byteLength($with)) {
return true;
}
if ($caseSensitive) {
return strncmp($string, $with, $bytes) === 0;
}
$encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
$string = static::byteSubstr($string, 0, $bytes);
return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
} | Check if given string starts with specified substring. Binary and multibyte safe.
@param string $string Input string
@param string $with Part to search inside the $string
@param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, `$with` must
exactly match the starting of the string in order to get a true value.
@return bool Returns true if first input starts with second input, false otherwise | startsWith | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function endsWith($string, $with, $caseSensitive = true)
{
$string = (string)$string;
$with = (string)$with;
if (!$bytes = static::byteLength($with)) {
return true;
}
if ($caseSensitive) {
// Warning check, see https://php.net/substr-compare#refsect1-function.substr-compare-returnvalues
if (static::byteLength($string) < $bytes) {
return false;
}
return substr_compare($string, $with, -$bytes, $bytes) === 0;
}
$encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
$string = static::byteSubstr($string, -$bytes);
return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
} | Check if given string ends with specified substring. Binary and multibyte safe.
@param string $string Input string to check
@param string $with Part to search inside of the `$string`.
@param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, `$with` must
exactly match the ending of the string in order to get a true value.
@return bool Returns true if first input ends with second input, false otherwise | endsWith | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function mb_ucfirst($string, $encoding = 'UTF-8')
{
$firstChar = mb_substr((string)$string, 0, 1, $encoding);
$rest = mb_substr((string)$string, 1, null, $encoding);
return mb_strtoupper($firstChar, $encoding) . $rest;
} | This method provides a unicode-safe implementation of built-in PHP function `ucfirst()`.
@param string $string the string to be proceeded
@param string $encoding Optional, defaults to "UTF-8"
@return string
@see https://www.php.net/manual/en/function.ucfirst.php
@since 2.0.16
@phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps | mb_ucfirst | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function mask($string, $start, $length, $mask = '*')
{
$strLength = mb_strlen($string, 'UTF-8');
// Return original string if start position is out of bounds
if ($start >= $strLength || $start < -$strLength) {
return $string;
}
$masked = mb_substr($string, 0, $start, 'UTF-8');
$masked .= str_repeat($mask, abs($length));
$masked .= mb_substr($string, $start + abs($length), null, 'UTF-8');
return $masked;
} | Masks a portion of a string with a repeated character.
This method is multibyte-safe.
@param string $string The input string.
@param int $start The starting position from where to begin masking.
This can be a positive or negative integer.
Positive values count from the beginning,
negative values count from the end of the string.
@param int $length The length of the section to be masked.
The masking will start from the $start position
and continue for $length characters.
@param string $mask The character to use for masking. The default is '*'.
@return string The masked string. | mask | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function findBetween($string, $start, $end)
{
$startPos = mb_strpos($string, $start);
if ($startPos === false) {
return null;
}
$startPos += mb_strlen($start);
$endPos = mb_strrpos($string, $end, $startPos);
if ($endPos === false) {
return null;
}
return mb_substr($string, $startPos, $endPos - $startPos);
} | Returns the portion of the string that lies between the first occurrence of the start string
and the last occurrence of the end string after that.
@param string $string The input string.
@param string $start The string marking the start of the portion to extract.
@param string $end The string marking the end of the portion to extract.
@return string|null The portion of the string between the first occurrence of
start and the last occurrence of end, or null if either start or end cannot be found. | findBetween | php | yiisoft/yii2 | framework/helpers/BaseStringHelper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php | BSD-3-Clause |
public static function process($markdown, $flavor = null)
{
$parser = static::getParser($flavor);
return $parser->parse($markdown);
} | Converts markdown into HTML.
@param string $markdown the markdown text to parse
@param string|null $flavor the markdown flavor to use. See [[$flavors]] for available values.
Defaults to [[$defaultFlavor]], if not set.
@return string the parsed HTML output
@throws InvalidArgumentException when an undefined flavor is given. | process | php | yiisoft/yii2 | framework/helpers/BaseMarkdown.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseMarkdown.php | BSD-3-Clause |
public static function processParagraph($markdown, $flavor = null)
{
$parser = static::getParser($flavor);
return $parser->parseParagraph($markdown);
} | Converts markdown into HTML but only parses inline elements.
This can be useful for parsing small comments or description lines.
@param string $markdown the markdown text to parse
@param string|null $flavor the markdown flavor to use. See [[$flavors]] for available values.
Defaults to [[$defaultFlavor]], if not set.
@return string the parsed HTML output
@throws InvalidArgumentException when an undefined flavor is given. | processParagraph | php | yiisoft/yii2 | framework/helpers/BaseMarkdown.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseMarkdown.php | BSD-3-Clause |
public static function ensureScheme($url, $scheme)
{
if (static::isRelative($url) || !is_string($scheme)) {
return $url;
}
if (strncmp($url, '//', 2) === 0) {
// e.g. //example.com/path/to/resource
return $scheme === '' ? $url : "$scheme:$url";
}
if (($pos = strpos($url, '://')) !== false) {
if ($scheme === '') {
$url = substr($url, $pos + 1);
} else {
$url = $scheme . substr($url, $pos);
}
}
return $url;
} | Normalize the URL by ensuring it uses specified scheme.
If the URL is relative or the scheme is not a string, normalization is skipped.
@param string $url the URL to process
@param string $scheme the URI scheme used in the URL (e.g. `http` or `https`). Use an empty string to
create protocol-relative URL (e.g. `//example.com/path`)
@return string the processed URL
@since 2.0.11 | ensureScheme | php | yiisoft/yii2 | framework/helpers/BaseUrl.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseUrl.php | BSD-3-Clause |
public static function dump($var, $depth = 10, $highlight = false)
{
echo static::dumpAsString($var, $depth, $highlight);
} | Displays a variable.
This method achieves the similar functionality as var_dump and print_r
but is more robust when handling complex objects such as Yii controllers.
@param mixed $var variable to be dumped
@param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
@param bool $highlight whether the result should be syntax-highlighted | dump | php | yiisoft/yii2 | framework/helpers/BaseVarDumper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseVarDumper.php | BSD-3-Clause |
public static function dumpAsString($var, $depth = 10, $highlight = false)
{
self::$_output = '';
self::$_objects = [];
self::$_depth = $depth;
self::dumpInternal($var, 0);
if ($highlight) {
$result = highlight_string("<?php\n" . self::$_output, true);
self::$_output = preg_replace('/<\\?php<br \\/>/', '', $result, 1);
}
return self::$_output;
} | Dumps a variable in terms of a string.
This method achieves the similar functionality as var_dump and print_r
but is more robust when handling complex objects such as Yii controllers.
@param mixed $var variable to be dumped
@param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
@param bool $highlight whether the result should be syntax-highlighted
@return string the string representation of the variable | dumpAsString | php | yiisoft/yii2 | framework/helpers/BaseVarDumper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseVarDumper.php | BSD-3-Clause |
public static function export($var)
{
self::$_output = '';
self::exportInternal($var, 0);
return self::$_output;
} | Exports a variable as a string representation.
The string is a valid PHP expression that can be evaluated by PHP parser
and the evaluation result will give back the variable value.
This method is similar to `var_export()`. The main difference is that
it generates more compact string representation using short array syntax.
It also handles objects by using the PHP functions serialize() and unserialize().
PHP 5.4 or above is required to parse the exported value.
@param mixed $var the variable to be exported.
@return string a string representation of the variable | export | php | yiisoft/yii2 | framework/helpers/BaseVarDumper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseVarDumper.php | BSD-3-Clause |
private static function exportClosure(\Closure $closure)
{
$reflection = new \ReflectionFunction($closure);
$fileName = $reflection->getFileName();
$start = $reflection->getStartLine();
$end = $reflection->getEndLine();
if ($fileName === false || $start === false || $end === false) {
return 'function() {/* Error: unable to determine Closure source */}';
}
--$start;
$source = implode("\n", array_slice(file($fileName), $start, $end - $start));
$tokens = token_get_all('<?php ' . $source);
array_shift($tokens);
$closureTokens = [];
$pendingParenthesisCount = 0;
foreach ($tokens as $token) {
if (isset($token[0]) && $token[0] === T_FUNCTION) {
$closureTokens[] = $token[1];
continue;
}
if ($closureTokens !== []) {
$closureTokens[] = isset($token[1]) ? $token[1] : $token;
if ($token === '}') {
$pendingParenthesisCount--;
if ($pendingParenthesisCount === 0) {
break;
}
} elseif ($token === '{') {
$pendingParenthesisCount++;
}
}
}
return implode('', $closureTokens);
} | Exports a [[Closure]] instance.
@param \Closure $closure closure instance.
@return string | exportClosure | php | yiisoft/yii2 | framework/helpers/BaseVarDumper.php | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseVarDumper.php | BSD-3-Clause |
public function init()
{
parent::init();
if ($this->user !== false) {
$this->user = Instance::ensure($this->user, User::className());
}
foreach ($this->rules as $i => $rule) {
if (is_array($rule)) {
$this->rules[$i] = Yii::createObject(array_merge($this->ruleConfig, $rule));
}
}
} | Initializes the [[rules]] array by instantiating rule objects from configurations. | init | php | yiisoft/yii2 | framework/filters/AccessControl.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/AccessControl.php | BSD-3-Clause |
public function allows($action, $user, $request)
{
if (
$this->matchAction($action)
&& $this->matchRole($user)
&& $this->matchIP($request->getUserIP())
&& $this->matchVerb($request->getMethod())
&& $this->matchController($action->controller)
&& $this->matchCustom($action)
) {
return $this->allow ? true : false;
}
return null;
} | Checks whether the Web user is allowed to perform the specified action.
@param Action $action the action to be performed
@param User|false $user the user object or `false` in case of detached User component
@param Request $request
@return bool|null `true` if the user is allowed, `false` if the user is denied, `null` if the rule does not apply to the user | allows | php | yiisoft/yii2 | framework/filters/AccessRule.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/AccessRule.php | BSD-3-Clause |
public function checkRateLimit($user, $request, $response, $action)
{
list($limit, $window) = $user->getRateLimit($request, $action);
list($allowance, $timestamp) = $user->loadAllowance($request, $action);
$current = time();
$allowance += (int) (($current - $timestamp) * $limit / $window);
if ($allowance > $limit) {
$allowance = $limit;
}
if ($allowance < 1) {
$user->saveAllowance($request, $action, 0, $current);
$this->addRateLimitHeaders($response, $limit, 0, $window);
throw new TooManyRequestsHttpException($this->errorMessage);
}
$user->saveAllowance($request, $action, $allowance - 1, $current);
$this->addRateLimitHeaders($response, $limit, $allowance - 1, (int) (($limit - $allowance + 1) * $window / $limit));
} | Checks whether the rate limit exceeds.
@param RateLimitInterface $user the current user
@param Request $request
@param Response $response
@param \yii\base\Action $action the action to be executed
@throws TooManyRequestsHttpException if rate limit exceeds | checkRateLimit | php | yiisoft/yii2 | framework/filters/RateLimiter.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/RateLimiter.php | BSD-3-Clause |
public function addRateLimitHeaders($response, $limit, $remaining, $reset)
{
if ($this->enableRateLimitHeaders) {
$response->getHeaders()
->set('X-Rate-Limit-Limit', $limit)
->set('X-Rate-Limit-Remaining', $remaining)
->set('X-Rate-Limit-Reset', $reset);
}
} | Adds the rate limit headers to the response.
@param Response $response
@param int $limit the maximum number of allowed requests during a period
@param int $remaining the remaining number of allowed requests within the current period
@param int $reset the number of seconds to wait before having maximum number of allowed requests again | addRateLimitHeaders | php | yiisoft/yii2 | framework/filters/RateLimiter.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/RateLimiter.php | BSD-3-Clause |
public function beforeCacheResponse()
{
return true;
} | This method is invoked right before the response caching is to be started.
You may override this method to cancel caching by returning `false` or store an additional data
in a cache entry by returning an array instead of `true`.
@return bool|array whether to cache or not, return an array instead of `true` to store an additional data.
@since 2.0.11 | beforeCacheResponse | php | yiisoft/yii2 | framework/filters/PageCache.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/PageCache.php | BSD-3-Clause |
public function afterRestoreResponse($data)
{
} | This method is invoked right after the response restoring is finished (but before the response is sent).
You may override this method to do last-minute preparation before the response is sent.
@param array|null $data an array of an additional data stored in a cache entry or `null`.
@since 2.0.11 | afterRestoreResponse | php | yiisoft/yii2 | framework/filters/PageCache.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/PageCache.php | BSD-3-Clause |
protected function restoreResponse($response, $data)
{
foreach (['format', 'version', 'statusCode', 'statusText', 'content'] as $name) {
$response->{$name} = $data[$name];
}
foreach (['headers', 'cookies'] as $name) {
if (isset($data[$name]) && is_array($data[$name])) {
$response->{$name}->fromArray(array_merge($data[$name], $response->{$name}->toArray()));
}
}
if (!empty($data['dynamicPlaceholders']) && is_array($data['dynamicPlaceholders'])) {
$response->content = $this->updateDynamicContent($response->content, $data['dynamicPlaceholders'], true);
}
$this->afterRestoreResponse(isset($data['cacheData']) ? $data['cacheData'] : null);
} | Restores response properties from the given data.
@param Response $response the response to be restored.
@param array $data the response property data.
@since 2.0.3 | restoreResponse | php | yiisoft/yii2 | framework/filters/PageCache.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/PageCache.php | BSD-3-Clause |
private function insertResponseCookieCollectionIntoData(Response $response, array &$data)
{
if ($this->cacheCookies === false) {
return;
}
$all = $response->cookies->toArray();
if (is_array($this->cacheCookies)) {
$filtered = [];
foreach ($this->cacheCookies as $name) {
if (isset($all[$name])) {
$filtered[$name] = $all[$name];
}
}
$all = $filtered;
}
$data['cookies'] = $all;
} | Inserts (or filters/ignores according to config) response cookies into a cache data array.
@param Response $response the response.
@param array $data the cache data. | insertResponseCookieCollectionIntoData | php | yiisoft/yii2 | framework/filters/PageCache.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/PageCache.php | BSD-3-Clause |
private function insertResponseHeaderCollectionIntoData(Response $response, array &$data)
{
if ($this->cacheHeaders === false) {
return;
}
$all = $response->headers->toOriginalArray();
if (is_array($this->cacheHeaders)) {
$filtered = [];
foreach ($this->cacheHeaders as $name) {
if (isset($all[$name])) {
$filtered[$name] = $all[$name];
}
}
$all = $filtered;
}
$data['headers'] = $all;
} | Inserts (or filters/ignores according to config) response headers into a cache data array.
@param Response $response the response.
@param array $data the cache data. | insertResponseHeaderCollectionIntoData | php | yiisoft/yii2 | framework/filters/PageCache.php | https://github.com/yiisoft/yii2/blob/master/framework/filters/PageCache.php | BSD-3-Clause |
protected function detectAttributeTypes()
{
$attributeTypes = [];
foreach ($this->owner->getValidators() as $validator) {
$type = null;
if ($validator instanceof BooleanValidator) {
$type = self::TYPE_BOOLEAN;
} elseif ($validator instanceof NumberValidator) {
$type = $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT;
} elseif ($validator instanceof StringValidator) {
$type = self::TYPE_STRING;
}
if ($type !== null) {
$attributeTypes += array_fill_keys($validator->getAttributeNames(), $type);
}
}
return $attributeTypes;
} | Composes default value for [[attributeTypes]] from the owner validation rules.
@return array attribute type map. | detectAttributeTypes | php | yiisoft/yii2 | framework/behaviors/AttributeTypecastBehavior.php | https://github.com/yiisoft/yii2/blob/master/framework/behaviors/AttributeTypecastBehavior.php | BSD-3-Clause |
protected function resetOldAttributes()
{
if ($this->attributeTypes === null) {
return;
}
$attributes = array_keys($this->attributeTypes);
foreach ($attributes as $attribute) {
if ($this->owner->canSetOldAttribute($attribute)) {
$this->owner->setOldAttribute($attribute, $this->owner->{$attribute});
}
}
} | Resets the old values of the named attributes. | resetOldAttributes | php | yiisoft/yii2 | framework/behaviors/AttributeTypecastBehavior.php | https://github.com/yiisoft/yii2/blob/master/framework/behaviors/AttributeTypecastBehavior.php | BSD-3-Clause |
public function init()
{
parent::init();
$this->addServers($this->getMemcache(), $this->getServers());
} | Initializes this application component.
It creates the memcache instance and adds memcache servers. | init | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
protected function addServers($cache, $servers)
{
if (empty($servers)) {
$servers = [new MemCacheServer([
'host' => '127.0.0.1',
'port' => 11211,
])];
} else {
foreach ($servers as $server) {
if ($server->host === null) {
throw new InvalidConfigException("The 'host' property must be specified for every memcache server.");
}
}
}
if ($this->useMemcached) {
$this->addMemcachedServers($cache, $servers);
} else {
$this->addMemcacheServers($cache, $servers);
}
} | Add servers to the server pool of the cache specified.
@param \Memcache|\Memcached $cache
@param MemCacheServer[] $servers
@throws InvalidConfigException | addServers | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
protected function addMemcachedServers($cache, $servers)
{
$existingServers = [];
if ($this->persistentId !== null) {
foreach ($cache->getServerList() as $s) {
$existingServers[$s['host'] . ':' . $s['port']] = true;
}
}
foreach ($servers as $server) {
if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) {
$cache->addServer($server->host, $server->port, $server->weight);
}
}
} | Add servers to the server pool of the cache specified
Used for memcached PECL extension.
@param \Memcached $cache
@param MemCacheServer[] $servers | addMemcachedServers | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
public function getMemcache()
{
if ($this->_cache === null) {
$extension = $this->useMemcached ? 'memcached' : 'memcache';
if (!extension_loaded($extension)) {
throw new InvalidConfigException("MemCache requires PHP $extension extension to be loaded.");
}
if ($this->useMemcached) {
$this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached();
if ($this->username !== null || $this->password !== null) {
$this->_cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
$this->_cache->setSaslAuthData($this->username, $this->password);
}
if (!empty($this->options)) {
$this->_cache->setOptions($this->options);
}
} else {
$this->_cache = new \Memcache();
}
}
return $this->_cache;
} | Returns the underlying memcache (or memcached) object.
@return \Memcache|\Memcached the memcache (or memcached) object used by this cache component.
@throws InvalidConfigException if memcache or memcached extension is not loaded | getMemcache | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
public function getServers()
{
return $this->_servers;
} | Returns the memcache or memcached server configurations.
@return MemCacheServer[] list of memcache server configurations. | getServers | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
protected function setValue($key, $value, $duration)
{
$expire = $this->normalizeDuration($duration);
return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
} | Stores a value identified by a key in cache.
This is the implementation of the method declared in the parent class.
@param string $key the key identifying the value to be cached
@param mixed $value the value to be cached.
@see [Memcache::set()](https://www.php.net/manual/en/memcache.set.php)
@param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
@return bool true if the value is successfully stored into cache, false otherwise | setValue | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
protected function setValues($data, $duration)
{
if ($this->useMemcached) {
$expire = $this->normalizeDuration($duration);
// Memcached::setMulti() returns boolean
// @see https://www.php.net/manual/en/memcached.setmulti.php
return $this->_cache->setMulti($data, $expire) ? [] : array_keys($data);
}
return parent::setValues($data, $duration);
} | Stores multiple key-value pairs in cache.
@param array $data array where key corresponds to cache key while value is the value stored
@param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
@return array array of failed keys. | setValues | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
protected function addValue($key, $value, $duration)
{
$expire = $this->normalizeDuration($duration);
return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
} | Stores a value identified by a key into cache if the cache does not contain this key.
This is the implementation of the method declared in the parent class.
@param string $key the key identifying the value to be cached
@param mixed $value the value to be cached
@see [Memcache::set()](https://www.php.net/manual/en/memcache.set.php)
@param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
@return bool true if the value is successfully stored into cache, false otherwise | addValue | php | yiisoft/yii2 | framework/caching/MemCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/MemCache.php | BSD-3-Clause |
protected function getValue($key)
{
return wincache_ucache_get($key);
} | Retrieves a value from cache with a specified key.
This is the implementation of the method declared in the parent class.
@param string $key a unique key identifying the cached value
@return string|bool the value stored in cache, false if the value is not in the cache or expired. | getValue | php | yiisoft/yii2 | framework/caching/WinCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/WinCache.php | BSD-3-Clause |
protected function setValues($data, $duration)
{
return wincache_ucache_set($data, null, $duration);
} | Stores multiple key-value pairs in cache.
@param array $data array where key corresponds to cache key while value is the value stored
@param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
@return array array of failed keys | setValues | php | yiisoft/yii2 | framework/caching/WinCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/WinCache.php | BSD-3-Clause |
protected function addValues($data, $duration)
{
return wincache_ucache_add($data, null, $duration);
} | Adds multiple key-value pairs to cache.
The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
storage supports multiadd, this method should be overridden to exploit that feature.
@param array $data array where key corresponds to cache key while value is the value stored
@param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
@return array array of failed keys | addValues | php | yiisoft/yii2 | framework/caching/WinCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/WinCache.php | BSD-3-Clause |
public function mset($items, $duration = null, $dependency = null)
{
return $this->multiSet($items, $duration, $dependency);
} | Stores multiple items in cache. Each item contains a value identified by a key.
If the cache already contains such a key, the existing value and
expiration time will be replaced with the new ones, respectively.
@param array $items the items to be cached, as key-value pairs.
@param int|null $duration default duration in seconds before the cache will expire. If not set,
default [[defaultDuration]] value is used.
@param Dependency|null $dependency dependency of the cached items. If the dependency changes,
the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
This parameter is ignored if [[serializer]] is false.
@return array array of failed keys
@deprecated This method is an alias for [[multiSet()]] and will be removed in 2.1.0. | mset | php | yiisoft/yii2 | framework/caching/Cache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/Cache.php | BSD-3-Clause |
public function multiSet($items, $duration = null, $dependency = null)
{
if ($duration === null) {
$duration = $this->defaultDuration;
}
$data = $this->prepareCacheData($items, $dependency);
return $this->setValues($data, $duration);
} | Stores multiple items in cache. Each item contains a value identified by a key.
If the cache already contains such a key, the existing value and
expiration time will be replaced with the new ones, respectively.
@param array $items the items to be cached, as key-value pairs.
@param int|null $duration default duration in seconds before the cache will expire. If not set,
default [[defaultDuration]] value is used.
@param Dependency|null $dependency dependency of the cached items. If the dependency changes,
the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
This parameter is ignored if [[serializer]] is false.
@return array array of failed keys
@since 2.0.7 | multiSet | php | yiisoft/yii2 | framework/caching/Cache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/Cache.php | BSD-3-Clause |
public function multiAdd($items, $duration = 0, $dependency = null)
{
$data = $this->prepareCacheData($items, $dependency);
return $this->addValues($data, $duration);
} | Stores multiple items in cache. Each item contains a value identified by a key.
If the cache already contains such a key, the existing value and expiration time will be preserved.
@param array $items the items to be cached, as key-value pairs.
@param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
@param Dependency|null $dependency dependency of the cached items. If the dependency changes,
the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
This parameter is ignored if [[serializer]] is false.
@return array array of failed keys
@since 2.0.7 | multiAdd | php | yiisoft/yii2 | framework/caching/Cache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/Cache.php | BSD-3-Clause |
protected function setValue($key, $value, $duration)
{
$this->gc();
$cacheFile = $this->getCacheFile($key);
if ($this->directoryLevel > 0) {
@FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true);
}
// If ownership differs the touch call will fail, so we try to
// rebuild the file from scratch by deleting it first
// https://github.com/yiisoft/yii2/pull/16120
if (is_file($cacheFile) && function_exists('posix_geteuid') && fileowner($cacheFile) !== posix_geteuid()) {
@unlink($cacheFile);
}
if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
if ($this->fileMode !== null) {
@chmod($cacheFile, $this->fileMode);
}
if ($duration <= 0) {
$duration = 31536000; // 1 year
}
if (@touch($cacheFile, $duration + time())) {
clearstatcache();
return true;
}
return false;
}
$message = "Unable to write cache file '{$cacheFile}'";
if ($error = error_get_last()) {
$message .= ": {$error['message']}";
}
Yii::warning($message, __METHOD__);
return false;
} | Stores a value identified by a key in cache.
This is the implementation of the method declared in the parent class.
@param string $key the key identifying the value to be cached
@param string $value the value to be cached. Other types (If you have disabled [[serializer]]) unable to get is
correct in [[getValue()]].
@param int $duration the number of seconds in which the cached value will expire. Fewer than or equal to 0 means 1 year expiration time.
@return bool true if the value is successfully stored into cache, false otherwise | setValue | php | yiisoft/yii2 | framework/caching/FileCache.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/FileCache.php | BSD-3-Clause |
protected function generateDependencyData($cache)
{
return ($this->callback)();
} | Generates the data needed to determine if dependency has been changed.
This method returns the result of the callback function.
@param CacheInterface $cache the cache component that is currently evaluating this dependency
@return mixed the data needed to determine if dependency has been changed. | generateDependencyData | php | yiisoft/yii2 | framework/caching/CallbackDependency.php | https://github.com/yiisoft/yii2/blob/master/framework/caching/CallbackDependency.php | BSD-3-Clause |
protected function renderBeforeItem($model, $key, $index)
{
if ($this->beforeItem instanceof Closure) {
return call_user_func($this->beforeItem, $model, $key, $index, $this);
}
return null;
} | Calls [[beforeItem]] closure, returns execution result.
If [[beforeItem]] is not a closure, `null` will be returned.
@param mixed $model the data model to be rendered
@param mixed $key the key value associated with the data model
@param int $index the zero-based index of the data model in the model array returned by [[dataProvider]].
@return string|null [[beforeItem]] call result or `null` when [[beforeItem]] is not a closure
@see beforeItem
@since 2.0.11 | renderBeforeItem | php | yiisoft/yii2 | framework/widgets/ListView.php | https://github.com/yiisoft/yii2/blob/master/framework/widgets/ListView.php | BSD-3-Clause |
protected function renderAfterItem($model, $key, $index)
{
if ($this->afterItem instanceof Closure) {
return call_user_func($this->afterItem, $model, $key, $index, $this);
}
return null;
} | Calls [[afterItem]] closure, returns execution result.
If [[afterItem]] is not a closure, `null` will be returned.
@param mixed $model the data model to be rendered
@param mixed $key the key value associated with the data model
@param int $index the zero-based index of the data model in the model array returned by [[dataProvider]].
@return string|null [[afterItem]] call result or `null` when [[afterItem]] is not a closure
@see afterItem
@since 2.0.11 | renderAfterItem | php | yiisoft/yii2 | framework/widgets/ListView.php | https://github.com/yiisoft/yii2/blob/master/framework/widgets/ListView.php | BSD-3-Clause |
protected function renderItem($item)
{
if (isset($item['url'])) {
$template = ArrayHelper::getValue($item, 'template', $this->linkTemplate);
return strtr($template, [
'{url}' => Html::encode(Url::to($item['url'])),
'{label}' => $item['label'],
]);
}
$template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
return strtr($template, [
'{label}' => $item['label'],
]);
} | Renders the content of a menu item.
Note that the container and the sub-menus are not rendered here.
@param array $item the menu item to be rendered. Please refer to [[items]] to see what data might be in the item.
@return string the rendering result | renderItem | php | yiisoft/yii2 | framework/widgets/Menu.php | https://github.com/yiisoft/yii2/blob/master/framework/widgets/Menu.php | BSD-3-Clause |
protected function parseDateValue($value)
{
// TODO consider merging these methods into single one at 2.1
return $this->parseDateValueFormat($value, $this->format);
} | Parses date string into UNIX timestamp.
@param mixed $value string representing date
@return int|false a UNIX timestamp or `false` on failure. | parseDateValue | php | yiisoft/yii2 | framework/validators/DateValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/DateValidator.php | BSD-3-Clause |
private function parseDateValueFormat($value, $format)
{
if (is_array($value)) {
return false;
}
if (strncmp($format, 'php:', 4) === 0) {
$format = substr($format, 4);
} else {
if (extension_loaded('intl')) {
return $this->parseDateValueIntl($value, $format);
}
// fallback to PHP if intl is not installed
$format = FormatConverter::convertDateIcuToPhp($format, 'date');
}
return $this->parseDateValuePHP($value, $format);
} | Parses date string into UNIX timestamp.
@param mixed $value string representing date
@param string $format expected date format
@return int|false a UNIX timestamp or `false` on failure.
@throws InvalidConfigException | parseDateValueFormat | php | yiisoft/yii2 | framework/validators/DateValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/DateValidator.php | BSD-3-Clause |
private function parseDateValueIntl($value, $format)
{
$formatter = $this->getIntlDateFormatter($format);
// enable strict parsing to avoid getting invalid date values
$formatter->setLenient(false);
// There should not be a warning thrown by parse() but this seems to be the case on windows so we suppress it here
// See https://github.com/yiisoft/yii2/issues/5962 and https://bugs.php.net/bug.php?id=68528
$parsePos = 0;
$parsedDate = @$formatter->parse($value, $parsePos);
$valueLength = mb_strlen($value, Yii::$app ? Yii::$app->charset : 'UTF-8');
if ($parsedDate === false || $parsePos !== $valueLength || ($this->strictDateFormat && $formatter->format($parsedDate) !== $value)) {
return false;
}
return $parsedDate;
} | Parses a date value using the IntlDateFormatter::parse().
@param string $value string representing date
@param string $format the expected date format
@return int|bool a UNIX timestamp or `false` on failure.
@throws InvalidConfigException | parseDateValueIntl | php | yiisoft/yii2 | framework/validators/DateValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/DateValidator.php | BSD-3-Clause |
private function parseDateValuePHP($value, $format)
{
$hasTimeInfo = strpbrk($format, 'HhGgisU') !== false;
// if no time was provided in the format string set timezone to default one to match yii\i18n\Formatter::formatDateTimeValue()
$timezone = $hasTimeInfo ? $this->timeZone : $this->defaultTimeZone;
$date = DateTime::createFromFormat($format, $value, new DateTimeZone($timezone));
$errors = DateTime::getLastErrors(); // Before PHP 8.2 may return array instead of false (see https://github.com/php/php-src/issues/9431).
if ($date === false || ($errors !== false && ($errors['error_count'] || $errors['warning_count'])) || ($this->strictDateFormat && $date->format($format) !== $value)) {
return false;
}
if (!$hasTimeInfo) {
// if no time was provided in the format string set time to 0 to get a simple date timestamp
$date->setTime(0, 0, 0);
}
return $date->getTimestamp();
} | Parses a date value using the DateTime::createFromFormat().
@param string $value string representing date
@param string $format the expected date format
@return int|bool a UNIX timestamp or `false` on failure. | parseDateValuePHP | php | yiisoft/yii2 | framework/validators/DateValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/DateValidator.php | BSD-3-Clause |
private function formatTimestamp($timestamp, $format)
{
if (strncmp($format, 'php:', 4) === 0) {
$format = substr($format, 4);
} else {
$format = FormatConverter::convertDateIcuToPhp($format, 'date');
}
$date = new DateTime();
$date->setTimestamp($timestamp);
$date->setTimezone(new DateTimeZone($this->timestampAttributeTimeZone));
return $date->format($format);
} | Formats a timestamp using the specified format.
@param int $timestamp
@param string $format
@return string
@throws Exception | formatTimestamp | php | yiisoft/yii2 | framework/validators/DateValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/DateValidator.php | BSD-3-Clause |
private function createEmbeddedValidator($model = null, $current = null)
{
$rule = $this->rule;
if ($rule instanceof Validator) {
return $rule;
}
if (is_array($rule) && isset($rule[0])) { // validator type
if (!is_object($model)) {
$model = new Model(); // mock up context model
}
$params = array_slice($rule, 1);
$params['current'] = $current;
return Validator::createValidator($rule[0], $model, $this->attributes, $params);
}
throw new InvalidConfigException('Invalid validation rule: a rule must be an array specifying validator type.');
} | Creates validator object based on the validation rule specified in [[rule]].
@param Model|null $model model in which context validator should be created.
@param mixed|null $current value being currently validated.
@throws \yii\base\InvalidConfigException
@return Validator validator instance | createEmbeddedValidator | php | yiisoft/yii2 | framework/validators/EachValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/EachValidator.php | BSD-3-Clause |
public function setRanges($ranges)
{
$this->_ranges = $this->prepareRanges((array) $ranges);
} | Set the IPv4 or IPv6 ranges that are allowed or forbidden.
The following preparation tasks are performed:
- Recursively substitutes aliases (described in [[networks]]) with their values.
- Removes duplicates
@param array|string|null $ranges the IPv4 or IPv6 ranges that are allowed or forbidden.
When the array is empty, or the option not set, all IP addresses are allowed.
Otherwise, the rules are checked sequentially until the first match is found.
An IP address is forbidden, when it has not matched any of the rules.
Example:
```php
[
'ranges' => [
'192.168.10.128'
'!192.168.10.0/24',
'any' // allows any other IP addresses
]
]
```
In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24` subnet.
IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction. | setRanges | php | yiisoft/yii2 | framework/validators/IpValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/IpValidator.php | BSD-3-Clause |
private function expandIPv6($ip)
{
return IpHelper::expandIPv6($ip);
} | Expands an IPv6 address to it's full notation.
For example `2001:db8::1` will be expanded to `2001:0db8:0000:0000:0000:0000:0000:0001`.
@param string $ip the original IPv6
@return string the expanded IPv6 | expandIPv6 | php | yiisoft/yii2 | framework/validators/IpValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/IpValidator.php | BSD-3-Clause |
private function parseNegatedRange($string)
{
$isNegated = strpos($string, static::NEGATION_CHAR) === 0;
return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
} | Parses IP address/range for the negation with [[NEGATION_CHAR]].
@param $string
@return array `[0 => bool, 1 => string]`
- boolean: whether the string is negated
- string: the string without negation (when the negation were present) | parseNegatedRange | php | yiisoft/yii2 | framework/validators/IpValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/IpValidator.php | BSD-3-Clause |
private function getIpParsePattern()
{
return '/^(' . preg_quote(static::NEGATION_CHAR, '/') . '?)(.+?)(\/(\d+))?$/';
} | Used to get the Regexp pattern for initial IP address parsing.
@return string | getIpParsePattern | php | yiisoft/yii2 | framework/validators/IpValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/IpValidator.php | BSD-3-Clause |
private function inRange($ip, $cidr, $range)
{
return IpHelper::inRange($ip . '/' . $cidr, $range);
} | Checks whether the IP is in subnet range.
@param string $ip an IPv4 or IPv6 address
@param int $cidr
@param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64`
@return bool | inRange | php | yiisoft/yii2 | framework/validators/IpValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/IpValidator.php | BSD-3-Clause |
protected function trimValue($value)
{
return $this->isEmpty($value) ? '' : trim((string) $value, $this->chars ?: " \n\r\t\v\x00");
} | Converts given value to string and strips declared characters.
@param mixed $value the value to strip
@return string | trimValue | php | yiisoft/yii2 | framework/validators/TrimValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/TrimValidator.php | BSD-3-Clause |
private function queryValueExists($query, $value)
{
if (is_array($value)) {
return $query->count("DISTINCT [[$this->targetAttribute]]") == count(array_unique($value));
}
return $query->exists();
} | Run query to check if value exists.
@param QueryInterface $query
@param mixed $value the value to be checked
@return bool | queryValueExists | php | yiisoft/yii2 | framework/validators/ExistValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/ExistValidator.php | BSD-3-Clause |
private function applyTableAlias($query, $conditions, $alias = null)
{
if ($alias === null) {
$alias = array_keys($query->getTablesUsedInFrom())[0];
}
$prefixedConditions = [];
foreach ($conditions as $columnName => $columnValue) {
if (strpos($columnName, '(') === false) {
$prefixedColumn = "{$alias}.[[" . preg_replace(
'/^' . preg_quote($alias, '/') . '\.(.*)$/',
'$1',
$columnName
) . ']]';
} else {
// there is an expression, can't prefix it reliably
$prefixedColumn = $columnName;
}
$prefixedConditions[$prefixedColumn] = $columnValue;
}
return $prefixedConditions;
} | Returns conditions with alias.
@param ActiveQuery $query
@param array $conditions array of condition, keys to be modified
@param string|null $alias set empty string for no apply alias. Set null for apply primary table alias
@return array | applyTableAlias | php | yiisoft/yii2 | framework/validators/ExistValidator.php | https://github.com/yiisoft/yii2/blob/master/framework/validators/ExistValidator.php | BSD-3-Clause |
public function all($db = null)
{
if ($this->emulateExecution) {
return [];
}
$rows = $this->createCommand($db)->queryAll();
return $this->populate($rows);
} | Executes the query and returns all results as an array.
@param Connection|null $db the database connection used to generate the SQL statement.
If this parameter is not given, the `db` application component will be used.
@return array the query results. If the query results in nothing, an empty array will be returned. | all | php | yiisoft/yii2 | framework/db/Query.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Query.php | BSD-3-Clause |
protected function queryScalar($selectExpression, $db)
{
if ($this->emulateExecution) {
return null;
}
if (
!$this->distinct
&& empty($this->groupBy)
&& empty($this->having)
&& empty($this->union)
) {
$select = $this->select;
$order = $this->orderBy;
$limit = $this->limit;
$offset = $this->offset;
$this->select = [$selectExpression];
$this->orderBy = null;
$this->limit = null;
$this->offset = null;
$e = null;
try {
$command = $this->createCommand($db);
} catch (\Exception $e) {
// throw it later (for PHP < 7.0)
} catch (\Throwable $e) {
// throw it later
}
$this->select = $select;
$this->orderBy = $order;
$this->limit = $limit;
$this->offset = $offset;
if ($e !== null) {
throw $e;
}
return $command->queryScalar();
}
$command = (new self())
->select([$selectExpression])
->from(['c' => $this])
->createCommand($db);
$this->setCommandCache($command);
return $command->queryScalar();
} | Queries a scalar value by setting [[select]] first.
Restores the value of select to make this query reusable.
@param string|ExpressionInterface $selectExpression
@param Connection|null $db the database connection used to execute the query.
@return bool|string|null
@throws \Throwable if can't create command | queryScalar | php | yiisoft/yii2 | framework/db/Query.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Query.php | BSD-3-Clause |
public function prepare($forRead = null)
{
if ($this->pdoStatement) {
$this->bindPendingParams();
return;
}
$sql = $this->getSql();
if ($sql === '') {
return;
}
if ($this->db->getTransaction()) {
// master is in a transaction. use the same connection.
$forRead = false;
}
if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
$pdo = $this->db->getSlavePdo(true);
} else {
$pdo = $this->db->getMasterPdo();
}
try {
$this->pdoStatement = $pdo->prepare($sql);
$this->bindPendingParams();
} catch (\Exception $e) {
$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new Exception($message, $errorInfo, $e->getCode(), $e);
} catch (\Throwable $e) {
$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
throw new Exception($message, null, $e->getCode(), $e);
}
} | Prepares the SQL statement to be executed.
For complex SQL statement that is to be executed multiple times,
this may improve performance.
For SQL statement with binding parameters, this method is invoked
automatically.
@param bool|null $forRead whether this method is called for a read query. If null, it means
the SQL statement should be used to determine whether it is for read or write.
@throws Exception if there is any DB error | prepare | php | yiisoft/yii2 | framework/db/Command.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Command.php | BSD-3-Clause |
protected function queryInternal($method, $fetchMode = null)
{
list($profile, $rawSql) = $this->logQuery('yii\db\Command::query');
if ($method !== '') {
$info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
if (is_array($info)) {
/* @var $cache \yii\caching\CacheInterface */
$cache = $info[0];
$cacheKey = $this->getCacheKey($method, $fetchMode, '');
$result = $cache->get($cacheKey);
if (is_array($result) && array_key_exists(0, $result)) {
Yii::debug('Query result served from cache', 'yii\db\Command::query');
return $result[0];
}
}
}
$this->prepare(true);
try {
$profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
$this->internalExecute($rawSql);
if ($method === '') {
$result = new DataReader($this);
} else {
if ($fetchMode === null) {
$fetchMode = $this->fetchMode;
}
$result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
$this->pdoStatement->closeCursor();
}
$profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
} catch (Exception $e) {
$profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
throw $e;
}
if (isset($cache, $cacheKey, $info)) {
$cache->set($cacheKey, [$result], $info[1], $info[2]);
Yii::debug('Saved query result in cache', 'yii\db\Command::query');
}
return $result;
} | Performs the actual DB query of a SQL statement.
@param string $method method of PDOStatement to be called
@param int|null $fetchMode the result fetch mode. Please refer to [PHP manual](https://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
@return mixed the method execution result
@throws Exception if the query causes any problem
@since 2.0.1 this method is protected (was private before). | queryInternal | php | yiisoft/yii2 | framework/db/Command.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Command.php | BSD-3-Clause |
public static function getDb()
{
return Yii::$app->getDb();
} | Returns the database connection used by this AR class.
By default, the "db" application component is used as the database connection.
You may override this method if you want to use a different database connection.
@return Connection the database connection used by this AR class. | getDb | php | yiisoft/yii2 | framework/db/ActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php | BSD-3-Clause |
protected static function filterValidAliases(Query $query)
{
$tables = $query->getTablesUsedInFrom();
$aliases = array_diff(array_keys($tables), $tables);
return array_map(function ($alias) {
return preg_replace('/{{(\w+)}}/', '$1', $alias);
}, array_values($aliases));
} | Returns table aliases which are not the same as the name of the tables.
@param Query $query
@return array
@throws InvalidConfigException
@since 2.0.17
@internal | filterValidAliases | php | yiisoft/yii2 | framework/db/ActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php | BSD-3-Clause |
public static function tableName()
{
return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
} | Declares the name of the database table associated with this AR class.
By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
`Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
if the table is not named after this convention.
@return string the table name | tableName | php | yiisoft/yii2 | framework/db/ActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php | BSD-3-Clause |
public static function getTableSchema()
{
$tableSchema = static::getDb()
->getSchema()
->getTableSchema(static::tableName());
if ($tableSchema === null) {
throw new InvalidConfigException('The table does not exist: ' . static::tableName());
}
return $tableSchema;
} | Returns the schema information of the DB table associated with this AR class.
@return TableSchema the schema information of the DB table associated with this AR class.
@throws InvalidConfigException if the table for the AR class does not exist. | getTableSchema | php | yiisoft/yii2 | framework/db/ActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php | BSD-3-Clause |
public static function primaryKey()
{
return static::getTableSchema()->primaryKey;
} | Returns the primary key name(s) for this AR class.
The default implementation will return the primary key(s) as declared
in the DB table that is associated with this AR class.
If the DB table does not declare any primary key, you should override
this method to return the attributes that you want to use as primary keys
for this AR class.
Note that an array should be returned even for a table with single primary key.
@return string[] the primary keys of the associated database table. | primaryKey | php | yiisoft/yii2 | framework/db/ActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php | BSD-3-Clause |
protected function deleteInternal()
{
if (!$this->beforeDelete()) {
return false;
}
// we do not check the return value of deleteAll() because it's possible
// the record is already deleted in the database and thus the method will return 0
$condition = $this->getOldPrimaryKey(true);
$lock = $this->optimisticLock();
if ($lock !== null) {
$condition[$lock] = $this->$lock;
}
$result = static::deleteAll($condition);
if ($lock !== null && !$result) {
throw new StaleObjectException('The object being deleted is outdated.');
}
$this->setOldAttributes(null);
$this->afterDelete();
return $result;
} | Deletes an ActiveRecord without considering transaction.
@return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
@throws StaleObjectException | deleteInternal | php | yiisoft/yii2 | framework/db/ActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php | BSD-3-Clause |
public function equals($record)
{
if ($this->isNewRecord || $record->isNewRecord) {
return false;
}
return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
} | Returns a value indicating whether the given active record is the same as the current one.
The comparison is made by comparing the table names and the primary key values of the two active records.
If one of the records [[isNewRecord|is new]] they are also considered not equal.
@param ActiveRecord $record record to compare to
@return bool whether the two active records refer to the same row in the same database table. | equals | php | yiisoft/yii2 | framework/db/ActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php | BSD-3-Clause |
public function addCheck($name, $table, $expression)
{
$time = $this->beginCommand("add check $name in table $table");
$this->db->createCommand()->addCheck($name, $table, $expression)->execute();
$this->endCommand($time);
} | Creates a SQL command for adding a check constraint to an existing table.
@param string $name the name of the check constraint.
The name will be properly quoted by the method.
@param string $table the table that the check constraint will be added to.
The name will be properly quoted by the method.
@param string $expression the SQL of the `CHECK` constraint. | addCheck | php | yiisoft/yii2 | framework/db/Migration.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Migration.php | BSD-3-Clause |
public function dropCheck($name, $table)
{
$time = $this->beginCommand("drop check $name in table $table");
$this->db->createCommand()->dropCheck($name, $table)->execute();
$this->endCommand($time);
} | Creates a SQL command for dropping a check constraint.
@param string $name the name of the check constraint to be dropped.
The name will be properly quoted by the method.
@param string $table the table whose check constraint is to be dropped.
The name will be properly quoted by the method. | dropCheck | php | yiisoft/yii2 | framework/db/Migration.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Migration.php | BSD-3-Clause |
public function __toString()
{
return $this->getSql();
} | Returns the SQL code representing the token.
@return string SQL code. | __toString | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
public function offsetExists($offset)
{
return isset($this->_children[$this->calculateOffset($offset)]);
} | Returns whether there is a child token at the specified offset.
This method is required by the SPL [[\ArrayAccess]] interface.
It is implicitly called when you use something like `isset($token[$offset])`.
@param int $offset child token offset.
@return bool whether the token exists. | offsetExists | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
public function offsetGet($offset)
{
$offset = $this->calculateOffset($offset);
return isset($this->_children[$offset]) ? $this->_children[$offset] : null;
} | Returns a child token at the specified offset.
This method is required by the SPL [[\ArrayAccess]] interface.
It is implicitly called when you use something like `$child = $token[$offset];`.
@param int $offset child token offset.
@return SqlToken|null the child token at the specified offset, `null` if there's no token. | offsetGet | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
public function offsetSet($offset, $token)
{
$token->parent = $this;
if ($offset === null) {
$this->_children[] = $token;
} else {
$this->_children[$this->calculateOffset($offset)] = $token;
}
$this->updateCollectionOffsets();
} | Adds a child token to the token.
This method is required by the SPL [[\ArrayAccess]] interface.
It is implicitly called when you use something like `$token[$offset] = $child;`.
@param int|null $offset child token offset.
@param SqlToken $token token to be added. | offsetSet | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
public function offsetUnset($offset)
{
$offset = $this->calculateOffset($offset);
if (isset($this->_children[$offset])) {
array_splice($this->_children, $offset, 1);
}
$this->updateCollectionOffsets();
} | Removes a child token at the specified offset.
This method is required by the SPL [[\ArrayAccess]] interface.
It is implicitly called when you use something like `unset($token[$offset])`.
@param int $offset child token offset. | offsetUnset | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
public function getIsCollection()
{
return in_array($this->type, [
self::TYPE_CODE,
self::TYPE_STATEMENT,
self::TYPE_PARENTHESIS,
], true);
} | Returns whether the token represents a collection of tokens.
@return bool whether the token represents a collection of tokens. | getIsCollection | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
public function getHasChildren()
{
return $this->getIsCollection() && !empty($this->_children);
} | Returns whether the token represents a collection of tokens and has non-zero number of children.
@return bool whether the token has children. | getHasChildren | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
private function tokensMatch(SqlToken $patternToken, SqlToken $token, $offset = 0, &$firstMatchIndex = null, &$lastMatchIndex = null)
{
if (
$patternToken->getIsCollection() !== $token->getIsCollection()
|| (!$patternToken->getIsCollection() && $patternToken->content !== $token->content)
) {
return false;
}
if ($patternToken->children === $token->children) {
$firstMatchIndex = $lastMatchIndex = $offset;
return true;
}
$firstMatchIndex = $lastMatchIndex = null;
$wildcard = false;
for ($index = 0, $count = count($patternToken->children); $index < $count; $index++) {
// Here we iterate token by token with an exception of "any" that toggles
// an iteration until we matched with a next pattern token or EOF.
if ($patternToken[$index]->content === 'any') {
$wildcard = true;
continue;
}
for ($limit = $wildcard ? count($token->children) : $offset + 1; $offset < $limit; $offset++) {
if (!$wildcard && !isset($token[$offset])) {
break;
}
if (!$this->tokensMatch($patternToken[$index], $token[$offset])) {
continue;
}
if ($firstMatchIndex === null) {
$firstMatchIndex = $offset;
}
$lastMatchIndex = $offset;
$wildcard = false;
$offset++;
continue 2;
}
return false;
}
return true;
} | Tests the given token to match the specified pattern token.
@param SqlToken $patternToken
@param SqlToken $token
@param int $offset
@param int|null $firstMatchIndex
@param int|null $lastMatchIndex
@return bool | tokensMatch | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
private function calculateOffset($offset)
{
if ($offset >= 0) {
return $offset;
}
return count($this->_children) + $offset;
} | Returns an absolute offset in the children array.
@param int $offset
@return int | calculateOffset | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.