repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
hail-framework/framework | src/Util/Strings.php | Strings.split | public static function split(string $subject, string $pattern, int $flags = 0): array
{
return static::pcre('\preg_split', [$pattern, $subject, -1, $flags | PREG_SPLIT_DELIM_CAPTURE]);
} | php | public static function split(string $subject, string $pattern, int $flags = 0): array
{
return static::pcre('\preg_split', [$pattern, $subject, -1, $flags | PREG_SPLIT_DELIM_CAPTURE]);
} | [
"public",
"static",
"function",
"split",
"(",
"string",
"$",
"subject",
",",
"string",
"$",
"pattern",
",",
"int",
"$",
"flags",
"=",
"0",
")",
":",
"array",
"{",
"return",
"static",
"::",
"pcre",
"(",
"'\\preg_split'",
",",
"[",
"$",
"pattern",
",",
... | Splits string by a regular expression.
@param string $subject
@param string $pattern
@param int $flags
@return array
@throws RegexpException | [
"Splits",
"string",
"by",
"a",
"regular",
"expression",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Strings.php#L615-L618 | train |
hail-framework/framework | src/Util/Strings.php | Strings.match | public static function match(string $subject, string $pattern, int $flags = 0, int $offset = 0)
{
if ($offset > \strlen($subject)) {
return null;
}
$m = null;
return static::pcre('\preg_match', [$pattern, $subject, &$m, $flags, $offset])
? $m
: null;
} | php | public static function match(string $subject, string $pattern, int $flags = 0, int $offset = 0)
{
if ($offset > \strlen($subject)) {
return null;
}
$m = null;
return static::pcre('\preg_match', [$pattern, $subject, &$m, $flags, $offset])
? $m
: null;
} | [
"public",
"static",
"function",
"match",
"(",
"string",
"$",
"subject",
",",
"string",
"$",
"pattern",
",",
"int",
"$",
"flags",
"=",
"0",
",",
"int",
"$",
"offset",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"offset",
">",
"\\",
"strlen",
"(",
"$",
"su... | Performs a regular expression match.
@param string $subject
@param string $pattern
@param int $flags can be PREG_OFFSET_CAPTURE (returned in bytes)
@param int $offset offset in bytes
@return array|null
@throws RegexpException | [
"Performs",
"a",
"regular",
"expression",
"match",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Strings.php#L632-L643 | train |
hail-framework/framework | src/Util/Strings.php | Strings.matchAll | public static function matchAll(string $subject, string $pattern, int $flags = 0, int $offset = 0): array
{
if ($offset > \strlen($subject)) {
return [];
}
$m = null;
static::pcre('\preg_match_all', [
$pattern,
$subject,
&$m,
($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER),
$offset,
]);
return $m;
} | php | public static function matchAll(string $subject, string $pattern, int $flags = 0, int $offset = 0): array
{
if ($offset > \strlen($subject)) {
return [];
}
$m = null;
static::pcre('\preg_match_all', [
$pattern,
$subject,
&$m,
($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER),
$offset,
]);
return $m;
} | [
"public",
"static",
"function",
"matchAll",
"(",
"string",
"$",
"subject",
",",
"string",
"$",
"pattern",
",",
"int",
"$",
"flags",
"=",
"0",
",",
"int",
"$",
"offset",
"=",
"0",
")",
":",
"array",
"{",
"if",
"(",
"$",
"offset",
">",
"\\",
"strlen"... | Performs a global regular expression match.
@param string $subject
@param string $pattern
@param int $flags can be PREG_OFFSET_CAPTURE (returned in bytes); PREG_SET_ORDER is default
@param int $offset offset in bytes
@return array
@throws RegexpException | [
"Performs",
"a",
"global",
"regular",
"expression",
"match",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Strings.php#L657-L673 | train |
hail-framework/framework | src/Debugger/Profiler.php | Profiler.finish | public static function finish(...$args)
{
if (Debugger::isProductionMode()) {
return false;
}
if ([] === static::$stack) {
throw new \RuntimeException('The stack is empty. Call Hail\Debugger\Profiler::start() first.');
}
$now = \microtime(true);
$memoryUsage = \memory_get_usage(true);
if (!isset($args[1])) {
$label = $args[0] ?? static::getCurrentFileHashLine(1);
} else {
$label = \sprintf(...$args);
}
/** @var array $profile */
$profile = \array_pop(static::$stack);
$profile['meta'][self::FINISH_LABEL] = $label;
$profile['meta'][self::FINISH_TIME] = $now;
$profile['meta'][self::FINISH_MEMORY_USAGE] = $memoryUsage;
$profile[self::ABSOLUTE_DURATION] = $profile['meta'][self::FINISH_TIME] - $profile['meta'][self::START_TIME];
$profile[self::DURATION] = $profile[self::ABSOLUTE_DURATION] - $profile['meta'][self::TIME_OFFSET];
$profile[self::ABSOLUTE_MEMORY_USAGE_CHANGE] = $profile['meta'][self::FINISH_MEMORY_USAGE] - $profile['meta'][self::START_MEMORY_USAGE];
$profile[self::MEMORY_USAGE_CHANGE] = $profile[self::ABSOLUTE_MEMORY_USAGE_CHANGE] - $profile['meta'][self::MEMORY_USAGE_OFFSET];
if ([] !== static::$stack) {
$prefix = &static::$stack[\count(static::$stack) - 1]['meta'];
$prefix[self::TIME_OFFSET] += $profile[self::ABSOLUTE_DURATION];
$prefix[self::MEMORY_USAGE_OFFSET] += $profile[self::ABSOLUTE_MEMORY_USAGE_CHANGE];
}
self::$profiles[] = $profile;
return $profile;
} | php | public static function finish(...$args)
{
if (Debugger::isProductionMode()) {
return false;
}
if ([] === static::$stack) {
throw new \RuntimeException('The stack is empty. Call Hail\Debugger\Profiler::start() first.');
}
$now = \microtime(true);
$memoryUsage = \memory_get_usage(true);
if (!isset($args[1])) {
$label = $args[0] ?? static::getCurrentFileHashLine(1);
} else {
$label = \sprintf(...$args);
}
/** @var array $profile */
$profile = \array_pop(static::$stack);
$profile['meta'][self::FINISH_LABEL] = $label;
$profile['meta'][self::FINISH_TIME] = $now;
$profile['meta'][self::FINISH_MEMORY_USAGE] = $memoryUsage;
$profile[self::ABSOLUTE_DURATION] = $profile['meta'][self::FINISH_TIME] - $profile['meta'][self::START_TIME];
$profile[self::DURATION] = $profile[self::ABSOLUTE_DURATION] - $profile['meta'][self::TIME_OFFSET];
$profile[self::ABSOLUTE_MEMORY_USAGE_CHANGE] = $profile['meta'][self::FINISH_MEMORY_USAGE] - $profile['meta'][self::START_MEMORY_USAGE];
$profile[self::MEMORY_USAGE_CHANGE] = $profile[self::ABSOLUTE_MEMORY_USAGE_CHANGE] - $profile['meta'][self::MEMORY_USAGE_OFFSET];
if ([] !== static::$stack) {
$prefix = &static::$stack[\count(static::$stack) - 1]['meta'];
$prefix[self::TIME_OFFSET] += $profile[self::ABSOLUTE_DURATION];
$prefix[self::MEMORY_USAGE_OFFSET] += $profile[self::ABSOLUTE_MEMORY_USAGE_CHANGE];
}
self::$profiles[] = $profile;
return $profile;
} | [
"public",
"static",
"function",
"finish",
"(",
"...",
"$",
"args",
")",
"{",
"if",
"(",
"Debugger",
"::",
"isProductionMode",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"[",
"]",
"===",
"static",
"::",
"$",
"stack",
")",
"{",
"thro... | Finish profiling and get result
@param array ...$args
@return bool|array profile on success or false on failure
@throws \RuntimeException | [
"Finish",
"profiling",
"and",
"get",
"result"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Profiler.php#L96-L133 | train |
hail-framework/framework | src/Config.php | Config.loadYaml | protected static function loadYaml($file, $ext)
{
$filename = \basename($file);
$dir = \runtime_path('yaml');
$cache = $dir . DIRECTORY_SEPARATOR . substr($filename, 0, -\strlen($ext)) . '.php';
if (@\filemtime($cache) < \filemtime($file)) {
$content = Yaml::parseFile($file);
if (!\is_dir($dir) && !@\mkdir($dir, 0755) && !\is_dir($dir)) {
throw new \RuntimeException('Temp directory permission denied');
}
\file_put_contents($cache, '<?php return ' . static::parseArrayToCode($content) . ';');
if (\function_exists('\opcache_invalidate')) {
\opcache_invalidate($cache, true);
}
}
return include $cache;
} | php | protected static function loadYaml($file, $ext)
{
$filename = \basename($file);
$dir = \runtime_path('yaml');
$cache = $dir . DIRECTORY_SEPARATOR . substr($filename, 0, -\strlen($ext)) . '.php';
if (@\filemtime($cache) < \filemtime($file)) {
$content = Yaml::parseFile($file);
if (!\is_dir($dir) && !@\mkdir($dir, 0755) && !\is_dir($dir)) {
throw new \RuntimeException('Temp directory permission denied');
}
\file_put_contents($cache, '<?php return ' . static::parseArrayToCode($content) . ';');
if (\function_exists('\opcache_invalidate')) {
\opcache_invalidate($cache, true);
}
}
return include $cache;
} | [
"protected",
"static",
"function",
"loadYaml",
"(",
"$",
"file",
",",
"$",
"ext",
")",
"{",
"$",
"filename",
"=",
"\\",
"basename",
"(",
"$",
"file",
")",
";",
"$",
"dir",
"=",
"\\",
"runtime_path",
"(",
"'yaml'",
")",
";",
"$",
"cache",
"=",
"$",
... | Parse a YAML file or load it from the cache
@param $file
@return array|mixed | [
"Parse",
"a",
"YAML",
"file",
"or",
"load",
"it",
"from",
"the",
"cache"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Config.php#L149-L171 | train |
Kajna/K-Core | Core/Container/Container.php | Container.get | public function get($key)
{
if (!$this->offsetExists($key)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $key));
}
return $this->offsetGet($key);
} | php | public function get($key)
{
if (!$this->offsetExists($key)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $key));
}
return $this->offsetGet($key);
} | [
"public",
"function",
"get",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"offsetExists",
"(",
"$",
"key",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Identifier \"%s\" is not defined.'",
",",
"$",
"ke... | Get entry from container
@param string $key
@return mixed
@throws InvalidArgumentException | [
"Get",
"entry",
"from",
"container"
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Container/Container.php#L76-L82 | train |
mirko-pagliai/php-tools | src/FileArray.php | FileArray.delete | public function delete($key)
{
key_exists_or_fail($key, $this->data);
unset($this->data[$key]);
$this->data = array_values($this->data);
return $this;
} | php | public function delete($key)
{
key_exists_or_fail($key, $this->data);
unset($this->data[$key]);
$this->data = array_values($this->data);
return $this;
} | [
"public",
"function",
"delete",
"(",
"$",
"key",
")",
"{",
"key_exists_or_fail",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"data",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
")",
";",
"$",
"this",
"->",
"data",
"=",
... | Deletes a value from its key number.
Note that the keys will be re-ordered.
@param int $key Key number
@return $this
@throws KeyNotExistsException
@uses $data | [
"Deletes",
"a",
"value",
"from",
"its",
"key",
"number",
"."
] | 46003b05490de4b570b46c6377f1e09139ffe43b | https://github.com/mirko-pagliai/php-tools/blob/46003b05490de4b570b46c6377f1e09139ffe43b/src/FileArray.php#L74-L81 | train |
hail-framework/framework | src/Debugger/Debugger.php | Debugger.enable | public static function enable($mode = null, string $logDirectory = null, string $email = null): void
{
if ($mode !== null || self::$productionMode === null) {
self::$mode = $mode;
if (\is_bool($mode)) {
self::$productionMode = $mode;
}
}
// logging configuration
if ($email !== null) {
self::$email = $email;
}
if ($logDirectory) {
if (!preg_match('#([a-z]+:)?[/\\\\]#Ai', $logDirectory)) {
self::exceptionHandler(new \RuntimeException('Logging directory must be absolute path.'));
} elseif (!is_dir(self::$logDirectory)) {
self::exceptionHandler(new \RuntimeException("Logging directory '" . $logDirectory . "' is not found."));
}
self::$logDirectory = $logDirectory;
}
if (self::$enabled) {
return;
}
self::$reserved = \str_repeat('t', 30000);
self::$obLevel = \ob_get_level();
// php configuration
if (self::$iniSet = \function_exists('\ini_set')) {
\ini_set('html_errors', '0');
\ini_set('log_errors', '0');
}
\error_reporting(E_ALL);
\register_shutdown_function([__CLASS__, 'shutdownHandler']);
\set_exception_handler([__CLASS__, 'exceptionHandler']);
\set_error_handler([__CLASS__, 'errorHandler']);
self::$enabled = true;
self::$enabledTime = \microtime(true);
} | php | public static function enable($mode = null, string $logDirectory = null, string $email = null): void
{
if ($mode !== null || self::$productionMode === null) {
self::$mode = $mode;
if (\is_bool($mode)) {
self::$productionMode = $mode;
}
}
// logging configuration
if ($email !== null) {
self::$email = $email;
}
if ($logDirectory) {
if (!preg_match('#([a-z]+:)?[/\\\\]#Ai', $logDirectory)) {
self::exceptionHandler(new \RuntimeException('Logging directory must be absolute path.'));
} elseif (!is_dir(self::$logDirectory)) {
self::exceptionHandler(new \RuntimeException("Logging directory '" . $logDirectory . "' is not found."));
}
self::$logDirectory = $logDirectory;
}
if (self::$enabled) {
return;
}
self::$reserved = \str_repeat('t', 30000);
self::$obLevel = \ob_get_level();
// php configuration
if (self::$iniSet = \function_exists('\ini_set')) {
\ini_set('html_errors', '0');
\ini_set('log_errors', '0');
}
\error_reporting(E_ALL);
\register_shutdown_function([__CLASS__, 'shutdownHandler']);
\set_exception_handler([__CLASS__, 'exceptionHandler']);
\set_error_handler([__CLASS__, 'errorHandler']);
self::$enabled = true;
self::$enabledTime = \microtime(true);
} | [
"public",
"static",
"function",
"enable",
"(",
"$",
"mode",
"=",
"null",
",",
"string",
"$",
"logDirectory",
"=",
"null",
",",
"string",
"$",
"email",
"=",
"null",
")",
":",
"void",
"{",
"if",
"(",
"$",
"mode",
"!==",
"null",
"||",
"self",
"::",
"$... | Enables displaying or logging errors and exceptions.
@param mixed $mode production, development mode, autodetection or IP address(es) whitelist.
@param string $logDirectory error log directory
@param string $email administrator email; enables email sending in production mode
@return void | [
"Enables",
"displaying",
"or",
"logging",
"errors",
"and",
"exceptions",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Debugger.php#L210-L256 | train |
hail-framework/framework | src/Debugger/Debugger.php | Debugger.shutdownHandler | public static function shutdownHandler(): void
{
if (!self::$reserved) {
return;
}
$error = \error_get_last();
if (\in_array($error['type'],
[E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE, E_RECOVERABLE_ERROR, E_USER_ERROR], true
)) {
self::exceptionHandler(
Helpers::fixStack(
new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'])
), false
);
}
} | php | public static function shutdownHandler(): void
{
if (!self::$reserved) {
return;
}
$error = \error_get_last();
if (\in_array($error['type'],
[E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE, E_RECOVERABLE_ERROR, E_USER_ERROR], true
)) {
self::exceptionHandler(
Helpers::fixStack(
new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'])
), false
);
}
} | [
"public",
"static",
"function",
"shutdownHandler",
"(",
")",
":",
"void",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"reserved",
")",
"{",
"return",
";",
"}",
"$",
"error",
"=",
"\\",
"error_get_last",
"(",
")",
";",
"if",
"(",
"\\",
"in_array",
"(",
... | Shutdown handler to catch fatal errors and execute of the planned activities.
@return void
@internal | [
"Shutdown",
"handler",
"to",
"catch",
"fatal",
"errors",
"and",
"execute",
"of",
"the",
"planned",
"activities",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Debugger.php#L372-L388 | train |
hail-framework/framework | src/Debugger/Debugger.php | Debugger.dump | public static function dump($var, bool $return = false)
{
if ($return) {
\ob_start();
Dumper::dump($var, [
Dumper::DEPTH => self::$maxDepth,
Dumper::TRUNCATE => self::$maxLength,
]);
return \ob_get_clean();
}
if (!self::isProductionMode()) {
Dumper::dump($var, [
Dumper::DEPTH => self::$maxDepth,
Dumper::TRUNCATE => self::$maxLength,
Dumper::LOCATION => self::$showLocation,
]);
}
return $var;
} | php | public static function dump($var, bool $return = false)
{
if ($return) {
\ob_start();
Dumper::dump($var, [
Dumper::DEPTH => self::$maxDepth,
Dumper::TRUNCATE => self::$maxLength,
]);
return \ob_get_clean();
}
if (!self::isProductionMode()) {
Dumper::dump($var, [
Dumper::DEPTH => self::$maxDepth,
Dumper::TRUNCATE => self::$maxLength,
Dumper::LOCATION => self::$showLocation,
]);
}
return $var;
} | [
"public",
"static",
"function",
"dump",
"(",
"$",
"var",
",",
"bool",
"$",
"return",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"return",
")",
"{",
"\\",
"ob_start",
"(",
")",
";",
"Dumper",
"::",
"dump",
"(",
"$",
"var",
",",
"[",
"Dumper",
"::",
... | Dumps information about a variable in readable format.
@tracySkipLocation
@param mixed $var variable to dump
@param bool $return return output instead of printing it? (bypasses $productionMode)
@return mixed variable itself or dump | [
"Dumps",
"information",
"about",
"a",
"variable",
"in",
"readable",
"format",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Debugger.php#L746-L767 | train |
hail-framework/framework | src/Debugger/Debugger.php | Debugger.barDump | public static function barDump($var, string $title = null, array $options = null)
{
if (!self::isProductionMode()) {
static $panel;
if (!$panel) {
self::getBar()->addPanel($panel = new Bar\DefaultPanel('dumps'), 'Tracy:dumps');
}
$panel->data[] = [
'title' => $title,
'dump' => Dumper::toHtml($var, $options + [
Dumper::DEPTH => self::$maxDepth,
Dumper::TRUNCATE => self::$maxLength,
Dumper::LOCATION => self::$showLocation ?: Dumper::LOCATION_CLASS | Dumper::LOCATION_SOURCE,
]),
];
}
return $var;
} | php | public static function barDump($var, string $title = null, array $options = null)
{
if (!self::isProductionMode()) {
static $panel;
if (!$panel) {
self::getBar()->addPanel($panel = new Bar\DefaultPanel('dumps'), 'Tracy:dumps');
}
$panel->data[] = [
'title' => $title,
'dump' => Dumper::toHtml($var, $options + [
Dumper::DEPTH => self::$maxDepth,
Dumper::TRUNCATE => self::$maxLength,
Dumper::LOCATION => self::$showLocation ?: Dumper::LOCATION_CLASS | Dumper::LOCATION_SOURCE,
]),
];
}
return $var;
} | [
"public",
"static",
"function",
"barDump",
"(",
"$",
"var",
",",
"string",
"$",
"title",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"isProductionMode",
"(",
")",
")",
"{",
"static",
"$",
"panel",
... | Dumps information about a variable in Tracy Debug Bar.
@tracySkipLocation
@param mixed $var variable to dump
@param string $title optional title
@param array $options dumper options
@return mixed variable itself | [
"Dumps",
"information",
"about",
"a",
"variable",
"in",
"Tracy",
"Debug",
"Bar",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Debugger.php#L797-L815 | train |
hail-framework/framework | src/Debugger/Debugger.php | Debugger.log | public static function log($message, string $priority = self::INFO): ?string
{
$logger = self::sendToLogger(self::getLogger(), $priority, $message);
if ($logger instanceof Logger) {
return $logger->getLastExceptionFile();
}
return null;
} | php | public static function log($message, string $priority = self::INFO): ?string
{
$logger = self::sendToLogger(self::getLogger(), $priority, $message);
if ($logger instanceof Logger) {
return $logger->getLastExceptionFile();
}
return null;
} | [
"public",
"static",
"function",
"log",
"(",
"$",
"message",
",",
"string",
"$",
"priority",
"=",
"self",
"::",
"INFO",
")",
":",
"?",
"string",
"{",
"$",
"logger",
"=",
"self",
"::",
"sendToLogger",
"(",
"self",
"::",
"getLogger",
"(",
")",
",",
"$",... | Logs message or exception.
@param mixed $message
@param string $priority
@return string|null | [
"Logs",
"message",
"or",
"exception",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Debugger.php#L826-L835 | train |
hail-framework/framework | src/Debugger/Debugger.php | Debugger.chromeLog | public static function chromeLog($message, string $priority = self::DEBUG): bool
{
if (self::$showChromeLogger && !self::isProductionMode()) {
self::sendToLogger(self::getChromeLogger(), $priority, $message);
return true;
}
return false;
} | php | public static function chromeLog($message, string $priority = self::DEBUG): bool
{
if (self::$showChromeLogger && !self::isProductionMode()) {
self::sendToLogger(self::getChromeLogger(), $priority, $message);
return true;
}
return false;
} | [
"public",
"static",
"function",
"chromeLog",
"(",
"$",
"message",
",",
"string",
"$",
"priority",
"=",
"self",
"::",
"DEBUG",
")",
":",
"bool",
"{",
"if",
"(",
"self",
"::",
"$",
"showChromeLogger",
"&&",
"!",
"self",
"::",
"isProductionMode",
"(",
")",
... | Sends message to ChromeLogger console.
@param mixed $message message to log
@param string $priority
@return bool was successful? | [
"Sends",
"message",
"to",
"ChromeLogger",
"console",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Debugger.php#L858-L867 | train |
mcrumm/pecan | src/Drupe.php | Drupe.checkRunning | public function checkRunning(Timer $timer)
{
if (!$this->running) {
$timer->cancel();
// @codeCoverageIgnoreStart
exit($this->exitCode);
// @codeCoverageIgnoreEnd
}
} | php | public function checkRunning(Timer $timer)
{
if (!$this->running) {
$timer->cancel();
// @codeCoverageIgnoreStart
exit($this->exitCode);
// @codeCoverageIgnoreEnd
}
} | [
"public",
"function",
"checkRunning",
"(",
"Timer",
"$",
"timer",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"running",
")",
"{",
"$",
"timer",
"->",
"cancel",
"(",
")",
";",
"// @codeCoverageIgnoreStart",
"exit",
"(",
"$",
"this",
"->",
"exitCode",
... | Checks whether or not the shell is still running.
@param Timer $timer | [
"Checks",
"whether",
"or",
"not",
"the",
"shell",
"is",
"still",
"running",
"."
] | f35f01249587a4df45c7d3ab78f3e51919471177 | https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Drupe.php#L151-L159 | train |
htmlburger/wpemerge-cli | src/Presets/FilesystemTrait.php | FilesystemTrait.copy | protected function copy( $files ) {
$failures = [];
foreach ( $files as $source => $destination ) {
if ( file_exists( $destination ) ) {
$failures[ $source ] = $destination;
continue;
}
$directory = dirname( $destination );
if ( ! file_exists( $directory ) ) {
mkdir( $directory );
}
copy( $source, $destination );
}
return $failures;
} | php | protected function copy( $files ) {
$failures = [];
foreach ( $files as $source => $destination ) {
if ( file_exists( $destination ) ) {
$failures[ $source ] = $destination;
continue;
}
$directory = dirname( $destination );
if ( ! file_exists( $directory ) ) {
mkdir( $directory );
}
copy( $source, $destination );
}
return $failures;
} | [
"protected",
"function",
"copy",
"(",
"$",
"files",
")",
"{",
"$",
"failures",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"source",
"=>",
"$",
"destination",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"destination",
")",
")",
"... | Copy a list of files, returning an array of failures.
@param array $files
@return array | [
"Copy",
"a",
"list",
"of",
"files",
"returning",
"an",
"array",
"of",
"failures",
"."
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/FilesystemTrait.php#L22-L40 | train |
htmlburger/wpemerge-cli | src/Presets/FilesystemTrait.php | FilesystemTrait.stringHasStatement | protected function stringHasStatement( $haystack, $needle ) {
$pattern = '~^\s*(' . preg_quote( $needle, '~' ) . ')\s*$~m';
return (bool) preg_match( $pattern, $haystack );
} | php | protected function stringHasStatement( $haystack, $needle ) {
$pattern = '~^\s*(' . preg_quote( $needle, '~' ) . ')\s*$~m';
return (bool) preg_match( $pattern, $haystack );
} | [
"protected",
"function",
"stringHasStatement",
"(",
"$",
"haystack",
",",
"$",
"needle",
")",
"{",
"$",
"pattern",
"=",
"'~^\\s*('",
".",
"preg_quote",
"(",
"$",
"needle",
",",
"'~'",
")",
".",
"')\\s*$~m'",
";",
"return",
"(",
"bool",
")",
"preg_match",
... | Get whether a string has a given statement present.
@param string $haystack
@param string $needle
@return boolean | [
"Get",
"whether",
"a",
"string",
"has",
"a",
"given",
"statement",
"present",
"."
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/FilesystemTrait.php#L62-L65 | train |
htmlburger/wpemerge-cli | src/Presets/FilesystemTrait.php | FilesystemTrait.appendUniqueStatement | protected function appendUniqueStatement( $filepath, $statement ) {
$contents = file_get_contents( $filepath );
if ( $this->stringHasStatement( $contents, $statement ) ) {
return;
}
$eol = $this->getEol( $contents );
$content_lines = explode( "\n", $contents );
$last_line = trim( $content_lines[ count( $content_lines ) - 1 ] );
if ( empty( $last_line ) ) {
$contents .= $statement . $eol;
} else {
$contents .= $eol . $statement;
}
file_put_contents( $filepath, $contents );
} | php | protected function appendUniqueStatement( $filepath, $statement ) {
$contents = file_get_contents( $filepath );
if ( $this->stringHasStatement( $contents, $statement ) ) {
return;
}
$eol = $this->getEol( $contents );
$content_lines = explode( "\n", $contents );
$last_line = trim( $content_lines[ count( $content_lines ) - 1 ] );
if ( empty( $last_line ) ) {
$contents .= $statement . $eol;
} else {
$contents .= $eol . $statement;
}
file_put_contents( $filepath, $contents );
} | [
"protected",
"function",
"appendUniqueStatement",
"(",
"$",
"filepath",
",",
"$",
"statement",
")",
"{",
"$",
"contents",
"=",
"file_get_contents",
"(",
"$",
"filepath",
")",
";",
"if",
"(",
"$",
"this",
"->",
"stringHasStatement",
"(",
"$",
"contents",
",",... | Append a statement to file.
@param string $filepath
@param string $statement
@return void | [
"Append",
"a",
"statement",
"to",
"file",
"."
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/FilesystemTrait.php#L74-L92 | train |
Kajna/K-Core | Core/Session/Handlers/DatabaseSessionHandler.php | DatabaseSessionHandler.read | public function read($id)
{
$stmt = $this->db->prepare("SELECT session_data FROM " . $this->tableName . " WHERE session_id = :id");
$stmt->execute(['id' => $id]);
return base64_decode($stmt->fetchColumn());
} | php | public function read($id)
{
$stmt = $this->db->prepare("SELECT session_data FROM " . $this->tableName . " WHERE session_id = :id");
$stmt->execute(['id' => $id]);
return base64_decode($stmt->fetchColumn());
} | [
"public",
"function",
"read",
"(",
"$",
"id",
")",
"{",
"$",
"stmt",
"=",
"$",
"this",
"->",
"db",
"->",
"prepare",
"(",
"\"SELECT session_data FROM \"",
".",
"$",
"this",
"->",
"tableName",
".",
"\" WHERE session_id = :id\"",
")",
";",
"$",
"stmt",
"->",
... | Read the session
@param int $id
@return string string of the session | [
"Read",
"the",
"session"
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Session/Handlers/DatabaseSessionHandler.php#L88-L93 | train |
hail-framework/framework | src/Mail/Message.php | Message.formatEmail | private function formatEmail(string $email, string $name = null): array
{
if (!$name && \preg_match('#^(.+) +<(.*)>\z#', $email, $matches)) {
return [$matches[2] => $matches[1]];
}
return [$email => $name];
} | php | private function formatEmail(string $email, string $name = null): array
{
if (!$name && \preg_match('#^(.+) +<(.*)>\z#', $email, $matches)) {
return [$matches[2] => $matches[1]];
}
return [$email => $name];
} | [
"private",
"function",
"formatEmail",
"(",
"string",
"$",
"email",
",",
"string",
"$",
"name",
"=",
"null",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"name",
"&&",
"\\",
"preg_match",
"(",
"'#^(.+) +<(.*)>\\z#'",
",",
"$",
"email",
",",
"$",
"matche... | Formats recipient email.
@param string $email
@param string|null $name
@return array | [
"Formats",
"recipient",
"email",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/Message.php#L175-L182 | train |
hail-framework/framework | src/Mail/Message.php | Message.setHtmlBody | public function setHtmlBody(string $html, string $basePath = null)
{
if ($basePath) {
$cids = [];
$matches = Strings::matchAll(
$html,
'#
(<img[^<>]*\s src\s*=\s*
|<body[^<>]*\s background\s*=\s*
|<[^<>]+\s style\s*=\s* ["\'][^"\'>]+[:\s] url\(
|<style[^>]*>[^<]+ [:\s] url\()
(["\']?)(?![a-z]+:|[/\\#])([^"\'>)\s]+)
|\[\[ ([\w()+./@~-]+) \]\]
#ix',
PREG_OFFSET_CAPTURE
);
foreach (\array_reverse($matches) as $m) {
$file = \rtrim($basePath, '/\\') . '/' . (isset($m[4]) ? $m[4][0] : \urldecode($m[3][0]));
if (!isset($cids[$file])) {
$cids[$file] = \substr($this->addEmbeddedFile($file)->getHeader('Content-ID'), 1, -1);
}
$html = \substr_replace($html,
"{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}",
$m[0][1], \strlen($m[0][0])
);
}
}
if ($this->getSubject() == null) { // intentionally ==
$html = Strings::replace($html, '#<title>(.+?)</title>#is', function (array $m): void {
$this->setSubject(\html_entity_decode($m[1], ENT_QUOTES, 'UTF-8'));
});
}
$this->htmlBody = \ltrim(\str_replace("\r", '', $html), "\n");
if ($html !== '' && $this->getBody() === '') {
$this->setBody($this->buildText($html));
}
return $this;
} | php | public function setHtmlBody(string $html, string $basePath = null)
{
if ($basePath) {
$cids = [];
$matches = Strings::matchAll(
$html,
'#
(<img[^<>]*\s src\s*=\s*
|<body[^<>]*\s background\s*=\s*
|<[^<>]+\s style\s*=\s* ["\'][^"\'>]+[:\s] url\(
|<style[^>]*>[^<]+ [:\s] url\()
(["\']?)(?![a-z]+:|[/\\#])([^"\'>)\s]+)
|\[\[ ([\w()+./@~-]+) \]\]
#ix',
PREG_OFFSET_CAPTURE
);
foreach (\array_reverse($matches) as $m) {
$file = \rtrim($basePath, '/\\') . '/' . (isset($m[4]) ? $m[4][0] : \urldecode($m[3][0]));
if (!isset($cids[$file])) {
$cids[$file] = \substr($this->addEmbeddedFile($file)->getHeader('Content-ID'), 1, -1);
}
$html = \substr_replace($html,
"{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}",
$m[0][1], \strlen($m[0][0])
);
}
}
if ($this->getSubject() == null) { // intentionally ==
$html = Strings::replace($html, '#<title>(.+?)</title>#is', function (array $m): void {
$this->setSubject(\html_entity_decode($m[1], ENT_QUOTES, 'UTF-8'));
});
}
$this->htmlBody = \ltrim(\str_replace("\r", '', $html), "\n");
if ($html !== '' && $this->getBody() === '') {
$this->setBody($this->buildText($html));
}
return $this;
} | [
"public",
"function",
"setHtmlBody",
"(",
"string",
"$",
"html",
",",
"string",
"$",
"basePath",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"basePath",
")",
"{",
"$",
"cids",
"=",
"[",
"]",
";",
"$",
"matches",
"=",
"Strings",
"::",
"matchAll",
"(",
"$... | Sets HTML body.
@param string $html
@param string|null $basePath
@return $this
@throws RegexpException | [
"Sets",
"HTML",
"body",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/Message.php#L243-L284 | train |
hail-framework/framework | src/Mail/Message.php | Message.addEmbeddedFile | public function addEmbeddedFile(string $file, string $content = null, string $contentType = null): MimePart
{
return $this->inlines[$file] = $this->createAttachment($file, $content, $contentType, 'inline')
->setHeader('Content-ID', $this->getRandomId());
} | php | public function addEmbeddedFile(string $file, string $content = null, string $contentType = null): MimePart
{
return $this->inlines[$file] = $this->createAttachment($file, $content, $contentType, 'inline')
->setHeader('Content-ID', $this->getRandomId());
} | [
"public",
"function",
"addEmbeddedFile",
"(",
"string",
"$",
"file",
",",
"string",
"$",
"content",
"=",
"null",
",",
"string",
"$",
"contentType",
"=",
"null",
")",
":",
"MimePart",
"{",
"return",
"$",
"this",
"->",
"inlines",
"[",
"$",
"file",
"]",
"... | Adds embedded file.
@param string $file
@param string|null $content
@param string|null $contentType
@return MimePart | [
"Adds",
"embedded",
"file",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/Message.php#L305-L309 | train |
hail-framework/framework | src/Mail/Message.php | Message.addAttachment | public function addAttachment(string $file, string $content = null, string $contentType = null): MimePart
{
return $this->attachments[] = $this->createAttachment($file, $content, $contentType, 'attachment');
} | php | public function addAttachment(string $file, string $content = null, string $contentType = null): MimePart
{
return $this->attachments[] = $this->createAttachment($file, $content, $contentType, 'attachment');
} | [
"public",
"function",
"addAttachment",
"(",
"string",
"$",
"file",
",",
"string",
"$",
"content",
"=",
"null",
",",
"string",
"$",
"contentType",
"=",
"null",
")",
":",
"MimePart",
"{",
"return",
"$",
"this",
"->",
"attachments",
"[",
"]",
"=",
"$",
"t... | Adds attachment.
@param string $file
@param string|null $content
@param string|null $contentType
@return MimePart | [
"Adds",
"attachment",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/Message.php#L336-L339 | train |
hail-framework/framework | src/Mail/Message.php | Message.createAttachment | private function createAttachment(
string $file,
string $content = null,
string $contentType = null,
string $disposition
): MimePart {
$part = new MimePart;
if ($content === null) {
$content = @\file_get_contents($file); // @ is escalated to exception
if ($content === false) {
throw new FileNotFoundException("Unable to read file '$file'.");
}
}
if (!$contentType) {
$contentType = MimeType::getMimeTypeByContent($content);
}
if (!\strcasecmp($contentType, 'message/rfc822')) { // not allowed for attached files
$contentType = 'application/octet-stream';
} elseif (!\strcasecmp($contentType, 'image/svg')) { // Troublesome for some mailers...
$contentType = 'image/svg+xml';
}
$part->setBody($content);
$part->setContentType($contentType);
$part->setEncoding(\preg_match('#(multipart|message)/#A', $contentType) ?
self::ENCODING_8BIT : self::ENCODING_BASE64);
$part->setHeader('Content-Disposition',
$disposition . '; filename="' . Strings::fixEncoding(\basename($file)) . '"');
return $part;
} | php | private function createAttachment(
string $file,
string $content = null,
string $contentType = null,
string $disposition
): MimePart {
$part = new MimePart;
if ($content === null) {
$content = @\file_get_contents($file); // @ is escalated to exception
if ($content === false) {
throw new FileNotFoundException("Unable to read file '$file'.");
}
}
if (!$contentType) {
$contentType = MimeType::getMimeTypeByContent($content);
}
if (!\strcasecmp($contentType, 'message/rfc822')) { // not allowed for attached files
$contentType = 'application/octet-stream';
} elseif (!\strcasecmp($contentType, 'image/svg')) { // Troublesome for some mailers...
$contentType = 'image/svg+xml';
}
$part->setBody($content);
$part->setContentType($contentType);
$part->setEncoding(\preg_match('#(multipart|message)/#A', $contentType) ?
self::ENCODING_8BIT : self::ENCODING_BASE64);
$part->setHeader('Content-Disposition',
$disposition . '; filename="' . Strings::fixEncoding(\basename($file)) . '"');
return $part;
} | [
"private",
"function",
"createAttachment",
"(",
"string",
"$",
"file",
",",
"string",
"$",
"content",
"=",
"null",
",",
"string",
"$",
"contentType",
"=",
"null",
",",
"string",
"$",
"disposition",
")",
":",
"MimePart",
"{",
"$",
"part",
"=",
"new",
"Mim... | Creates file MIME part.
@param string $file
@param string|null $content
@param string|null $contentType
@param string $disposition
@return MimePart | [
"Creates",
"file",
"MIME",
"part",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/Message.php#L363-L395 | train |
hail-framework/framework | src/Mail/Message.php | Message.build | protected function build()
{
$mail = clone $this;
$mail->setHeader('Message-ID', $this->getRandomId());
$cursor = $mail;
if ($mail->attachments) {
$tmp = $cursor->setContentType('multipart/mixed');
$cursor = $cursor->addPart();
foreach ($mail->attachments as $value) {
$tmp->addPart($value);
}
}
if ($mail->htmlBody !== '') {
$tmp = $cursor->setContentType('multipart/alternative');
$cursor = $cursor->addPart();
$alt = $tmp->addPart();
if ($mail->inlines) {
$tmp = $alt->setContentType('multipart/related');
$alt = $alt->addPart();
foreach ($mail->inlines as $value) {
$tmp->addPart($value);
}
}
$alt->setContentType('text/html', 'UTF-8')
->setEncoding(\preg_match('#[^\n]{990}#', $mail->htmlBody)
? self::ENCODING_QUOTED_PRINTABLE
: (\preg_match('#[\x80-\xFF]#', $mail->htmlBody) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
->setBody($mail->htmlBody);
}
$text = $mail->getBody();
$mail->setBody('');
$cursor->setContentType('text/plain', 'UTF-8')
->setEncoding(\preg_match('#[^\n]{990}#', $text)
? self::ENCODING_QUOTED_PRINTABLE
: (\preg_match('#[\x80-\xFF]#', $text) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
->setBody($text);
return $mail;
} | php | protected function build()
{
$mail = clone $this;
$mail->setHeader('Message-ID', $this->getRandomId());
$cursor = $mail;
if ($mail->attachments) {
$tmp = $cursor->setContentType('multipart/mixed');
$cursor = $cursor->addPart();
foreach ($mail->attachments as $value) {
$tmp->addPart($value);
}
}
if ($mail->htmlBody !== '') {
$tmp = $cursor->setContentType('multipart/alternative');
$cursor = $cursor->addPart();
$alt = $tmp->addPart();
if ($mail->inlines) {
$tmp = $alt->setContentType('multipart/related');
$alt = $alt->addPart();
foreach ($mail->inlines as $value) {
$tmp->addPart($value);
}
}
$alt->setContentType('text/html', 'UTF-8')
->setEncoding(\preg_match('#[^\n]{990}#', $mail->htmlBody)
? self::ENCODING_QUOTED_PRINTABLE
: (\preg_match('#[\x80-\xFF]#', $mail->htmlBody) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
->setBody($mail->htmlBody);
}
$text = $mail->getBody();
$mail->setBody('');
$cursor->setContentType('text/plain', 'UTF-8')
->setEncoding(\preg_match('#[^\n]{990}#', $text)
? self::ENCODING_QUOTED_PRINTABLE
: (\preg_match('#[\x80-\xFF]#', $text) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
->setBody($text);
return $mail;
} | [
"protected",
"function",
"build",
"(",
")",
"{",
"$",
"mail",
"=",
"clone",
"$",
"this",
";",
"$",
"mail",
"->",
"setHeader",
"(",
"'Message-ID'",
",",
"$",
"this",
"->",
"getRandomId",
"(",
")",
")",
";",
"$",
"cursor",
"=",
"$",
"mail",
";",
"if"... | Builds email. Does not modify itself, but returns a new object.
@return static | [
"Builds",
"email",
".",
"Does",
"not",
"modify",
"itself",
"but",
"returns",
"a",
"new",
"object",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/Message.php#L415-L456 | train |
hail-framework/framework | src/Mail/Message.php | Message.buildText | protected function buildText(string $html): string
{
$text = Strings::replace($html, [
'#<(style|script|head).*</\\1>#Uis' => '',
'#<t[dh][ >]#i' => ' $0',
'#<a\s[^>]*href=(?|"([^"]+)"|\'([^\']+)\')[^>]*>(.*?)</a>#is' => '$2 <$1>',
'#[\r\n]+#' => ' ',
'#<(/?p|/?h\d|li|br|/tr)[ >/]#i' => "\n$0",
]);
$text = \html_entity_decode(\strip_tags($text), ENT_QUOTES, 'UTF-8');
$text = Strings::replace($text, '#[ \t]+#', ' ');
return \trim($text);
} | php | protected function buildText(string $html): string
{
$text = Strings::replace($html, [
'#<(style|script|head).*</\\1>#Uis' => '',
'#<t[dh][ >]#i' => ' $0',
'#<a\s[^>]*href=(?|"([^"]+)"|\'([^\']+)\')[^>]*>(.*?)</a>#is' => '$2 <$1>',
'#[\r\n]+#' => ' ',
'#<(/?p|/?h\d|li|br|/tr)[ >/]#i' => "\n$0",
]);
$text = \html_entity_decode(\strip_tags($text), ENT_QUOTES, 'UTF-8');
$text = Strings::replace($text, '#[ \t]+#', ' ');
return \trim($text);
} | [
"protected",
"function",
"buildText",
"(",
"string",
"$",
"html",
")",
":",
"string",
"{",
"$",
"text",
"=",
"Strings",
"::",
"replace",
"(",
"$",
"html",
",",
"[",
"'#<(style|script|head).*</\\\\1>#Uis'",
"=>",
"''",
",",
"'#<t[dh][ >]#i'",
"=>",
"' $0'",
"... | Builds text content.
@param string $html
@return string
@throws RegexpException | [
"Builds",
"text",
"content",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/Message.php#L467-L480 | train |
hail-framework/framework | src/Mail/MimePart.php | MimePart.getEncodedHeader | public function getEncodedHeader(string $name): ?string
{
$offset = \strlen($name) + 2; // colon + space
if (!isset($this->headers[$name])) {
return null;
}
if (\is_array($this->headers[$name])) {
$s = '';
foreach ($this->headers[$name] as $email => $mailer) {
if ($mailer != null) { // intentionally ==
$s .= self::encodeHeader($mailer, $offset, true);
$email = " <$email>";
}
$s .= self::append($email . ',', $offset);
}
return \ltrim(\substr($s, 0, -1)); // last comma
}
if (\preg_match('#^(\S+; (?:file)?name=)"(.*)"\z#', $this->headers[$name], $m)) { // Content-Disposition
$offset += \strlen($m[1]);
return $m[1] . '"' . self::encodeHeader($m[2], $offset) . '"';
}
return \ltrim(self::encodeHeader($this->headers[$name], $offset));
} | php | public function getEncodedHeader(string $name): ?string
{
$offset = \strlen($name) + 2; // colon + space
if (!isset($this->headers[$name])) {
return null;
}
if (\is_array($this->headers[$name])) {
$s = '';
foreach ($this->headers[$name] as $email => $mailer) {
if ($mailer != null) { // intentionally ==
$s .= self::encodeHeader($mailer, $offset, true);
$email = " <$email>";
}
$s .= self::append($email . ',', $offset);
}
return \ltrim(\substr($s, 0, -1)); // last comma
}
if (\preg_match('#^(\S+; (?:file)?name=)"(.*)"\z#', $this->headers[$name], $m)) { // Content-Disposition
$offset += \strlen($m[1]);
return $m[1] . '"' . self::encodeHeader($m[2], $offset) . '"';
}
return \ltrim(self::encodeHeader($this->headers[$name], $offset));
} | [
"public",
"function",
"getEncodedHeader",
"(",
"string",
"$",
"name",
")",
":",
"?",
"string",
"{",
"$",
"offset",
"=",
"\\",
"strlen",
"(",
"$",
"name",
")",
"+",
"2",
";",
"// colon + space",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"header... | Returns an encoded header. | [
"Returns",
"an",
"encoded",
"header",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/MimePart.php#L126-L155 | train |
hail-framework/framework | src/Mail/MimePart.php | MimePart.setContentType | public function setContentType(string $contentType, string $charset = null)
{
$this->setHeader('Content-Type', $contentType . ($charset ? "; charset=$charset" : ''));
return $this;
} | php | public function setContentType(string $contentType, string $charset = null)
{
$this->setHeader('Content-Type', $contentType . ($charset ? "; charset=$charset" : ''));
return $this;
} | [
"public",
"function",
"setContentType",
"(",
"string",
"$",
"contentType",
",",
"string",
"$",
"charset",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"setHeader",
"(",
"'Content-Type'",
",",
"$",
"contentType",
".",
"(",
"$",
"charset",
"?",
"\"; charset=$char... | Sets Content-Type header.
@return static | [
"Sets",
"Content",
"-",
"Type",
"header",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/MimePart.php#L172-L177 | train |
hail-framework/framework | src/Mail/MimePart.php | MimePart.addPart | public function addPart(self $part = null): self
{
return $this->parts[] = $part === null ? new self : $part;
} | php | public function addPart(self $part = null): self
{
return $this->parts[] = $part === null ? new self : $part;
} | [
"public",
"function",
"addPart",
"(",
"self",
"$",
"part",
"=",
"null",
")",
":",
"self",
"{",
"return",
"$",
"this",
"->",
"parts",
"[",
"]",
"=",
"$",
"part",
"===",
"null",
"?",
"new",
"self",
":",
"$",
"part",
";",
"}"
] | Adds or creates new multipart. | [
"Adds",
"or",
"creates",
"new",
"multipart",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/MimePart.php#L205-L208 | train |
hail-framework/framework | src/Mail/MimePart.php | MimePart.getEncodedMessage | public function getEncodedMessage(): string
{
$output = '';
$boundary = '--------' . Generators::random();
foreach ($this->headers as $name => $value) {
$output .= $name . ': ' . $this->getEncodedHeader($name);
if ($this->parts && $name === 'Content-Type') {
$output .= ';' . self::EOL . "\tboundary=\"$boundary\"";
}
$output .= self::EOL;
}
$output .= self::EOL;
$body = $this->body;
if ($body !== '') {
switch ($this->getEncoding()) {
case self::ENCODING_QUOTED_PRINTABLE:
$output .= \quoted_printable_encode($body);
break;
case self::ENCODING_BASE64:
$output .= \rtrim(\chunk_split(\base64_encode($body), self::LINE_LENGTH, self::EOL));
break;
case self::ENCODING_7BIT:
$body = \preg_replace('#[\x80-\xFF]+#', '', $body);
// break intentionally omitted
case self::ENCODING_8BIT:
$output .= \str_replace(["\x00", "\r", "\n"], ['', '', self::EOL], $body);
break;
default:
throw new RuntimeException('Unknown encoding.');
}
}
if ($this->parts) {
if (\substr($output, -\strlen(self::EOL)) !== self::EOL) {
$output .= self::EOL;
}
foreach ($this->parts as $part) {
$output .= '--' . $boundary . self::EOL . $part->getEncodedMessage() . self::EOL;
}
$output .= '--' . $boundary . '--';
}
return $output;
} | php | public function getEncodedMessage(): string
{
$output = '';
$boundary = '--------' . Generators::random();
foreach ($this->headers as $name => $value) {
$output .= $name . ': ' . $this->getEncodedHeader($name);
if ($this->parts && $name === 'Content-Type') {
$output .= ';' . self::EOL . "\tboundary=\"$boundary\"";
}
$output .= self::EOL;
}
$output .= self::EOL;
$body = $this->body;
if ($body !== '') {
switch ($this->getEncoding()) {
case self::ENCODING_QUOTED_PRINTABLE:
$output .= \quoted_printable_encode($body);
break;
case self::ENCODING_BASE64:
$output .= \rtrim(\chunk_split(\base64_encode($body), self::LINE_LENGTH, self::EOL));
break;
case self::ENCODING_7BIT:
$body = \preg_replace('#[\x80-\xFF]+#', '', $body);
// break intentionally omitted
case self::ENCODING_8BIT:
$output .= \str_replace(["\x00", "\r", "\n"], ['', '', self::EOL], $body);
break;
default:
throw new RuntimeException('Unknown encoding.');
}
}
if ($this->parts) {
if (\substr($output, -\strlen(self::EOL)) !== self::EOL) {
$output .= self::EOL;
}
foreach ($this->parts as $part) {
$output .= '--' . $boundary . self::EOL . $part->getEncodedMessage() . self::EOL;
}
$output .= '--' . $boundary . '--';
}
return $output;
} | [
"public",
"function",
"getEncodedMessage",
"(",
")",
":",
"string",
"{",
"$",
"output",
"=",
"''",
";",
"$",
"boundary",
"=",
"'--------'",
".",
"Generators",
"::",
"random",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"headers",
"as",
"$",
"name... | Returns encoded message. | [
"Returns",
"encoded",
"message",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/MimePart.php#L239-L288 | train |
hail-framework/framework | src/Mail/MimePart.php | MimePart.encodeHeader | private static function encodeHeader(string $s, int &$offset = 0, bool $quotes = false): string
{
if (\strspn($s,
"!\"#$%&\'()*+,-./0123456789:;<>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`abcdefghijklmnopqrstuvwxyz{|}~=? _\r\n\t") === \strlen($s)) {
if ($quotes && \preg_match('#[^ a-zA-Z0-9!\#$%&\'*+/?^_`{|}~-]#', $s)) { // RFC 2822 atext except =
return self::append('"' . \addcslashes($s, '"\\') . '"', $offset);
}
return self::append($s, $offset);
}
$o = '';
if ($offset >= 55) { // maximum for iconv_mime_encode
$o = self::EOL . "\t";
$offset = 1;
}
$filed = \str_repeat(' ', $old = $offset);
if (\function_exists('\iconv_mime_encode')) {
$s = \iconv_mime_encode($filed, $s, [
'scheme' => 'B', // Q is broken
'input-charset' => 'UTF-8',
'output-charset' => 'UTF-8',
]);
} else {
$s = $filed . ': ' . \mb_encode_mimeheader($s, 'UTF-8', 'B');
}
$offset = \strlen($s) - \strrpos($s, "\n");
$s = \str_replace("\n ", "\n\t", \substr($s, $old + 2)); // adds ': '
return $o . $s;
} | php | private static function encodeHeader(string $s, int &$offset = 0, bool $quotes = false): string
{
if (\strspn($s,
"!\"#$%&\'()*+,-./0123456789:;<>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`abcdefghijklmnopqrstuvwxyz{|}~=? _\r\n\t") === \strlen($s)) {
if ($quotes && \preg_match('#[^ a-zA-Z0-9!\#$%&\'*+/?^_`{|}~-]#', $s)) { // RFC 2822 atext except =
return self::append('"' . \addcslashes($s, '"\\') . '"', $offset);
}
return self::append($s, $offset);
}
$o = '';
if ($offset >= 55) { // maximum for iconv_mime_encode
$o = self::EOL . "\t";
$offset = 1;
}
$filed = \str_repeat(' ', $old = $offset);
if (\function_exists('\iconv_mime_encode')) {
$s = \iconv_mime_encode($filed, $s, [
'scheme' => 'B', // Q is broken
'input-charset' => 'UTF-8',
'output-charset' => 'UTF-8',
]);
} else {
$s = $filed . ': ' . \mb_encode_mimeheader($s, 'UTF-8', 'B');
}
$offset = \strlen($s) - \strrpos($s, "\n");
$s = \str_replace("\n ", "\n\t", \substr($s, $old + 2)); // adds ': '
return $o . $s;
} | [
"private",
"static",
"function",
"encodeHeader",
"(",
"string",
"$",
"s",
",",
"int",
"&",
"$",
"offset",
"=",
"0",
",",
"bool",
"$",
"quotes",
"=",
"false",
")",
":",
"string",
"{",
"if",
"(",
"\\",
"strspn",
"(",
"$",
"s",
",",
"\"!\\\"#$%&\\'()*+,... | Converts a 8 bit header to a string. | [
"Converts",
"a",
"8",
"bit",
"header",
"to",
"a",
"string",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Mail/MimePart.php#L297-L329 | train |
hail-framework/framework | src/Debugger/Dumper.php | Dumper.dump | public static function dump($var, array $options = null)
{
if (Helpers::isHtmlMode()) {
echo self::toHtml($var, $options);
} elseif (self::detectColors()) {
echo self::toTerminal($var, $options);
} else {
echo self::toText($var, $options);
}
return $var;
} | php | public static function dump($var, array $options = null)
{
if (Helpers::isHtmlMode()) {
echo self::toHtml($var, $options);
} elseif (self::detectColors()) {
echo self::toTerminal($var, $options);
} else {
echo self::toText($var, $options);
}
return $var;
} | [
"public",
"static",
"function",
"dump",
"(",
"$",
"var",
",",
"array",
"$",
"options",
"=",
"null",
")",
"{",
"if",
"(",
"Helpers",
"::",
"isHtmlMode",
"(",
")",
")",
"{",
"echo",
"self",
"::",
"toHtml",
"(",
"$",
"var",
",",
"$",
"options",
")",
... | Dumps variable to the output.
@param mixed $var
@param array|null $options
@return mixed variable | [
"Dumps",
"variable",
"to",
"the",
"output",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Dumper.php#L79-L90 | train |
hail-framework/framework | src/Debugger/Dumper.php | Dumper.toHtml | public static function toHtml($var, array $options = null): string
{
$options += [
self::DEPTH => 4,
self::TRUNCATE => 150,
self::COLLAPSE => 14,
self::COLLAPSE_COUNT => 7,
self::OBJECT_EXPORTERS => null,
self::DEBUGINFO => false,
self::KEYS_TO_HIDE => [],
];
$loc = &$options[self::LOCATION];
$loc = $loc === true ? ~0 : (int) $loc;
$options[self::KEYS_TO_HIDE] = \array_flip(\array_map('\\strtolower', $options[self::KEYS_TO_HIDE]));
$options[self::OBJECT_EXPORTERS] = (array) $options[self::OBJECT_EXPORTERS] + self::$objectExporters;
\uksort($options[self::OBJECT_EXPORTERS], function ($a, $b): int {
return $b === '' || (\class_exists($a, false) && \is_subclass_of($a, $b)) ? -1 : 1;
});
$live = !empty($options[self::LIVE]) && $var && (\is_array($var) || \is_object($var) || \is_resource($var));
[$file, $line, $code] = $loc ? self::findLocation() : null;
$locAttrs = $file && $loc & self::LOCATION_SOURCE ? Helpers::formatHtml(
' title="%in file % on line %" data-tracy-href="%"', "$code\n", $file, $line,
Helpers::editorUri($file, $line)
) : null;
return '<pre class="tracy-dump' . ($live && $options[self::COLLAPSE] === true ? ' tracy-collapsed' : '') . '"'
. $locAttrs
. ($live ? " data-tracy-dump='" . \json_encode(self::toJson($var, $options),
JSON_HEX_APOS | JSON_HEX_AMP) . "'>" : '>')
. ($live ? '' : self::dumpVar($var, $options))
. ($file && $loc & self::LOCATION_LINK ? '<small>in ' . Helpers::editorLink($file, $line) . '</small>' : '')
. "</pre>\n";
} | php | public static function toHtml($var, array $options = null): string
{
$options += [
self::DEPTH => 4,
self::TRUNCATE => 150,
self::COLLAPSE => 14,
self::COLLAPSE_COUNT => 7,
self::OBJECT_EXPORTERS => null,
self::DEBUGINFO => false,
self::KEYS_TO_HIDE => [],
];
$loc = &$options[self::LOCATION];
$loc = $loc === true ? ~0 : (int) $loc;
$options[self::KEYS_TO_HIDE] = \array_flip(\array_map('\\strtolower', $options[self::KEYS_TO_HIDE]));
$options[self::OBJECT_EXPORTERS] = (array) $options[self::OBJECT_EXPORTERS] + self::$objectExporters;
\uksort($options[self::OBJECT_EXPORTERS], function ($a, $b): int {
return $b === '' || (\class_exists($a, false) && \is_subclass_of($a, $b)) ? -1 : 1;
});
$live = !empty($options[self::LIVE]) && $var && (\is_array($var) || \is_object($var) || \is_resource($var));
[$file, $line, $code] = $loc ? self::findLocation() : null;
$locAttrs = $file && $loc & self::LOCATION_SOURCE ? Helpers::formatHtml(
' title="%in file % on line %" data-tracy-href="%"', "$code\n", $file, $line,
Helpers::editorUri($file, $line)
) : null;
return '<pre class="tracy-dump' . ($live && $options[self::COLLAPSE] === true ? ' tracy-collapsed' : '') . '"'
. $locAttrs
. ($live ? " data-tracy-dump='" . \json_encode(self::toJson($var, $options),
JSON_HEX_APOS | JSON_HEX_AMP) . "'>" : '>')
. ($live ? '' : self::dumpVar($var, $options))
. ($file && $loc & self::LOCATION_LINK ? '<small>in ' . Helpers::editorLink($file, $line) . '</small>' : '')
. "</pre>\n";
} | [
"public",
"static",
"function",
"toHtml",
"(",
"$",
"var",
",",
"array",
"$",
"options",
"=",
"null",
")",
":",
"string",
"{",
"$",
"options",
"+=",
"[",
"self",
"::",
"DEPTH",
"=>",
"4",
",",
"self",
"::",
"TRUNCATE",
"=>",
"150",
",",
"self",
"::... | Dumps variable to HTML.
@return string | [
"Dumps",
"variable",
"to",
"HTML",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Dumper.php#L98-L132 | train |
hail-framework/framework | src/Debugger/Dumper.php | Dumper.toText | public static function toText($var, array $options = null): string
{
return \htmlspecialchars_decode(\strip_tags(self::toHtml($var, $options)), ENT_QUOTES);
} | php | public static function toText($var, array $options = null): string
{
return \htmlspecialchars_decode(\strip_tags(self::toHtml($var, $options)), ENT_QUOTES);
} | [
"public",
"static",
"function",
"toText",
"(",
"$",
"var",
",",
"array",
"$",
"options",
"=",
"null",
")",
":",
"string",
"{",
"return",
"\\",
"htmlspecialchars_decode",
"(",
"\\",
"strip_tags",
"(",
"self",
"::",
"toHtml",
"(",
"$",
"var",
",",
"$",
"... | Dumps variable to plain text.
@return string | [
"Dumps",
"variable",
"to",
"plain",
"text",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Dumper.php#L140-L143 | train |
hail-framework/framework | src/Debugger/Dumper.php | Dumper.toTerminal | public static function toTerminal($var, array $options = null): string
{
return \htmlspecialchars_decode(\strip_tags(\preg_replace_callback('#<span class="tracy-dump-(\w+)">|</span>#',
function ($m) {
return "\033[" . (isset($m[1], self::$terminalColors[$m[1]]) ? self::$terminalColors[$m[1]] : '0') . 'm';
}, self::toHtml($var, $options))), ENT_QUOTES);
} | php | public static function toTerminal($var, array $options = null): string
{
return \htmlspecialchars_decode(\strip_tags(\preg_replace_callback('#<span class="tracy-dump-(\w+)">|</span>#',
function ($m) {
return "\033[" . (isset($m[1], self::$terminalColors[$m[1]]) ? self::$terminalColors[$m[1]] : '0') . 'm';
}, self::toHtml($var, $options))), ENT_QUOTES);
} | [
"public",
"static",
"function",
"toTerminal",
"(",
"$",
"var",
",",
"array",
"$",
"options",
"=",
"null",
")",
":",
"string",
"{",
"return",
"\\",
"htmlspecialchars_decode",
"(",
"\\",
"strip_tags",
"(",
"\\",
"preg_replace_callback",
"(",
"'#<span class=\"tracy... | Dumps variable to x-terminal.
@return string | [
"Dumps",
"variable",
"to",
"x",
"-",
"terminal",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Dumper.php#L151-L157 | train |
hail-framework/framework | src/Debugger/Dumper.php | Dumper.findLocation | private static function findLocation(): ?array
{
foreach (\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $item) {
if (isset($item['class']) && $item['class'] === __CLASS__) {
$location = $item;
continue;
}
if (isset($item['function'])) {
try {
$reflection = isset($item['class'])
? new \ReflectionMethod($item['class'], $item['function'])
: new \ReflectionFunction($item['function']);
if ($reflection->isInternal() || \preg_match('#\s@tracySkipLocation\s#',
(string) $reflection->getDocComment())) {
$location = $item;
continue;
}
} catch (\ReflectionException $e) {
}
}
break;
}
if (isset($location['file'], $location['line']) && \is_file($location['file'])) {
$lines = \file($location['file']);
$line = $lines[$location['line'] - 1];
return [
$location['file'],
$location['line'],
\trim(\preg_match('#\w*dump(er::\w+)?\(.*\)#i', $line, $m) ? $m[0] : $line),
];
}
return null;
} | php | private static function findLocation(): ?array
{
foreach (\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $item) {
if (isset($item['class']) && $item['class'] === __CLASS__) {
$location = $item;
continue;
}
if (isset($item['function'])) {
try {
$reflection = isset($item['class'])
? new \ReflectionMethod($item['class'], $item['function'])
: new \ReflectionFunction($item['function']);
if ($reflection->isInternal() || \preg_match('#\s@tracySkipLocation\s#',
(string) $reflection->getDocComment())) {
$location = $item;
continue;
}
} catch (\ReflectionException $e) {
}
}
break;
}
if (isset($location['file'], $location['line']) && \is_file($location['file'])) {
$lines = \file($location['file']);
$line = $lines[$location['line'] - 1];
return [
$location['file'],
$location['line'],
\trim(\preg_match('#\w*dump(er::\w+)?\(.*\)#i', $line, $m) ? $m[0] : $line),
];
}
return null;
} | [
"private",
"static",
"function",
"findLocation",
"(",
")",
":",
"?",
"array",
"{",
"foreach",
"(",
"\\",
"debug_backtrace",
"(",
"DEBUG_BACKTRACE_IGNORE_ARGS",
")",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"item",
"[",
"'class'",
"]",
"... | Finds the location where dump was called.
@return array|null [file, line, code] | [
"Finds",
"the",
"location",
"where",
"dump",
"was",
"called",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Dumper.php#L573-L609 | train |
hail-framework/framework | src/Console/Option/Option.php | Option.renderReadableSpec | public function renderReadableSpec($renderHint = true)
{
$c1 = '';
if ($this->short) {
$c1 = '-' . $this->short;
}
if ($this->long) {
if ($c1 !== '') {
$c1 .= ', ';
}
$c1 .= '--' . $this->long;
}
if ($renderHint) {
return $c1 . $this->renderValueHint();
}
return $c1;
} | php | public function renderReadableSpec($renderHint = true)
{
$c1 = '';
if ($this->short) {
$c1 = '-' . $this->short;
}
if ($this->long) {
if ($c1 !== '') {
$c1 .= ', ';
}
$c1 .= '--' . $this->long;
}
if ($renderHint) {
return $c1 . $this->renderValueHint();
}
return $c1;
} | [
"public",
"function",
"renderReadableSpec",
"(",
"$",
"renderHint",
"=",
"true",
")",
"{",
"$",
"c1",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"short",
")",
"{",
"$",
"c1",
"=",
"'-'",
".",
"$",
"this",
"->",
"short",
";",
"}",
"if",
"(",
... | get readable spec for printing.
@param bool $renderHint render also value hint
@return string | [
"get",
"readable",
"spec",
"for",
"printing",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Option/Option.php#L409-L429 | train |
hail-framework/framework | src/Filesystem/Adapter/Fallback.php | Fallback.portFromFallback | private function portFromFallback($path, $newpath)
{
$buffer = $this->fallback->readStream($path);
if (false === $buffer) {
return false;
}
$result = $this->mainAdapter->writeStream($newpath, $buffer['stream'], []);
if (\is_resource($buffer['stream'])) {
\fclose($buffer['stream']);
}
return (false !== $result);
} | php | private function portFromFallback($path, $newpath)
{
$buffer = $this->fallback->readStream($path);
if (false === $buffer) {
return false;
}
$result = $this->mainAdapter->writeStream($newpath, $buffer['stream'], []);
if (\is_resource($buffer['stream'])) {
\fclose($buffer['stream']);
}
return (false !== $result);
} | [
"private",
"function",
"portFromFallback",
"(",
"$",
"path",
",",
"$",
"newpath",
")",
"{",
"$",
"buffer",
"=",
"$",
"this",
"->",
"fallback",
"->",
"readStream",
"(",
"$",
"path",
")",
";",
"if",
"(",
"false",
"===",
"$",
"buffer",
")",
"{",
"return... | Copies a resource accessible through the fallback adapter to the filesystem abstracted with the main adapter.
@param $path
@return bool | [
"Copies",
"a",
"resource",
"accessible",
"through",
"the",
"fallback",
"adapter",
"to",
"the",
"filesystem",
"abstracted",
"with",
"the",
"main",
"adapter",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Fallback.php#L351-L366 | train |
hail-framework/framework | src/Http/Response.php | Response.template | public function template($name, array $params = []): ResponseInterface
{
if (\is_array($name)) {
$params = $name;
$name = null;
}
if ($name === null) {
$handler = $this->app->handler();
if ($handler instanceof \Closure) {
throw new \LogicException('Con not build the template from closure handler!');
}
$name = \ltrim($handler['app'] . '/' . $handler['controller'] . '/' . $handler['action'], '/');
} elseif (!\is_string($name)) {
throw new \InvalidArgumentException('Template name not found!');
}
$response = $this->response();
return $this->app->render($response, $name, $params);
} | php | public function template($name, array $params = []): ResponseInterface
{
if (\is_array($name)) {
$params = $name;
$name = null;
}
if ($name === null) {
$handler = $this->app->handler();
if ($handler instanceof \Closure) {
throw new \LogicException('Con not build the template from closure handler!');
}
$name = \ltrim($handler['app'] . '/' . $handler['controller'] . '/' . $handler['action'], '/');
} elseif (!\is_string($name)) {
throw new \InvalidArgumentException('Template name not found!');
}
$response = $this->response();
return $this->app->render($response, $name, $params);
} | [
"public",
"function",
"template",
"(",
"$",
"name",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
":",
"ResponseInterface",
"{",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"$",
"params",
"=",
"$",
"name",
";",
"$",
"name",
"... | Get or set template name
@param string|array|null $name
@param array $params
@return ResponseInterface
@throws \InvalidArgumentException
@throws \LogicException | [
"Get",
"or",
"set",
"template",
"name"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Response.php#L264-L285 | train |
hail-framework/framework | src/Http/Response.php | Response.setDate | public function setDate(\DateTime $date): self
{
$date->setTimezone(new \DateTimeZone('UTC'));
$this->header->set('Date', $date->format('D, d M Y H:i:s') . ' GMT');
return $this;
} | php | public function setDate(\DateTime $date): self
{
$date->setTimezone(new \DateTimeZone('UTC'));
$this->header->set('Date', $date->format('D, d M Y H:i:s') . ' GMT');
return $this;
} | [
"public",
"function",
"setDate",
"(",
"\\",
"DateTime",
"$",
"date",
")",
":",
"self",
"{",
"$",
"date",
"->",
"setTimezone",
"(",
"new",
"\\",
"DateTimeZone",
"(",
"'UTC'",
")",
")",
";",
"$",
"this",
"->",
"header",
"->",
"set",
"(",
"'Date'",
",",... | Sets the Date header.
@param \DateTime $date A \DateTime instance
@return $this | [
"Sets",
"the",
"Date",
"header",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Response.php#L686-L692 | train |
hail-framework/framework | src/Http/Response.php | Response.setTtl | public function setTtl(int $seconds): self
{
$this->setSharedMaxAge($this->getAge() + $seconds);
return $this;
} | php | public function setTtl(int $seconds): self
{
$this->setSharedMaxAge($this->getAge() + $seconds);
return $this;
} | [
"public",
"function",
"setTtl",
"(",
"int",
"$",
"seconds",
")",
":",
"self",
"{",
"$",
"this",
"->",
"setSharedMaxAge",
"(",
"$",
"this",
"->",
"getAge",
"(",
")",
"+",
"$",
"seconds",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the response's time-to-live for shared caches.
This method adjusts the Cache-Control/s-maxage directive.
@param int $seconds Number of seconds
@return $this | [
"Sets",
"the",
"response",
"s",
"time",
"-",
"to",
"-",
"live",
"for",
"shared",
"caches",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Response.php#L911-L916 | train |
hail-framework/framework | src/Console/Option/OptionCollection.php | OptionCollection.addOption | public function addOption(Option $spec)
{
$this->data[$spec->getId()] = $spec;
if ($spec->long) {
if (isset($this->longOptions[$spec->long])) {
throw new OptionConflictException('Option conflict: --' . $spec->long . ' is already defined.');
}
$this->longOptions[$spec->long] = $spec;
}
if ($spec->short) {
if (isset($this->shortOptions[$spec->short])) {
throw new OptionConflictException('Option conflict: -' . $spec->short . ' is already defined.');
}
$this->shortOptions[$spec->short] = $spec;
}
$this->options[] = $spec;
if (!$spec->long && !$spec->short) {
throw new InvalidArgumentException('Neither long option name nor short name is not given.');
}
} | php | public function addOption(Option $spec)
{
$this->data[$spec->getId()] = $spec;
if ($spec->long) {
if (isset($this->longOptions[$spec->long])) {
throw new OptionConflictException('Option conflict: --' . $spec->long . ' is already defined.');
}
$this->longOptions[$spec->long] = $spec;
}
if ($spec->short) {
if (isset($this->shortOptions[$spec->short])) {
throw new OptionConflictException('Option conflict: -' . $spec->short . ' is already defined.');
}
$this->shortOptions[$spec->short] = $spec;
}
$this->options[] = $spec;
if (!$spec->long && !$spec->short) {
throw new InvalidArgumentException('Neither long option name nor short name is not given.');
}
} | [
"public",
"function",
"addOption",
"(",
"Option",
"$",
"spec",
")",
"{",
"$",
"this",
"->",
"data",
"[",
"$",
"spec",
"->",
"getId",
"(",
")",
"]",
"=",
"$",
"spec",
";",
"if",
"(",
"$",
"spec",
"->",
"long",
")",
"{",
"if",
"(",
"isset",
"(",
... | Add option object.
@param Option $spec the option object.
@throws InvalidArgumentException
@throws OptionConflictException | [
"Add",
"option",
"object",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Option/OptionCollection.php#L118-L137 | train |
mcrumm/pecan | src/Console.php | Console.format | public function format($message)
{
if (!$this->output) {
throw new \LogicException('A ConsoleOutputInterface must be set before calling format().');
}
return $this->output->getFormatter()->format($message);
} | php | public function format($message)
{
if (!$this->output) {
throw new \LogicException('A ConsoleOutputInterface must be set before calling format().');
}
return $this->output->getFormatter()->format($message);
} | [
"public",
"function",
"format",
"(",
"$",
"message",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"output",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'A ConsoleOutputInterface must be set before calling format().'",
")",
";",
"}",
"return",
"$",
... | Formats a message.
@param $message
@return string
@throws \LogicException When called before Output is set. | [
"Formats",
"a",
"message",
"."
] | f35f01249587a4df45c7d3ab78f3e51919471177 | https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Console.php#L53-L60 | train |
DoSomething/gateway | src/Laravel/LaravelNorthstar.php | LaravelNorthstar.send | public function send($method, $path, $options = [], $withAuthorization = true)
{
try {
return parent::send($method, $path, $options, $withAuthorization);
} catch (ValidationException $e) {
throw LaravelValidationException::withMessages($e->getErrors());
} catch (UnauthorizedException $e) {
throw new \Illuminate\Auth\AuthenticationException;
} catch (ForbiddenException $e) {
throw new \Illuminate\Auth\AuthenticationException;
} catch (InternalException $e) {
$message = 'Northstar returned an unexpected error for that request.';
if (config('app.debug')) {
$message = $e->getMessage();
}
throw new HttpException(500, $message);
}
} | php | public function send($method, $path, $options = [], $withAuthorization = true)
{
try {
return parent::send($method, $path, $options, $withAuthorization);
} catch (ValidationException $e) {
throw LaravelValidationException::withMessages($e->getErrors());
} catch (UnauthorizedException $e) {
throw new \Illuminate\Auth\AuthenticationException;
} catch (ForbiddenException $e) {
throw new \Illuminate\Auth\AuthenticationException;
} catch (InternalException $e) {
$message = 'Northstar returned an unexpected error for that request.';
if (config('app.debug')) {
$message = $e->getMessage();
}
throw new HttpException(500, $message);
}
} | [
"public",
"function",
"send",
"(",
"$",
"method",
",",
"$",
"path",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"withAuthorization",
"=",
"true",
")",
"{",
"try",
"{",
"return",
"parent",
"::",
"send",
"(",
"$",
"method",
",",
"$",
"path",
",",
... | Send a Northstar API request, and translates any Northstar exceptions
into their built-in Laravel equivalents.
@param string $method
@param string $path
@param array $options
@param bool $withAuthorization
@return \GuzzleHttp\Psr7\Response|void | [
"Send",
"a",
"Northstar",
"API",
"request",
"and",
"translates",
"any",
"Northstar",
"exceptions",
"into",
"their",
"built",
"-",
"in",
"Laravel",
"equivalents",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Laravel/LaravelNorthstar.php#L41-L60 | train |
htmlburger/wpemerge-cli | src/Composer/Composer.php | Composer.getComposerJson | public static function getComposerJson( $directory ) {
$composer_json = $directory . DIRECTORY_SEPARATOR . 'composer.json';
if ( ! file_exists( $composer_json ) ) {
return null;
}
$composer = @json_decode( file_get_contents( $composer_json ), true );
if ( ! $composer ) {
return null;
}
return $composer;
} | php | public static function getComposerJson( $directory ) {
$composer_json = $directory . DIRECTORY_SEPARATOR . 'composer.json';
if ( ! file_exists( $composer_json ) ) {
return null;
}
$composer = @json_decode( file_get_contents( $composer_json ), true );
if ( ! $composer ) {
return null;
}
return $composer;
} | [
"public",
"static",
"function",
"getComposerJson",
"(",
"$",
"directory",
")",
"{",
"$",
"composer_json",
"=",
"$",
"directory",
".",
"DIRECTORY_SEPARATOR",
".",
"'composer.json'",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"composer_json",
")",
")",
"{",
... | Load and parse a composer.json file from a directory
@param string $directory
@return array|null | [
"Load",
"and",
"parse",
"a",
"composer",
".",
"json",
"file",
"from",
"a",
"directory"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Composer/Composer.php#L15-L29 | train |
htmlburger/wpemerge-cli | src/Composer/Composer.php | Composer.storeComposerJson | public static function storeComposerJson( $composer, $directory ) {
$composer_json = $directory . DIRECTORY_SEPARATOR . 'composer.json';
file_put_contents( $composer_json, json_encode( $composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) );
} | php | public static function storeComposerJson( $composer, $directory ) {
$composer_json = $directory . DIRECTORY_SEPARATOR . 'composer.json';
file_put_contents( $composer_json, json_encode( $composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) );
} | [
"public",
"static",
"function",
"storeComposerJson",
"(",
"$",
"composer",
",",
"$",
"directory",
")",
"{",
"$",
"composer_json",
"=",
"$",
"directory",
".",
"DIRECTORY_SEPARATOR",
".",
"'composer.json'",
";",
"file_put_contents",
"(",
"$",
"composer_json",
",",
... | Store a parsed composer.json file in a directory
@param array $composer
@param string $directory
@return void | [
"Store",
"a",
"parsed",
"composer",
".",
"json",
"file",
"in",
"a",
"directory"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Composer/Composer.php#L38-L42 | train |
htmlburger/wpemerge-cli | src/Composer/Composer.php | Composer.installed | public static function installed( $directory, $package ) {
$command = 'composer show ' . $package . ' -D';
try {
App::execute( $command, $directory );
} catch ( ProcessFailedException $e ) {
return false;
}
return true;
} | php | public static function installed( $directory, $package ) {
$command = 'composer show ' . $package . ' -D';
try {
App::execute( $command, $directory );
} catch ( ProcessFailedException $e ) {
return false;
}
return true;
} | [
"public",
"static",
"function",
"installed",
"(",
"$",
"directory",
",",
"$",
"package",
")",
"{",
"$",
"command",
"=",
"'composer show '",
".",
"$",
"package",
".",
"' -D'",
";",
"try",
"{",
"App",
"::",
"execute",
"(",
"$",
"command",
",",
"$",
"dire... | Check if a package is already installed
@param string $directory
@param string $package
@return boolean | [
"Check",
"if",
"a",
"package",
"is",
"already",
"installed"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Composer/Composer.php#L51-L61 | train |
hail-framework/framework | src/AliasLoader.php | AliasLoader.ensureFacadeExists | protected function ensureFacadeExists(string $alias): string
{
if (\file_exists($path = \runtime_path('facade', $alias . '.php'))) {
return $path;
}
if (!\is_dir($dir = \dirname($path)) && !@\mkdir($dir) && !\is_dir($dir)) {
throw new \RuntimeException('Temp directory permission denied');
}
\file_put_contents($path, $this->formatFacadeCode($alias));
if (\function_exists('\opcache_invalidate')) {
\opcache_invalidate($path, true);
}
return $path;
} | php | protected function ensureFacadeExists(string $alias): string
{
if (\file_exists($path = \runtime_path('facade', $alias . '.php'))) {
return $path;
}
if (!\is_dir($dir = \dirname($path)) && !@\mkdir($dir) && !\is_dir($dir)) {
throw new \RuntimeException('Temp directory permission denied');
}
\file_put_contents($path, $this->formatFacadeCode($alias));
if (\function_exists('\opcache_invalidate')) {
\opcache_invalidate($path, true);
}
return $path;
} | [
"protected",
"function",
"ensureFacadeExists",
"(",
"string",
"$",
"alias",
")",
":",
"string",
"{",
"if",
"(",
"\\",
"file_exists",
"(",
"$",
"path",
"=",
"\\",
"runtime_path",
"(",
"'facade'",
",",
"$",
"alias",
".",
"'.php'",
")",
")",
")",
"{",
"re... | Ensure that the given alias has an existing real-time facade class.
@param string $alias
@return string
@throws \RuntimeException | [
"Ensure",
"that",
"the",
"given",
"alias",
"has",
"an",
"existing",
"real",
"-",
"time",
"facade",
"class",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/AliasLoader.php#L89-L106 | train |
hail-framework/framework | src/AliasLoader.php | AliasLoader.register | public function register(): void
{
if (!$this->registered) {
\spl_autoload_register([$this, 'load'], true, true);
$this->registered = true;
}
} | php | public function register(): void
{
if (!$this->registered) {
\spl_autoload_register([$this, 'load'], true, true);
$this->registered = true;
}
} | [
"public",
"function",
"register",
"(",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"registered",
")",
"{",
"\\",
"spl_autoload_register",
"(",
"[",
"$",
"this",
",",
"'load'",
"]",
",",
"true",
",",
"true",
")",
";",
"$",
"this",
"->"... | Prepend the loader to the auto-loader stack.
@return void | [
"Prepend",
"the",
"loader",
"to",
"the",
"auto",
"-",
"loader",
"stack",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/AliasLoader.php#L198-L204 | train |
Kajna/K-Core | Core/Session/Session.php | Session.validate | protected function validate()
{
// Are needed session variables set ?
if (!isset($_SESSION['s3ss10nCr3at3d']) || !isset($_SESSION['n3k0t'])) {
return false;
}
// Check if session token match ?
if ($this->matchUserAgent) {
if ($_SESSION['n3k0t'] !== hash_hmac($this->hashAlgo, $_SERVER['HTTP_USER_AGENT'] . $_SESSION['s3ss10nCr3at3d'], $this->hashKey)) {
return false;
}
} elseif ($_SESSION['n3k0t'] !== hash_hmac($this->hashAlgo, $_SESSION['s3ss10nCr3at3d'], $this->hashKey)) {
return false;
}
// Is session expired ?
if ((time() > ($_SESSION['s3ss10nCr3at3d']) + $this->expiration)) {
return false;
}
// Everything is fine return true
return true;
} | php | protected function validate()
{
// Are needed session variables set ?
if (!isset($_SESSION['s3ss10nCr3at3d']) || !isset($_SESSION['n3k0t'])) {
return false;
}
// Check if session token match ?
if ($this->matchUserAgent) {
if ($_SESSION['n3k0t'] !== hash_hmac($this->hashAlgo, $_SERVER['HTTP_USER_AGENT'] . $_SESSION['s3ss10nCr3at3d'], $this->hashKey)) {
return false;
}
} elseif ($_SESSION['n3k0t'] !== hash_hmac($this->hashAlgo, $_SESSION['s3ss10nCr3at3d'], $this->hashKey)) {
return false;
}
// Is session expired ?
if ((time() > ($_SESSION['s3ss10nCr3at3d']) + $this->expiration)) {
return false;
}
// Everything is fine return true
return true;
} | [
"protected",
"function",
"validate",
"(",
")",
"{",
"// Are needed session variables set ?",
"if",
"(",
"!",
"isset",
"(",
"$",
"_SESSION",
"[",
"'s3ss10nCr3at3d'",
"]",
")",
"||",
"!",
"isset",
"(",
"$",
"_SESSION",
"[",
"'n3k0t'",
"]",
")",
")",
"{",
"re... | Validate session.
@return bool | [
"Validate",
"session",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Session/Session.php#L136-L159 | train |
Kajna/K-Core | Core/Session/Session.php | Session.regenerate | public function regenerate()
{
// If headers already sent can't do much
if (headers_sent()) {
return;
}
// Clear old session data
$_SESSION = [];
// Set session start time
$_SESSION['s3ss10nCr3at3d'] = time();
// Set new session token
if ($this->matchUserAgent) {
$_SESSION['n3k0t'] = hash_hmac($this->hashAlgo, $_SERVER['HTTP_USER_AGENT'] . $_SESSION['s3ss10nCr3at3d'], $this->hashKey);
} else {
$_SESSION['n3k0t'] = hash_hmac($this->hashAlgo, $_SESSION['s3ss10nCr3at3d'], $this->hashKey);
}
// Regenerate session
session_regenerate_id();
} | php | public function regenerate()
{
// If headers already sent can't do much
if (headers_sent()) {
return;
}
// Clear old session data
$_SESSION = [];
// Set session start time
$_SESSION['s3ss10nCr3at3d'] = time();
// Set new session token
if ($this->matchUserAgent) {
$_SESSION['n3k0t'] = hash_hmac($this->hashAlgo, $_SERVER['HTTP_USER_AGENT'] . $_SESSION['s3ss10nCr3at3d'], $this->hashKey);
} else {
$_SESSION['n3k0t'] = hash_hmac($this->hashAlgo, $_SESSION['s3ss10nCr3at3d'], $this->hashKey);
}
// Regenerate session
session_regenerate_id();
} | [
"public",
"function",
"regenerate",
"(",
")",
"{",
"// If headers already sent can't do much",
"if",
"(",
"headers_sent",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Clear old session data",
"$",
"_SESSION",
"=",
"[",
"]",
";",
"// Set session start time",
"$",
"_... | Completely regenerate session. | [
"Completely",
"regenerate",
"session",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Session/Session.php#L164-L183 | train |
spiral/debug | src/Traits/BenchmarkTrait.php | BenchmarkTrait.benchmark | private function benchmark(string $event, $context = null): Benchmark
{
$container = ContainerScope::getContainer();
if (empty($container) || !$container->has(BenchmarkerInterface::class)) {
return new Benchmark(
get_class($this),
$event,
$context
);
}
return $container->get(BenchmarkerInterface::class)->record(
get_class($this),
$event,
$context
);
} | php | private function benchmark(string $event, $context = null): Benchmark
{
$container = ContainerScope::getContainer();
if (empty($container) || !$container->has(BenchmarkerInterface::class)) {
return new Benchmark(
get_class($this),
$event,
$context
);
}
return $container->get(BenchmarkerInterface::class)->record(
get_class($this),
$event,
$context
);
} | [
"private",
"function",
"benchmark",
"(",
"string",
"$",
"event",
",",
"$",
"context",
"=",
"null",
")",
":",
"Benchmark",
"{",
"$",
"container",
"=",
"ContainerScope",
"::",
"getContainer",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"container",
")",
... | Creates new benchmark record associated with current object.
@param string $event Event name or set of names.
@param string $context Record context (if any).
@return Benchmark
@throws \Psr\Container\ContainerExceptionInterface | [
"Creates",
"new",
"benchmark",
"record",
"associated",
"with",
"current",
"object",
"."
] | d477c7f2e50be8cb934cf3a5f327d6dc3eee2f9f | https://github.com/spiral/debug/blob/d477c7f2e50be8cb934cf3a5f327d6dc3eee2f9f/src/Traits/BenchmarkTrait.php#L31-L47 | train |
hail-framework/framework | src/Database/Migration/Adapter/PdoAdapter.php | PdoAdapter.setConnection | public function setConnection(\PDO $connection)
{
$this->connection = $connection;
// Create the schema table if it doesn't already exist
if (!$this->hasSchemaTable()) {
$this->createSchemaTable();
} else {
$table = new Table($this->getSchemaTableName(), [], $this);
if (!$table->hasColumn('migration_name')) {
$table
->addColumn('migration_name', 'string',
['limit' => 100, 'after' => 'version', 'default' => null, 'null' => true]
)
->save();
}
if (!$table->hasColumn('breakpoint')) {
$table
->addColumn('breakpoint', 'boolean', ['default' => false])
->save();
}
}
return $this;
} | php | public function setConnection(\PDO $connection)
{
$this->connection = $connection;
// Create the schema table if it doesn't already exist
if (!$this->hasSchemaTable()) {
$this->createSchemaTable();
} else {
$table = new Table($this->getSchemaTableName(), [], $this);
if (!$table->hasColumn('migration_name')) {
$table
->addColumn('migration_name', 'string',
['limit' => 100, 'after' => 'version', 'default' => null, 'null' => true]
)
->save();
}
if (!$table->hasColumn('breakpoint')) {
$table
->addColumn('breakpoint', 'boolean', ['default' => false])
->save();
}
}
return $this;
} | [
"public",
"function",
"setConnection",
"(",
"\\",
"PDO",
"$",
"connection",
")",
"{",
"$",
"this",
"->",
"connection",
"=",
"$",
"connection",
";",
"// Create the schema table if it doesn't already exist",
"if",
"(",
"!",
"$",
"this",
"->",
"hasSchemaTable",
"(",
... | Sets the database connection.
@param \PDO $connection Connection
@return AdapterInterface | [
"Sets",
"the",
"database",
"connection",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/PdoAdapter.php#L70-L94 | train |
hail-framework/framework | src/Database/Migration/Adapter/ProxyAdapter.php | ProxyAdapter.executeCommands | public function executeCommands()
{
$commands = $this->getCommands();
foreach ($commands as $command) {
call_user_func_array([$this->getAdapter(), $command['name']], $command['arguments']);
}
} | php | public function executeCommands()
{
$commands = $this->getCommands();
foreach ($commands as $command) {
call_user_func_array([$this->getAdapter(), $command['name']], $command['arguments']);
}
} | [
"public",
"function",
"executeCommands",
"(",
")",
"{",
"$",
"commands",
"=",
"$",
"this",
"->",
"getCommands",
"(",
")",
";",
"foreach",
"(",
"$",
"commands",
"as",
"$",
"command",
")",
"{",
"call_user_func_array",
"(",
"[",
"$",
"this",
"->",
"getAdapt... | Execute the recorded commands.
@return void | [
"Execute",
"the",
"recorded",
"commands",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/ProxyAdapter.php#L253-L259 | train |
hail-framework/framework | src/Database/Migration/Adapter/ProxyAdapter.php | ProxyAdapter.executeInvertedCommands | public function executeInvertedCommands()
{
$commands = $this->getInvertedCommands();
foreach ($commands as $command) {
call_user_func_array([$this->getAdapter(), $command['name']], $command['arguments']);
}
} | php | public function executeInvertedCommands()
{
$commands = $this->getInvertedCommands();
foreach ($commands as $command) {
call_user_func_array([$this->getAdapter(), $command['name']], $command['arguments']);
}
} | [
"public",
"function",
"executeInvertedCommands",
"(",
")",
"{",
"$",
"commands",
"=",
"$",
"this",
"->",
"getInvertedCommands",
"(",
")",
";",
"foreach",
"(",
"$",
"commands",
"as",
"$",
"command",
")",
"{",
"call_user_func_array",
"(",
"[",
"$",
"this",
"... | Execute the recorded commands in reverse.
@return void | [
"Execute",
"the",
"recorded",
"commands",
"in",
"reverse",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/ProxyAdapter.php#L266-L272 | train |
hail-framework/framework | src/Http/Middleware/Cors.php | Cors.withCorsHeaders | private static function withCorsHeaders(ResponseInterface $response, array $headers): ResponseInterface
{
foreach ($headers as $name => $value) {
$response = $response->withHeader($name, $value);
}
return $response;
} | php | private static function withCorsHeaders(ResponseInterface $response, array $headers): ResponseInterface
{
foreach ($headers as $name => $value) {
$response = $response->withHeader($name, $value);
}
return $response;
} | [
"private",
"static",
"function",
"withCorsHeaders",
"(",
"ResponseInterface",
"$",
"response",
",",
"array",
"$",
"headers",
")",
":",
"ResponseInterface",
"{",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"response",... | Adds cors headers to the response.
@param ResponseInterface $response
@param array $headers
@return ResponseInterface | [
"Adds",
"cors",
"headers",
"to",
"the",
"response",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Middleware/Cors.php#L172-L179 | train |
hail-framework/framework | src/Http/Middleware/Cors.php | Cors.analyze | public function analyze(RequestInterface $request): array
{
$serverOrigin = Factory::uri($this->settings[self::KEY_SERVER_ORIGIN]);
// check 'Host' request
if ($this->settings[self::KEY_IS_CHECK_HOST] && !$this->isSameHost($request, $serverOrigin)) {
return $this->result(self::ERROR_NO_HOST_HEADER);
}
// Request handlers have common part (#6.1.1 - #6.1.2 and #6.2.1 - #6.2.2)
// #6.1.1 and #6.2.1
$requestOrigin = $this->getRequestOrigin($request);
if ($requestOrigin === null || $requestOrigin === $this->getOriginFromUri($serverOrigin)) {
return $this->result(self::TYPE_REQUEST_OUT_OF_CORS_SCOPE);
}
// #6.1.2 and #6.2.2
if (
!isset($this->settings[self::KEY_ALLOWED_ORIGINS][self::VALUE_ALLOW_ORIGIN_ALL]) &&
!isset($this->settings[self::KEY_ALLOWED_ORIGINS][$requestOrigin])
) {
return $this->result(self::ERROR_ORIGIN_NOT_ALLOWED);
}
// Since this point handlers have their own path for
// - simple CORS and actual CORS request (#6.1.3 - #6.1.4)
// - pre-flight request (#6.2.3 - #6.2.10)
if ($request->getMethod() === 'OPTIONS') {
return $this->analyzeAsPreFlight($request, $requestOrigin);
}
return $this->analyzeAsRequest($requestOrigin);
} | php | public function analyze(RequestInterface $request): array
{
$serverOrigin = Factory::uri($this->settings[self::KEY_SERVER_ORIGIN]);
// check 'Host' request
if ($this->settings[self::KEY_IS_CHECK_HOST] && !$this->isSameHost($request, $serverOrigin)) {
return $this->result(self::ERROR_NO_HOST_HEADER);
}
// Request handlers have common part (#6.1.1 - #6.1.2 and #6.2.1 - #6.2.2)
// #6.1.1 and #6.2.1
$requestOrigin = $this->getRequestOrigin($request);
if ($requestOrigin === null || $requestOrigin === $this->getOriginFromUri($serverOrigin)) {
return $this->result(self::TYPE_REQUEST_OUT_OF_CORS_SCOPE);
}
// #6.1.2 and #6.2.2
if (
!isset($this->settings[self::KEY_ALLOWED_ORIGINS][self::VALUE_ALLOW_ORIGIN_ALL]) &&
!isset($this->settings[self::KEY_ALLOWED_ORIGINS][$requestOrigin])
) {
return $this->result(self::ERROR_ORIGIN_NOT_ALLOWED);
}
// Since this point handlers have their own path for
// - simple CORS and actual CORS request (#6.1.3 - #6.1.4)
// - pre-flight request (#6.2.3 - #6.2.10)
if ($request->getMethod() === 'OPTIONS') {
return $this->analyzeAsPreFlight($request, $requestOrigin);
}
return $this->analyzeAsRequest($requestOrigin);
} | [
"public",
"function",
"analyze",
"(",
"RequestInterface",
"$",
"request",
")",
":",
"array",
"{",
"$",
"serverOrigin",
"=",
"Factory",
"::",
"uri",
"(",
"$",
"this",
"->",
"settings",
"[",
"self",
"::",
"KEY_SERVER_ORIGIN",
"]",
")",
";",
"// check 'Host' re... | Set request for analysis.
@param RequestInterface $request
@return array
@see http://www.w3.org/TR/cors/#resource-processing-model | [
"Set",
"request",
"for",
"analysis",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Middleware/Cors.php#L189-L223 | train |
hail-framework/framework | src/Image/Image.php | Image.setBackup | public function setBackup($resource, $name = null)
{
$name = $name ?? 'default';
$this->backups[$name] = $resource;
return $this;
} | php | public function setBackup($resource, $name = null)
{
$name = $name ?? 'default';
$this->backups[$name] = $resource;
return $this;
} | [
"public",
"function",
"setBackup",
"(",
"$",
"resource",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"name",
"=",
"$",
"name",
"??",
"'default'",
";",
"$",
"this",
"->",
"backups",
"[",
"$",
"name",
"]",
"=",
"$",
"resource",
";",
"return",
"$",
... | Sets current image backup
@param mixed $resource
@param string $name
@return self | [
"Sets",
"current",
"image",
"backup"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Image.php#L244-L251 | train |
netgen-layouts/content-browser-sylius | lib/Backend/ProductBackend.php | ProductBackend.buildLocations | private function buildLocations(array $taxons): array
{
return array_map(
function (TaxonInterface $taxon): Location {
return $this->buildLocation($taxon);
},
$taxons
);
} | php | private function buildLocations(array $taxons): array
{
return array_map(
function (TaxonInterface $taxon): Location {
return $this->buildLocation($taxon);
},
$taxons
);
} | [
"private",
"function",
"buildLocations",
"(",
"array",
"$",
"taxons",
")",
":",
"array",
"{",
"return",
"array_map",
"(",
"function",
"(",
"TaxonInterface",
"$",
"taxon",
")",
":",
"Location",
"{",
"return",
"$",
"this",
"->",
"buildLocation",
"(",
"$",
"t... | Builds the locations from provided taxons.
@param \Sylius\Component\Taxonomy\Model\TaxonInterface[] $taxons
@return \Netgen\ContentBrowser\Sylius\Item\Product\Location[] | [
"Builds",
"the",
"locations",
"from",
"provided",
"taxons",
"."
] | feb3ab56b584f6fbf4b8b6557ba6398513b116e5 | https://github.com/netgen-layouts/content-browser-sylius/blob/feb3ab56b584f6fbf4b8b6557ba6398513b116e5/lib/Backend/ProductBackend.php#L182-L190 | train |
hail-framework/framework | src/Filesystem/Util/ContentListingFormatter.php | ContentListingFormatter.formatListing | public static function formatListing(string $directory, bool $recursive, array $listing)
{
self::$directory = $directory;
self::$recursive = $recursive;
$listing = \array_values(
\array_map(
['self', 'addPathInfo'],
\array_filter($listing, ['self', 'isEntryOutOfScope'])
)
);
return self::sortListing($listing);
} | php | public static function formatListing(string $directory, bool $recursive, array $listing)
{
self::$directory = $directory;
self::$recursive = $recursive;
$listing = \array_values(
\array_map(
['self', 'addPathInfo'],
\array_filter($listing, ['self', 'isEntryOutOfScope'])
)
);
return self::sortListing($listing);
} | [
"public",
"static",
"function",
"formatListing",
"(",
"string",
"$",
"directory",
",",
"bool",
"$",
"recursive",
",",
"array",
"$",
"listing",
")",
"{",
"self",
"::",
"$",
"directory",
"=",
"$",
"directory",
";",
"self",
"::",
"$",
"recursive",
"=",
"$",... | Format contents listing.
@param string $directory
@param bool $recursive
@param array $listing
@return array | [
"Format",
"contents",
"listing",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Util/ContentListingFormatter.php#L32-L45 | train |
hail-framework/framework | src/Http/Request.php | Request.delete | public function delete(string $name): void
{
!$this->all && $this->inputs();
Arrays::delete($this->input, $name);
$this->cache = [];
} | php | public function delete(string $name): void
{
!$this->all && $this->inputs();
Arrays::delete($this->input, $name);
$this->cache = [];
} | [
"public",
"function",
"delete",
"(",
"string",
"$",
"name",
")",
":",
"void",
"{",
"!",
"$",
"this",
"->",
"all",
"&&",
"$",
"this",
"->",
"inputs",
"(",
")",
";",
"Arrays",
"::",
"delete",
"(",
"$",
"this",
"->",
"input",
",",
"$",
"name",
")",
... | Delete from input
@param string $name | [
"Delete",
"from",
"input"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Request.php#L177-L183 | train |
Becklyn/RadBundle | src/Model/DoctrineModel.php | DoctrineModel.getRepository | protected function getRepository ($persistentObject = null) : EntityRepository
{
if (null === $persistentObject)
{
$persistentObject = $this->getFullEntityName();
}
return $this->doctrine->getRepository($persistentObject);
} | php | protected function getRepository ($persistentObject = null) : EntityRepository
{
if (null === $persistentObject)
{
$persistentObject = $this->getFullEntityName();
}
return $this->doctrine->getRepository($persistentObject);
} | [
"protected",
"function",
"getRepository",
"(",
"$",
"persistentObject",
"=",
"null",
")",
":",
"EntityRepository",
"{",
"if",
"(",
"null",
"===",
"$",
"persistentObject",
")",
"{",
"$",
"persistentObject",
"=",
"$",
"this",
"->",
"getFullEntityName",
"(",
")",... | Returns the repository.
@param string|null $persistentObject you can specify which repository you want to load. Defaults to the
automatically derived one.
@return EntityRepository | [
"Returns",
"the",
"repository",
"."
] | 34d5887e13f5a4018843b77dcbefc2eb2f3169f4 | https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/DoctrineModel.php#L48-L56 | train |
Becklyn/RadBundle | src/Model/DoctrineModel.php | DoctrineModel.getFullEntityName | protected function getFullEntityName () : string
{
$entityClass = $this->classNameTransformer->transformModelToEntity(static::class);
if (!\class_exists($entityClass))
{
throw new AutoConfigurationFailedException(\sprintf(
"Cannot automatically generate entity name for model '%s', guessed '%s'.",
static::class,
$entityClass
));
}
return $entityClass;
} | php | protected function getFullEntityName () : string
{
$entityClass = $this->classNameTransformer->transformModelToEntity(static::class);
if (!\class_exists($entityClass))
{
throw new AutoConfigurationFailedException(\sprintf(
"Cannot automatically generate entity name for model '%s', guessed '%s'.",
static::class,
$entityClass
));
}
return $entityClass;
} | [
"protected",
"function",
"getFullEntityName",
"(",
")",
":",
"string",
"{",
"$",
"entityClass",
"=",
"$",
"this",
"->",
"classNameTransformer",
"->",
"transformModelToEntity",
"(",
"static",
"::",
"class",
")",
";",
"if",
"(",
"!",
"\\",
"class_exists",
"(",
... | Returns the entity name.
@throws AutoConfigurationFailedException
@return string the entity reference string | [
"Returns",
"the",
"entity",
"name",
"."
] | 34d5887e13f5a4018843b77dcbefc2eb2f3169f4 | https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/DoctrineModel.php#L77-L91 | train |
Becklyn/RadBundle | src/Model/DoctrineModel.php | DoctrineModel.removeEntity | protected function removeEntity (...$entities) : void
{
try
{
$entities = \array_filter($entities);
if (empty($entities))
{
return;
}
$entityManager = $this->getEntityManager();
\array_map([$entityManager, "remove"], $entities);
$entityManager->flush();
}
catch (ForeignKeyConstraintViolationException $foreignKeyException)
{
throw new EntityRemovalBlockedException(
$entities,
"Can't remove entities as a foreign key constraint failed.",
$foreignKeyException
);
}
} | php | protected function removeEntity (...$entities) : void
{
try
{
$entities = \array_filter($entities);
if (empty($entities))
{
return;
}
$entityManager = $this->getEntityManager();
\array_map([$entityManager, "remove"], $entities);
$entityManager->flush();
}
catch (ForeignKeyConstraintViolationException $foreignKeyException)
{
throw new EntityRemovalBlockedException(
$entities,
"Can't remove entities as a foreign key constraint failed.",
$foreignKeyException
);
}
} | [
"protected",
"function",
"removeEntity",
"(",
"...",
"$",
"entities",
")",
":",
"void",
"{",
"try",
"{",
"$",
"entities",
"=",
"\\",
"array_filter",
"(",
"$",
"entities",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"entities",
")",
")",
"{",
"return",
";... | Removes the given entities.
@param object[] ...$entities | [
"Removes",
"the",
"given",
"entities",
"."
] | 34d5887e13f5a4018843b77dcbefc2eb2f3169f4 | https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/DoctrineModel.php#L111-L134 | train |
systemson/collection | src/Base/ArrayFunctionsTrait.php | ArrayFunctionsTrait.filter | public function filter(Closure $callback): CollectionInterface
{
$array = array_filter(
$this->toArray(),
$callback,
ARRAY_FILTER_USE_BOTH
);
return static::make(array_values($array));
} | php | public function filter(Closure $callback): CollectionInterface
{
$array = array_filter(
$this->toArray(),
$callback,
ARRAY_FILTER_USE_BOTH
);
return static::make(array_values($array));
} | [
"public",
"function",
"filter",
"(",
"Closure",
"$",
"callback",
")",
":",
"CollectionInterface",
"{",
"$",
"array",
"=",
"array_filter",
"(",
"$",
"this",
"->",
"toArray",
"(",
")",
",",
"$",
"callback",
",",
"ARRAY_FILTER_USE_BOTH",
")",
";",
"return",
"... | Returns a new filtered collection using a user-defined function.
@param Closure $callback
@return Collection A new collection instance. | [
"Returns",
"a",
"new",
"filtered",
"collection",
"using",
"a",
"user",
"-",
"defined",
"function",
"."
] | fb3ae1a78806aafabc0562db96822e8b99dc2a64 | https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L45-L54 | train |
systemson/collection | src/Base/ArrayFunctionsTrait.php | ArrayFunctionsTrait.sort | public function sort(Closure $callback = null): CollectionInterface
{
$array = $this->toArray();
if (is_null($callback)) {
sort($array);
} else {
usort(
$array,
$callback
);
}
return static::make($array);
} | php | public function sort(Closure $callback = null): CollectionInterface
{
$array = $this->toArray();
if (is_null($callback)) {
sort($array);
} else {
usort(
$array,
$callback
);
}
return static::make($array);
} | [
"public",
"function",
"sort",
"(",
"Closure",
"$",
"callback",
"=",
"null",
")",
":",
"CollectionInterface",
"{",
"$",
"array",
"=",
"$",
"this",
"->",
"toArray",
"(",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"callback",
")",
")",
"{",
"sort",
"(",
... | Returns a new sorted collection using a user-defined comparison function.
@param Closure $callback The user-defined comparison function.
@return Collection A new collection instance. | [
"Returns",
"a",
"new",
"sorted",
"collection",
"using",
"a",
"user",
"-",
"defined",
"comparison",
"function",
"."
] | fb3ae1a78806aafabc0562db96822e8b99dc2a64 | https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L63-L77 | train |
systemson/collection | src/Base/ArrayFunctionsTrait.php | ArrayFunctionsTrait.chunk | public function chunk(int $size, bool $preserve_keys = false): CollectionInterface
{
$return = array_chunk($this->toArray(), $size, $preserve_keys);
return static::make($return);
} | php | public function chunk(int $size, bool $preserve_keys = false): CollectionInterface
{
$return = array_chunk($this->toArray(), $size, $preserve_keys);
return static::make($return);
} | [
"public",
"function",
"chunk",
"(",
"int",
"$",
"size",
",",
"bool",
"$",
"preserve_keys",
"=",
"false",
")",
":",
"CollectionInterface",
"{",
"$",
"return",
"=",
"array_chunk",
"(",
"$",
"this",
"->",
"toArray",
"(",
")",
",",
"$",
"size",
",",
"$",
... | Splits an array into chunks.
@param int $size The size of each chunk.
@param bool $preserve_keys Whether the keys should be preserved.
@return Collection A new collection instance. | [
"Splits",
"an",
"array",
"into",
"chunks",
"."
] | fb3ae1a78806aafabc0562db96822e8b99dc2a64 | https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L115-L120 | train |
systemson/collection | src/Base/ArrayFunctionsTrait.php | ArrayFunctionsTrait.random | public function random(int $num = 1): CollectionInterface
{
if ($this->isEmpty()) {
return static::make();
}
$keys = array_rand($this->toArray(), $num);
$return = $this->getMultiple((array) $keys);
return static::make($return);
} | php | public function random(int $num = 1): CollectionInterface
{
if ($this->isEmpty()) {
return static::make();
}
$keys = array_rand($this->toArray(), $num);
$return = $this->getMultiple((array) $keys);
return static::make($return);
} | [
"public",
"function",
"random",
"(",
"int",
"$",
"num",
"=",
"1",
")",
":",
"CollectionInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"isEmpty",
"(",
")",
")",
"{",
"return",
"static",
"::",
"make",
"(",
")",
";",
"}",
"$",
"keys",
"=",
"array_rand... | Pick one or more random items from the collection.
@param int $num
@return Collection | [
"Pick",
"one",
"or",
"more",
"random",
"items",
"from",
"the",
"collection",
"."
] | fb3ae1a78806aafabc0562db96822e8b99dc2a64 | https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L183-L194 | train |
Kajna/K-Core | Core/Database/Connections/MSSQLConnection.php | MSSQLConnection.connect | public function connect()
{
try {
// Make string containing database settings
$database = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->database;
// Make connection.
$conn = new \PDO($database, $this->username, $this->password);
// Set attributes from parameters
$conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $this->fetch);
$conn->setAttribute(\PDO::ATTR_ERRMODE, $this->error);
return $conn;
} catch (\PDOException $ex) {
throw new \InvalidArgumentException('Error! Cannot connect to database ' . $ex->getMessage());
}
} | php | public function connect()
{
try {
// Make string containing database settings
$database = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->database;
// Make connection.
$conn = new \PDO($database, $this->username, $this->password);
// Set attributes from parameters
$conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $this->fetch);
$conn->setAttribute(\PDO::ATTR_ERRMODE, $this->error);
return $conn;
} catch (\PDOException $ex) {
throw new \InvalidArgumentException('Error! Cannot connect to database ' . $ex->getMessage());
}
} | [
"public",
"function",
"connect",
"(",
")",
"{",
"try",
"{",
"// Make string containing database settings",
"$",
"database",
"=",
"'sqlsrv:Server='",
".",
"$",
"this",
"->",
"host",
".",
"';Database='",
".",
"$",
"this",
"->",
"database",
";",
"// Make connection."... | Connect to database with using settings
defined in class.
@return \PDO
@throws \PDOException
@throws \InvalidArgumentException | [
"Connect",
"to",
"database",
"with",
"using",
"settings",
"defined",
"in",
"class",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Database/Connections/MSSQLConnection.php#L34-L51 | train |
TheBnl/silverstripe-pageslices | src/extensions/PageSlicesExtension.php | PageSlicesExtension.getSlices | public function getSlices()
{
$controllers = ArrayList::create();
if(
$this->owner instanceof \VirtualPage
&& ($original = $this->owner->CopyContentFrom())
&& $original->hasExtension(self::class))
{
$slices = $original->PageSlices();
} else {
$slices = $this->owner->PageSlices();
}
if ($slices) {
/** @var PageSlice $slice */
foreach ($slices as $slice) {
$controller = $slice->getController();
$controller->init();
$controllers->push($controller);
}
return $controllers;
}
return $controllers;
} | php | public function getSlices()
{
$controllers = ArrayList::create();
if(
$this->owner instanceof \VirtualPage
&& ($original = $this->owner->CopyContentFrom())
&& $original->hasExtension(self::class))
{
$slices = $original->PageSlices();
} else {
$slices = $this->owner->PageSlices();
}
if ($slices) {
/** @var PageSlice $slice */
foreach ($slices as $slice) {
$controller = $slice->getController();
$controller->init();
$controllers->push($controller);
}
return $controllers;
}
return $controllers;
} | [
"public",
"function",
"getSlices",
"(",
")",
"{",
"$",
"controllers",
"=",
"ArrayList",
"::",
"create",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"owner",
"instanceof",
"\\",
"VirtualPage",
"&&",
"(",
"$",
"original",
"=",
"$",
"this",
"->",
"owner"... | Get the slice controllers
@return ArrayList | [
"Get",
"the",
"slice",
"controllers"
] | 5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b | https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/extensions/PageSlicesExtension.php#L59-L84 | train |
TheBnl/silverstripe-pageslices | src/extensions/PageSlicesExtension.php | PageSlicesExtension.onAfterDuplicate | public function onAfterDuplicate(\Page $page)
{
foreach ($this->owner->PageSlices() as $slice) {
/** @var PageSlice $slice */
$sliceCopy = $slice->duplicate(true);
$page->PageSlices()->add($sliceCopy);
$sliceCopy->publishRecursive();
}
} | php | public function onAfterDuplicate(\Page $page)
{
foreach ($this->owner->PageSlices() as $slice) {
/** @var PageSlice $slice */
$sliceCopy = $slice->duplicate(true);
$page->PageSlices()->add($sliceCopy);
$sliceCopy->publishRecursive();
}
} | [
"public",
"function",
"onAfterDuplicate",
"(",
"\\",
"Page",
"$",
"page",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"owner",
"->",
"PageSlices",
"(",
")",
"as",
"$",
"slice",
")",
"{",
"/** @var PageSlice $slice */",
"$",
"sliceCopy",
"=",
"$",
"slice",... | Loop over and copy the attached page slices
@param \Page $page | [
"Loop",
"over",
"and",
"copy",
"the",
"attached",
"page",
"slices"
] | 5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b | https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/extensions/PageSlicesExtension.php#L109-L117 | train |
TheBnl/silverstripe-pageslices | src/extensions/PageSlicesExtension.php | PageSlicesExtension.isValidClass | public function isValidClass()
{
$invalidClassList = array_unique(PageSlice::config()->get('default_slices_exceptions'));
return !in_array($this->owner->getClassName(), $invalidClassList);
} | php | public function isValidClass()
{
$invalidClassList = array_unique(PageSlice::config()->get('default_slices_exceptions'));
return !in_array($this->owner->getClassName(), $invalidClassList);
} | [
"public",
"function",
"isValidClass",
"(",
")",
"{",
"$",
"invalidClassList",
"=",
"array_unique",
"(",
"PageSlice",
"::",
"config",
"(",
")",
"->",
"get",
"(",
"'default_slices_exceptions'",
")",
")",
";",
"return",
"!",
"in_array",
"(",
"$",
"this",
"->",
... | Check if the class is not in the exception list
@return bool | [
"Check",
"if",
"the",
"class",
"is",
"not",
"in",
"the",
"exception",
"list"
] | 5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b | https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/extensions/PageSlicesExtension.php#L124-L128 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.getTokenByClientCredentialsGrant | protected function getTokenByClientCredentialsGrant()
{
$token = $this->getAuthorizationServer()->getAccessToken('client_credentials', [
'scope' => $this->config['client_credentials']['scope'],
]);
$this->getFrameworkBridge()->persistClientToken(
$this->config['client_credentials']['client_id'],
$token->getToken(),
$token->getExpires(),
$token->getValues()['role']
);
return $token;
} | php | protected function getTokenByClientCredentialsGrant()
{
$token = $this->getAuthorizationServer()->getAccessToken('client_credentials', [
'scope' => $this->config['client_credentials']['scope'],
]);
$this->getFrameworkBridge()->persistClientToken(
$this->config['client_credentials']['client_id'],
$token->getToken(),
$token->getExpires(),
$token->getValues()['role']
);
return $token;
} | [
"protected",
"function",
"getTokenByClientCredentialsGrant",
"(",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"getAuthorizationServer",
"(",
")",
"->",
"getAccessToken",
"(",
"'client_credentials'",
",",
"[",
"'scope'",
"=>",
"$",
"this",
"->",
"config",
"["... | Authorize a machine based on the given client credentials.
@return mixed | [
"Authorize",
"a",
"machine",
"based",
"on",
"the",
"given",
"client",
"credentials",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L83-L97 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.getTokenByAuthorizationCodeGrant | protected function getTokenByAuthorizationCodeGrant($code)
{
try {
$token = $this->getAuthorizationServer()->getAccessToken('authorization_code', [
'code' => $code,
]);
$this->getFrameworkBridge()->persistUserToken($token);
return $token;
} catch (IdentityProviderException $e) {
return null;
}
} | php | protected function getTokenByAuthorizationCodeGrant($code)
{
try {
$token = $this->getAuthorizationServer()->getAccessToken('authorization_code', [
'code' => $code,
]);
$this->getFrameworkBridge()->persistUserToken($token);
return $token;
} catch (IdentityProviderException $e) {
return null;
}
} | [
"protected",
"function",
"getTokenByAuthorizationCodeGrant",
"(",
"$",
"code",
")",
"{",
"try",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"getAuthorizationServer",
"(",
")",
"->",
"getAccessToken",
"(",
"'authorization_code'",
",",
"[",
"'code'",
"=>",
"$",
"... | Authorize a user by redirecting to Northstar's single sign-on page.
@param string $code
@return \League\OAuth2\Client\Token\AccessToken | [
"Authorize",
"a",
"user",
"by",
"redirecting",
"to",
"Northstar",
"s",
"single",
"sign",
"-",
"on",
"page",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L105-L118 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.authorize | public function authorize(ServerRequestInterface $request, ResponseInterface $response, $url = '/', $destination = null, $options = [])
{
// Make sure we're making request with the authorization_code grant.
$this->asUser();
$url = $this->getFrameworkBridge()->prepareUrl($url);
$query = $request->getQueryParams();
// If we don't have an authorization code then make one and redirect.
if (! isset($query['code'])) {
$params = array_merge($options, [
'scope' => $this->config['authorization_code']['scope'],
'destination' => ! empty($destination) ? $destination : null,
]);
$authorizationUrl = $this->getAuthorizationServer()->getAuthorizationUrl($params);
// Get the state generated for you and store it to the session.
$state = $this->getAuthorizationServer()->getState();
$this->getFrameworkBridge()->saveStateToken($state);
// Redirect the user to the authorization URL.
return $response->withStatus(302)->withHeader('Location', $authorizationUrl);
}
// Check given state against previously stored one to mitigate CSRF attack
if (! (isset($query['state']) && $query['state'] === $this->getFrameworkBridge()->getStateToken())) {
throw new InternalException('[authorization_code]', 500, 'The OAuth state field did not match.');
}
$token = $this->getTokenByAuthorizationCodeGrant($query['code']);
if (! $token) {
throw new InternalException('[authorization_code]', 500, 'The authorization server did not return a valid access token.');
}
// Find or create a local user account, and create a session for them.
$user = $this->getFrameworkBridge()->getOrCreateUser($token->getResourceOwnerId());
$this->getFrameworkBridge()->login($user, $token);
return $response->withStatus(302)->withHeader('Location', $url);
} | php | public function authorize(ServerRequestInterface $request, ResponseInterface $response, $url = '/', $destination = null, $options = [])
{
// Make sure we're making request with the authorization_code grant.
$this->asUser();
$url = $this->getFrameworkBridge()->prepareUrl($url);
$query = $request->getQueryParams();
// If we don't have an authorization code then make one and redirect.
if (! isset($query['code'])) {
$params = array_merge($options, [
'scope' => $this->config['authorization_code']['scope'],
'destination' => ! empty($destination) ? $destination : null,
]);
$authorizationUrl = $this->getAuthorizationServer()->getAuthorizationUrl($params);
// Get the state generated for you and store it to the session.
$state = $this->getAuthorizationServer()->getState();
$this->getFrameworkBridge()->saveStateToken($state);
// Redirect the user to the authorization URL.
return $response->withStatus(302)->withHeader('Location', $authorizationUrl);
}
// Check given state against previously stored one to mitigate CSRF attack
if (! (isset($query['state']) && $query['state'] === $this->getFrameworkBridge()->getStateToken())) {
throw new InternalException('[authorization_code]', 500, 'The OAuth state field did not match.');
}
$token = $this->getTokenByAuthorizationCodeGrant($query['code']);
if (! $token) {
throw new InternalException('[authorization_code]', 500, 'The authorization server did not return a valid access token.');
}
// Find or create a local user account, and create a session for them.
$user = $this->getFrameworkBridge()->getOrCreateUser($token->getResourceOwnerId());
$this->getFrameworkBridge()->login($user, $token);
return $response->withStatus(302)->withHeader('Location', $url);
} | [
"public",
"function",
"authorize",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
",",
"$",
"url",
"=",
"'/'",
",",
"$",
"destination",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// Make sure we're ... | Handle the OpenID Connect authorization flow.
@TODO: Merge $url & $destination into $options
@param ServerRequestInterface $request
@param ResponseInterface $response
@param string $url - The destination URL to redirect to on a successful login.
@param string $destination - the title for the post-login destination
@param array $options - Array of options to apply
@return ResponseInterface
@throws InternalException | [
"Handle",
"the",
"OpenID",
"Connect",
"authorization",
"flow",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L133-L172 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.logout | public function logout(ResponseInterface $response, $destination = '/')
{
// Make sure we're making request with the authorization_code grant.
$this->asUser();
$this->getFrameworkBridge()->logout();
$destination = $this->getFrameworkBridge()->prepareUrl($destination);
$ssoLogoutUrl = config('services.northstar.url').'/logout?redirect='.$destination;
return $response->withStatus(302)->withHeader('Location', $ssoLogoutUrl);
} | php | public function logout(ResponseInterface $response, $destination = '/')
{
// Make sure we're making request with the authorization_code grant.
$this->asUser();
$this->getFrameworkBridge()->logout();
$destination = $this->getFrameworkBridge()->prepareUrl($destination);
$ssoLogoutUrl = config('services.northstar.url').'/logout?redirect='.$destination;
return $response->withStatus(302)->withHeader('Location', $ssoLogoutUrl);
} | [
"public",
"function",
"logout",
"(",
"ResponseInterface",
"$",
"response",
",",
"$",
"destination",
"=",
"'/'",
")",
"{",
"// Make sure we're making request with the authorization_code grant.",
"$",
"this",
"->",
"asUser",
"(",
")",
";",
"$",
"this",
"->",
"getFrame... | Log a user out of the application and SSO service.
@param ResponseInterface $response
@param string $destination
@return ResponseInterface | [
"Log",
"a",
"user",
"out",
"of",
"the",
"application",
"and",
"SSO",
"service",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L181-L192 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.getTokenByRefreshTokenGrant | public function getTokenByRefreshTokenGrant(AccessToken $oldToken)
{
try {
$token = $this->getAuthorizationServer()->getAccessToken('refresh_token', [
'refresh_token' => $oldToken->getRefreshToken(),
'scope' => $this->config[$this->grant]['scope'],
]);
$this->getFrameworkBridge()->persistUserToken($token);
return $token;
} catch (IdentityProviderException $e) {
$this->getFrameworkBridge()->requestUserCredentials();
return null;
}
} | php | public function getTokenByRefreshTokenGrant(AccessToken $oldToken)
{
try {
$token = $this->getAuthorizationServer()->getAccessToken('refresh_token', [
'refresh_token' => $oldToken->getRefreshToken(),
'scope' => $this->config[$this->grant]['scope'],
]);
$this->getFrameworkBridge()->persistUserToken($token);
return $token;
} catch (IdentityProviderException $e) {
$this->getFrameworkBridge()->requestUserCredentials();
return null;
}
} | [
"public",
"function",
"getTokenByRefreshTokenGrant",
"(",
"AccessToken",
"$",
"oldToken",
")",
"{",
"try",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"getAuthorizationServer",
"(",
")",
"->",
"getAccessToken",
"(",
"'refresh_token'",
",",
"[",
"'refresh_token'",
... | Re-authorize a user based on their stored refresh token.
@param AccessToken $oldToken
@return AccessToken | [
"Re",
"-",
"authorize",
"a",
"user",
"based",
"on",
"their",
"stored",
"refresh",
"token",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L200-L216 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.invalidateCurrentRefreshToken | public function invalidateCurrentRefreshToken()
{
if ($this->grant === 'client_credentials') {
return;
}
$token = $this->getAccessToken();
if ($token) {
$this->invalidateRefreshToken($token);
}
} | php | public function invalidateCurrentRefreshToken()
{
if ($this->grant === 'client_credentials') {
return;
}
$token = $this->getAccessToken();
if ($token) {
$this->invalidateRefreshToken($token);
}
} | [
"public",
"function",
"invalidateCurrentRefreshToken",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"grant",
"===",
"'client_credentials'",
")",
"{",
"return",
";",
"}",
"$",
"token",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
";",
"if",
"(",
"$... | Invalidate the authenticated user's refresh token. | [
"Invalidate",
"the",
"authenticated",
"user",
"s",
"refresh",
"token",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L221-L231 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.invalidateRefreshToken | public function invalidateRefreshToken(AccessToken $token)
{
$this->getAuthorizationServer()->getAuthenticatedRequest('DELETE',
$this->authorizationServerUri . '/v2/auth/token', $token, [
'json' => [
'token' => $token->getRefreshToken(),
],
]);
$user = $this->getFrameworkBridge()->getUser($token->getResourceOwnerId());
$user->clearOAuthToken();
} | php | public function invalidateRefreshToken(AccessToken $token)
{
$this->getAuthorizationServer()->getAuthenticatedRequest('DELETE',
$this->authorizationServerUri . '/v2/auth/token', $token, [
'json' => [
'token' => $token->getRefreshToken(),
],
]);
$user = $this->getFrameworkBridge()->getUser($token->getResourceOwnerId());
$user->clearOAuthToken();
} | [
"public",
"function",
"invalidateRefreshToken",
"(",
"AccessToken",
"$",
"token",
")",
"{",
"$",
"this",
"->",
"getAuthorizationServer",
"(",
")",
"->",
"getAuthenticatedRequest",
"(",
"'DELETE'",
",",
"$",
"this",
"->",
"authorizationServerUri",
".",
"'/v2/auth/tok... | Invalidate the refresh token for the given access token.
@param AccessToken $token | [
"Invalidate",
"the",
"refresh",
"token",
"for",
"the",
"given",
"access",
"token",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L238-L249 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.getAccessToken | protected function getAccessToken()
{
switch ($this->grant) {
case 'provided_token':
return $this->token;
case 'client_credentials':
return $this->getFrameworkBridge()->getClientToken();
case 'authorization_code':
$user = $this->getFrameworkBridge()->getCurrentUser();
if (! $user) {
return null;
}
return $user->getOAuthToken();
default:
throw new \Exception('Unsupported grant type. Check $this->grant.');
}
} | php | protected function getAccessToken()
{
switch ($this->grant) {
case 'provided_token':
return $this->token;
case 'client_credentials':
return $this->getFrameworkBridge()->getClientToken();
case 'authorization_code':
$user = $this->getFrameworkBridge()->getCurrentUser();
if (! $user) {
return null;
}
return $user->getOAuthToken();
default:
throw new \Exception('Unsupported grant type. Check $this->grant.');
}
} | [
"protected",
"function",
"getAccessToken",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"grant",
")",
"{",
"case",
"'provided_token'",
":",
"return",
"$",
"this",
"->",
"token",
";",
"case",
"'client_credentials'",
":",
"return",
"$",
"this",
"->",
"ge... | Get the access token from the repository based on the chosen grant.
@return AccessToken|null
@throws \Exception | [
"Get",
"the",
"access",
"token",
"from",
"the",
"repository",
"based",
"on",
"the",
"chosen",
"grant",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L308-L329 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.refreshIfExpired | public function refreshIfExpired()
{
$user = $this->getFrameworkBridge()->getCurrentUser();
if (! $user) {
return null;
}
$token = $user->getOAuthToken();
if ($token && $token->hasExpired()) {
$this->refreshAccessToken($token);
}
} | php | public function refreshIfExpired()
{
$user = $this->getFrameworkBridge()->getCurrentUser();
if (! $user) {
return null;
}
$token = $user->getOAuthToken();
if ($token && $token->hasExpired()) {
$this->refreshAccessToken($token);
}
} | [
"public",
"function",
"refreshIfExpired",
"(",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getFrameworkBridge",
"(",
")",
"->",
"getCurrentUser",
"(",
")",
";",
"if",
"(",
"!",
"$",
"user",
")",
"{",
"return",
"null",
";",
"}",
"$",
"token",
"=",... | If a user is logged in & has an expired access token,
fetch a new one using their refresh token.
@return void | [
"If",
"a",
"user",
"is",
"logged",
"in",
"&",
"has",
"an",
"expired",
"access",
"token",
"fetch",
"a",
"new",
"one",
"using",
"their",
"refresh",
"token",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L337-L349 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.refreshAccessToken | protected function refreshAccessToken($token)
{
switch ($this->grant) {
case 'provided_token':
throw new UnauthorizedException('[internal]', 'The provided token expired.');
case 'client_credentials':
return $this->getTokenByClientCredentialsGrant();
case 'authorization_code':
return $this->getTokenByRefreshTokenGrant($token);
default:
throw new \Exception('Unsupported grant type. Check $this->grant.');
}
} | php | protected function refreshAccessToken($token)
{
switch ($this->grant) {
case 'provided_token':
throw new UnauthorizedException('[internal]', 'The provided token expired.');
case 'client_credentials':
return $this->getTokenByClientCredentialsGrant();
case 'authorization_code':
return $this->getTokenByRefreshTokenGrant($token);
default:
throw new \Exception('Unsupported grant type. Check $this->grant.');
}
} | [
"protected",
"function",
"refreshAccessToken",
"(",
"$",
"token",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"grant",
")",
"{",
"case",
"'provided_token'",
":",
"throw",
"new",
"UnauthorizedException",
"(",
"'[internal]'",
",",
"'The provided token expired.'",
")... | Get a new access token based on the chosen grant.
@param $token
@return mixed
@throws \Exception | [
"Get",
"a",
"new",
"access",
"token",
"based",
"on",
"the",
"chosen",
"grant",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L358-L373 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.getAuthorizationHeader | protected function getAuthorizationHeader($forceRefresh = false)
{
$token = $this->getAccessToken();
// If we're using a token provided with the request, return it.
if ($this->grant === 'provided_token') {
return ['Authorization' => 'Bearer ' . $token->getToken()];
}
// Don't attempt to refresh token if there isn't a logged-in user.
$user = $this->getFrameworkBridge()->getCurrentUser();
if ($this->grant === 'authorization_code' && ! $user) {
return [];
}
// If the token is expired, fetch a new one before making the request.
if (! $token || ($token && $token->hasExpired()) || $forceRefresh) {
$token = $this->refreshAccessToken($token);
}
return $this->getAuthorizationServer()->getHeaders($token);
} | php | protected function getAuthorizationHeader($forceRefresh = false)
{
$token = $this->getAccessToken();
// If we're using a token provided with the request, return it.
if ($this->grant === 'provided_token') {
return ['Authorization' => 'Bearer ' . $token->getToken()];
}
// Don't attempt to refresh token if there isn't a logged-in user.
$user = $this->getFrameworkBridge()->getCurrentUser();
if ($this->grant === 'authorization_code' && ! $user) {
return [];
}
// If the token is expired, fetch a new one before making the request.
if (! $token || ($token && $token->hasExpired()) || $forceRefresh) {
$token = $this->refreshAccessToken($token);
}
return $this->getAuthorizationServer()->getHeaders($token);
} | [
"protected",
"function",
"getAuthorizationHeader",
"(",
"$",
"forceRefresh",
"=",
"false",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
";",
"// If we're using a token provided with the request, return it.",
"if",
"(",
"$",
"this",
"->... | Get the authorization header for a request, if needed.
Overrides this empty method in RestApiClient.
@param bool $forceRefresh - Should the token be refreshed, even if expiration timestamp hasn't passed?
@return array
@throws \Exception | [
"Get",
"the",
"authorization",
"header",
"for",
"a",
"request",
"if",
"needed",
".",
"Overrides",
"this",
"empty",
"method",
"in",
"RestApiClient",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L383-L404 | train |
DoSomething/gateway | src/AuthorizesWithOAuth2.php | AuthorizesWithOAuth2.getAuthorizationServer | protected function getAuthorizationServer()
{
if (! $this->authorizationServer) {
$config = $this->config[$this->grant];
$options = [
'url' => $this->authorizationServerUri,
'clientId' => $config['client_id'],
'clientSecret' => $config['client_secret'],
];
if (! empty($config['redirect_uri'])) {
$options['redirectUri'] = $this->getFrameworkBridge()->prepareUrl($config['redirect_uri']);
}
// Allow setting a custom handler (for mocking requests in tests).
if (! empty($this->config['handler'])) {
$options['handler'] = $this->config['handler'];
}
$this->authorizationServer = new NorthstarOAuthProvider($options);
}
return $this->authorizationServer;
} | php | protected function getAuthorizationServer()
{
if (! $this->authorizationServer) {
$config = $this->config[$this->grant];
$options = [
'url' => $this->authorizationServerUri,
'clientId' => $config['client_id'],
'clientSecret' => $config['client_secret'],
];
if (! empty($config['redirect_uri'])) {
$options['redirectUri'] = $this->getFrameworkBridge()->prepareUrl($config['redirect_uri']);
}
// Allow setting a custom handler (for mocking requests in tests).
if (! empty($this->config['handler'])) {
$options['handler'] = $this->config['handler'];
}
$this->authorizationServer = new NorthstarOAuthProvider($options);
}
return $this->authorizationServer;
} | [
"protected",
"function",
"getAuthorizationServer",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"authorizationServer",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"config",
"[",
"$",
"this",
"->",
"grant",
"]",
";",
"$",
"options",
"=",
"[",
... | Get the authorization server. | [
"Get",
"the",
"authorization",
"server",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L432-L456 | train |
Kajna/K-Core | Core/Pagination/Pagination.php | Pagination.create | public function create()
{
$r = '';// Variable to hold result
// Calculate the total number of pages
$num_pages = ceil($this->totalRows / $this->perPage);
// If there is only one page make no links
if ($num_pages === 1 || $this->totalRows === 0) {
return '';
}
$display_offset = (int)($this->numLinks / 2);//precalculate display offset according to numLinks
$r .= '<div class="" id="pagination"><ul class="pagination">';//set opening tags
$r .= '<li class="' . $this->liClass . '" id="1"><a href="' . $this->baseUrl . '/0/' . $this->perPage . $this->extraParams . '">«</a></li>';//set go to first tag
$start = 0;
$end = $num_pages;
if (!($num_pages <= $this->numLinks)) {//if total pages is less than numLinks display all pages at once
$cur_link_number = ($this->curOffset / $this->perPage);
if (($cur_link_number) <= $display_offset) {//if current link in first set of links
$start = 0;
$end = $this->numLinks;
} elseif ($num_pages - $cur_link_number <= $display_offset) {//if current link in last set of links
$start = $num_pages - $this->numLinks;
$end = $num_pages;
} else {//if current link in middle set of links
$start = $cur_link_number - $display_offset;
$end = $cur_link_number + $display_offset + 1;
}
}
// Create links according to parameters
for ($i = $start; $i < $end; ++$i) {// Create links tags
$offset = $i * $this->perPage;// Set offset to pass to jquery function
if ($offset != $this->curOffset) $class = ''; else $class = ' active';// Set current link active
// Add link to result variable
$r .= '<li class="' . $this->liClass . $class . '" id="' . ($i + 1) . '">
<a href="' . $this->baseUrl . '/' . ($i * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">' . ($i + 1) . '</a></li>';
}
$r .= '<li class="' . $this->liClass . '" id="' . $num_pages . '"><a href="' . $this->baseUrl . '/' . (($num_pages - 1) * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">»</a></li>';//set go to last tag
$r .= '</div><ul>';// Set closing tags
return $r;// Return final result
} | php | public function create()
{
$r = '';// Variable to hold result
// Calculate the total number of pages
$num_pages = ceil($this->totalRows / $this->perPage);
// If there is only one page make no links
if ($num_pages === 1 || $this->totalRows === 0) {
return '';
}
$display_offset = (int)($this->numLinks / 2);//precalculate display offset according to numLinks
$r .= '<div class="" id="pagination"><ul class="pagination">';//set opening tags
$r .= '<li class="' . $this->liClass . '" id="1"><a href="' . $this->baseUrl . '/0/' . $this->perPage . $this->extraParams . '">«</a></li>';//set go to first tag
$start = 0;
$end = $num_pages;
if (!($num_pages <= $this->numLinks)) {//if total pages is less than numLinks display all pages at once
$cur_link_number = ($this->curOffset / $this->perPage);
if (($cur_link_number) <= $display_offset) {//if current link in first set of links
$start = 0;
$end = $this->numLinks;
} elseif ($num_pages - $cur_link_number <= $display_offset) {//if current link in last set of links
$start = $num_pages - $this->numLinks;
$end = $num_pages;
} else {//if current link in middle set of links
$start = $cur_link_number - $display_offset;
$end = $cur_link_number + $display_offset + 1;
}
}
// Create links according to parameters
for ($i = $start; $i < $end; ++$i) {// Create links tags
$offset = $i * $this->perPage;// Set offset to pass to jquery function
if ($offset != $this->curOffset) $class = ''; else $class = ' active';// Set current link active
// Add link to result variable
$r .= '<li class="' . $this->liClass . $class . '" id="' . ($i + 1) . '">
<a href="' . $this->baseUrl . '/' . ($i * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">' . ($i + 1) . '</a></li>';
}
$r .= '<li class="' . $this->liClass . '" id="' . $num_pages . '"><a href="' . $this->baseUrl . '/' . (($num_pages - 1) * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">»</a></li>';//set go to last tag
$r .= '</div><ul>';// Set closing tags
return $r;// Return final result
} | [
"public",
"function",
"create",
"(",
")",
"{",
"$",
"r",
"=",
"''",
";",
"// Variable to hold result",
"// Calculate the total number of pages",
"$",
"num_pages",
"=",
"ceil",
"(",
"$",
"this",
"->",
"totalRows",
"/",
"$",
"this",
"->",
"perPage",
")",
";",
... | Generate the pagination links.
@return string (HTML of pagination menu) | [
"Generate",
"the",
"pagination",
"links",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Pagination/Pagination.php#L115-L159 | train |
htmlburger/wpemerge-cli | src/Commands/Install.php | Install.shouldRemoveComposerAuthorInformation | protected function shouldRemoveComposerAuthorInformation( InputInterface $input, OutputInterface $output ) {
$helper = $this->getHelper( 'question' );
$question = new ConfirmationQuestion(
'Would you like to remove author information from composer.json? <info>[y/N]</info> ',
false
);
$install = $helper->ask( $input, $output, $question );
$output->writeln( '' );
return $install;
} | php | protected function shouldRemoveComposerAuthorInformation( InputInterface $input, OutputInterface $output ) {
$helper = $this->getHelper( 'question' );
$question = new ConfirmationQuestion(
'Would you like to remove author information from composer.json? <info>[y/N]</info> ',
false
);
$install = $helper->ask( $input, $output, $question );
$output->writeln( '' );
return $install;
} | [
"protected",
"function",
"shouldRemoveComposerAuthorInformation",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"helper",
"=",
"$",
"this",
"->",
"getHelper",
"(",
"'question'",
")",
";",
"$",
"question",
"=",
"new",
... | Check whether composer.json should be cleaned of author information
@param InputInterface $input
@param OutputInterface $output
@return boolean | [
"Check",
"whether",
"composer",
".",
"json",
"should",
"be",
"cleaned",
"of",
"author",
"information"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L72-L84 | train |
htmlburger/wpemerge-cli | src/Commands/Install.php | Install.removeComposerAuthorInformation | protected function removeComposerAuthorInformation( InputInterface $input, OutputInterface $output ) {
$command = $this->getApplication()->find( 'install:clean-composer' );
$output->write( '<comment>Cleaning <info>composer.json</info> ...</comment>' );
$command->run( new ArrayInput( [
'command' => 'install:carbon-fields',
] ), new NullOutput() );
$output->writeln( ' <info>Done</info>' );
} | php | protected function removeComposerAuthorInformation( InputInterface $input, OutputInterface $output ) {
$command = $this->getApplication()->find( 'install:clean-composer' );
$output->write( '<comment>Cleaning <info>composer.json</info> ...</comment>' );
$command->run( new ArrayInput( [
'command' => 'install:carbon-fields',
] ), new NullOutput() );
$output->writeln( ' <info>Done</info>' );
} | [
"protected",
"function",
"removeComposerAuthorInformation",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"command",
"=",
"$",
"this",
"->",
"getApplication",
"(",
")",
"->",
"find",
"(",
"'install:clean-composer'",
")"... | Remove author information from composer.json
@param InputInterface $input
@param OutputInterface $output
@return void | [
"Remove",
"author",
"information",
"from",
"composer",
".",
"json"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L93-L103 | train |
htmlburger/wpemerge-cli | src/Commands/Install.php | Install.shouldInstallCssFramework | protected function shouldInstallCssFramework( InputInterface $input, OutputInterface $output ) {
$helper = $this->getHelper( 'question' );
$question = new ChoiceQuestion(
'Please select a CSS framework:',
['None', 'Normalize.css', 'Bootstrap', 'Bulma', 'Foundation', 'Tachyons', 'Tailwind CSS', 'Spectre.css'],
0
);
$css_framework = $helper->ask( $input, $output, $question );
$output->writeln( '' );
return $css_framework;
} | php | protected function shouldInstallCssFramework( InputInterface $input, OutputInterface $output ) {
$helper = $this->getHelper( 'question' );
$question = new ChoiceQuestion(
'Please select a CSS framework:',
['None', 'Normalize.css', 'Bootstrap', 'Bulma', 'Foundation', 'Tachyons', 'Tailwind CSS', 'Spectre.css'],
0
);
$css_framework = $helper->ask( $input, $output, $question );
$output->writeln( '' );
return $css_framework;
} | [
"protected",
"function",
"shouldInstallCssFramework",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"helper",
"=",
"$",
"this",
"->",
"getHelper",
"(",
"'question'",
")",
";",
"$",
"question",
"=",
"new",
"ChoiceQue... | Check whether any CSS framework should be installed
@param InputInterface $input
@param OutputInterface $output
@return string | [
"Check",
"whether",
"any",
"CSS",
"framework",
"should",
"be",
"installed"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L148-L161 | train |
htmlburger/wpemerge-cli | src/Commands/Install.php | Install.installCssFramework | protected function installCssFramework( InputInterface $input, OutputInterface $output, $css_framework ) {
$command = $this->getApplication()->find( 'install:css-framework' );
$this->runInstallCommand( $css_framework, $command, new ArrayInput( [
'command' => 'install:css-framework',
'css-framework' => $css_framework,
] ), $output );
} | php | protected function installCssFramework( InputInterface $input, OutputInterface $output, $css_framework ) {
$command = $this->getApplication()->find( 'install:css-framework' );
$this->runInstallCommand( $css_framework, $command, new ArrayInput( [
'command' => 'install:css-framework',
'css-framework' => $css_framework,
] ), $output );
} | [
"protected",
"function",
"installCssFramework",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
",",
"$",
"css_framework",
")",
"{",
"$",
"command",
"=",
"$",
"this",
"->",
"getApplication",
"(",
")",
"->",
"find",
"(",
"'install:cs... | Install any CSS framework
@param InputInterface $input
@param OutputInterface $output
@param string $css_framework
@return void | [
"Install",
"any",
"CSS",
"framework"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L171-L178 | train |
htmlburger/wpemerge-cli | src/Commands/Install.php | Install.installFontAwesome | protected function installFontAwesome( InputInterface $input, OutputInterface $output ) {
$command = $this->getApplication()->find( 'install:font-awesome' );
$this->runInstallCommand( 'Font Awesome', $command, new ArrayInput( [
'command' => 'install:font-awesome',
] ), $output );
} | php | protected function installFontAwesome( InputInterface $input, OutputInterface $output ) {
$command = $this->getApplication()->find( 'install:font-awesome' );
$this->runInstallCommand( 'Font Awesome', $command, new ArrayInput( [
'command' => 'install:font-awesome',
] ), $output );
} | [
"protected",
"function",
"installFontAwesome",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"command",
"=",
"$",
"this",
"->",
"getApplication",
"(",
")",
"->",
"find",
"(",
"'install:font-awesome'",
")",
";",
"$",... | Install Font Awesome
@param InputInterface $input
@param OutputInterface $output
@return void | [
"Install",
"Font",
"Awesome"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L208-L214 | train |
htmlburger/wpemerge-cli | src/Commands/Install.php | Install.shouldProceedWithInstall | protected function shouldProceedWithInstall( InputInterface $input, OutputInterface $output, $config ) {
$helper = $this->getHelper( 'question' );
$output->writeln( 'Configuration:' );
$output->writeln(
str_pad( 'Clean composer.json: ', 25 ) .
( $config['remove_composer_author_information'] ? '<info>Yes</info>' : '<comment>No</comment>' )
);
$output->writeln(
str_pad( 'Install Carbon Fields: ', 25 ) .
( $config['install_carbon_fields'] ? '<info>Yes</info>' : '<comment>No</comment>' )
);
$output->writeln(
str_pad( 'Install CSS Framework: ', 25 ) .
'<info>' . $config['install_css_framework'] . '</info>'
);
$output->writeln(
str_pad( 'Install Font Awesome: ', 25 ) .
( $config['install_font_awesome'] ? '<info>Yes</info>' : '<comment>No</comment>' )
);
$output->writeln( '' );
$question = new ConfirmationQuestion(
'Proceed with installation? <info>[Y/n]</info> ',
true
);
$proceed = $helper->ask( $input, $output, $question );
$output->writeln( '' );
return $proceed;
} | php | protected function shouldProceedWithInstall( InputInterface $input, OutputInterface $output, $config ) {
$helper = $this->getHelper( 'question' );
$output->writeln( 'Configuration:' );
$output->writeln(
str_pad( 'Clean composer.json: ', 25 ) .
( $config['remove_composer_author_information'] ? '<info>Yes</info>' : '<comment>No</comment>' )
);
$output->writeln(
str_pad( 'Install Carbon Fields: ', 25 ) .
( $config['install_carbon_fields'] ? '<info>Yes</info>' : '<comment>No</comment>' )
);
$output->writeln(
str_pad( 'Install CSS Framework: ', 25 ) .
'<info>' . $config['install_css_framework'] . '</info>'
);
$output->writeln(
str_pad( 'Install Font Awesome: ', 25 ) .
( $config['install_font_awesome'] ? '<info>Yes</info>' : '<comment>No</comment>' )
);
$output->writeln( '' );
$question = new ConfirmationQuestion(
'Proceed with installation? <info>[Y/n]</info> ',
true
);
$proceed = $helper->ask( $input, $output, $question );
$output->writeln( '' );
return $proceed;
} | [
"protected",
"function",
"shouldProceedWithInstall",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
",",
"$",
"config",
")",
"{",
"$",
"helper",
"=",
"$",
"this",
"->",
"getHelper",
"(",
"'question'",
")",
";",
"$",
"output",
"->... | Check whether we should proceed with installation
@param InputInterface $input
@param OutputInterface $output
@param array $config
@return boolean | [
"Check",
"whether",
"we",
"should",
"proceed",
"with",
"installation"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L224-L260 | train |
htmlburger/wpemerge-cli | src/Commands/Install.php | Install.runInstallCommand | protected function runInstallCommand( $label, Command $command, InputInterface $input, OutputInterface $output ) {
$buffered_output = new BufferedOutput();
$buffered_output->setVerbosity( $output->getVerbosity() );
$output->write( '<comment>Installing <info>' . $label . '</info> ...</comment>' );
$command->run( $input, $buffered_output );
$output->writeln( ' <info>Done</info>' );
$buffered_output_value = $buffered_output->fetch();
if ( ! empty( $buffered_output_value ) ) {
$output->writeln( '---' );
$output->writeln( trim( $buffered_output_value ) );
$output->writeln( '---' );
}
} | php | protected function runInstallCommand( $label, Command $command, InputInterface $input, OutputInterface $output ) {
$buffered_output = new BufferedOutput();
$buffered_output->setVerbosity( $output->getVerbosity() );
$output->write( '<comment>Installing <info>' . $label . '</info> ...</comment>' );
$command->run( $input, $buffered_output );
$output->writeln( ' <info>Done</info>' );
$buffered_output_value = $buffered_output->fetch();
if ( ! empty( $buffered_output_value ) ) {
$output->writeln( '---' );
$output->writeln( trim( $buffered_output_value ) );
$output->writeln( '---' );
}
} | [
"protected",
"function",
"runInstallCommand",
"(",
"$",
"label",
",",
"Command",
"$",
"command",
",",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"buffered_output",
"=",
"new",
"BufferedOutput",
"(",
")",
";",
"$",
"... | Install a preset
@param string $label
@param Command $command
@param InputInterface $input
@param OutputInterface $output
@return void | [
"Install",
"a",
"preset"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L271-L285 | train |
mirko-pagliai/php-tools | src/BodyParser.php | BodyParser.extractLinks | public function extractLinks()
{
if ($this->extractedLinks) {
return $this->extractedLinks;
}
if (!is_html($this->body)) {
return [];
}
$libxmlPreviousState = libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTML($this->body);
libxml_clear_errors();
libxml_use_internal_errors($libxmlPreviousState);
$links = [];
foreach ($this->tags as $tag => $attribute) {
foreach ($dom->getElementsByTagName($tag) as $element) {
$link = $element->getAttribute($attribute);
if (!$link) {
continue;
}
$links[] = clean_url(url_to_absolute($this->url, $link), true, true);
}
}
return $this->extractedLinks = array_unique($links);
} | php | public function extractLinks()
{
if ($this->extractedLinks) {
return $this->extractedLinks;
}
if (!is_html($this->body)) {
return [];
}
$libxmlPreviousState = libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTML($this->body);
libxml_clear_errors();
libxml_use_internal_errors($libxmlPreviousState);
$links = [];
foreach ($this->tags as $tag => $attribute) {
foreach ($dom->getElementsByTagName($tag) as $element) {
$link = $element->getAttribute($attribute);
if (!$link) {
continue;
}
$links[] = clean_url(url_to_absolute($this->url, $link), true, true);
}
}
return $this->extractedLinks = array_unique($links);
} | [
"public",
"function",
"extractLinks",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"extractedLinks",
")",
"{",
"return",
"$",
"this",
"->",
"extractedLinks",
";",
"}",
"if",
"(",
"!",
"is_html",
"(",
"$",
"this",
"->",
"body",
")",
")",
"{",
"return"... | Extracs links from body
@return array
@uses $body
@uses $extractedLinks
@uses $tags
@uses $url | [
"Extracs",
"links",
"from",
"body"
] | 46003b05490de4b570b46c6377f1e09139ffe43b | https://github.com/mirko-pagliai/php-tools/blob/46003b05490de4b570b46c6377f1e09139ffe43b/src/BodyParser.php#L87-L120 | train |
mcrumm/pecan | src/Console/Output/PecanOutput.php | PecanOutput.initializePipes | protected function initializePipes()
{
$this->pipes = [
fopen($this->hasStdoutSupport() ? 'php://stdout' : 'php://output', 'w'),
fopen('php://stderr', 'w'),
];
foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, 0);
}
} | php | protected function initializePipes()
{
$this->pipes = [
fopen($this->hasStdoutSupport() ? 'php://stdout' : 'php://output', 'w'),
fopen('php://stderr', 'w'),
];
foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, 0);
}
} | [
"protected",
"function",
"initializePipes",
"(",
")",
"{",
"$",
"this",
"->",
"pipes",
"=",
"[",
"fopen",
"(",
"$",
"this",
"->",
"hasStdoutSupport",
"(",
")",
"?",
"'php://stdout'",
":",
"'php://output'",
",",
"'w'",
")",
",",
"fopen",
"(",
"'php://stderr... | Initialize the STDOUT and STDERR pipes. | [
"Initialize",
"the",
"STDOUT",
"and",
"STDERR",
"pipes",
"."
] | f35f01249587a4df45c7d3ab78f3e51919471177 | https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Console/Output/PecanOutput.php#L66-L76 | train |
railken/amethyst-template | src/Managers/TemplateManager.php | TemplateManager.getGeneratorOrFail | public function getGeneratorOrFail(string $filetype)
{
$generators = config('amethyst.template.generators', []);
$generator = isset($generators[$filetype]) ? $generators[$filetype] : null;
if (!$generator) {
throw new Exceptions\GeneratorNotFoundException(sprintf('No generator found for: %s', $filetype));
}
return $generator;
} | php | public function getGeneratorOrFail(string $filetype)
{
$generators = config('amethyst.template.generators', []);
$generator = isset($generators[$filetype]) ? $generators[$filetype] : null;
if (!$generator) {
throw new Exceptions\GeneratorNotFoundException(sprintf('No generator found for: %s', $filetype));
}
return $generator;
} | [
"public",
"function",
"getGeneratorOrFail",
"(",
"string",
"$",
"filetype",
")",
"{",
"$",
"generators",
"=",
"config",
"(",
"'amethyst.template.generators'",
",",
"[",
"]",
")",
";",
"$",
"generator",
"=",
"isset",
"(",
"$",
"generators",
"[",
"$",
"filetyp... | Retrieve the generator given the template or throw exception.
@param string $filetype
@return \Railken\Template\Generators\GeneratorContract | [
"Retrieve",
"the",
"generator",
"given",
"the",
"template",
"or",
"throw",
"exception",
"."
] | 211d696dd5636b85e44ab27061f72a4f792b128c | https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L33-L44 | train |
railken/amethyst-template | src/Managers/TemplateManager.php | TemplateManager.render | public function render(DataBuilder $data_builder, string $filetype, $parameters, array $data = [])
{
$result = new Result();
try {
$bag = new Bag($parameters);
$bag->set('content', $this->renderRaw($filetype, strval($bag->get('content')), $data));
$result->setResources(new Collection([$bag->toArray()]));
} catch (\Twig_Error $e) {
$e = new Exceptions\TemplateRenderException($e->getRawMessage().' on line '.$e->getTemplateLine());
$result->addErrors(new Collection([$e]));
}
return $result;
} | php | public function render(DataBuilder $data_builder, string $filetype, $parameters, array $data = [])
{
$result = new Result();
try {
$bag = new Bag($parameters);
$bag->set('content', $this->renderRaw($filetype, strval($bag->get('content')), $data));
$result->setResources(new Collection([$bag->toArray()]));
} catch (\Twig_Error $e) {
$e = new Exceptions\TemplateRenderException($e->getRawMessage().' on line '.$e->getTemplateLine());
$result->addErrors(new Collection([$e]));
}
return $result;
} | [
"public",
"function",
"render",
"(",
"DataBuilder",
"$",
"data_builder",
",",
"string",
"$",
"filetype",
",",
"$",
"parameters",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"try",
"{",
"$",
... | Render an email.
@param DataBuilder $data_builder
@param string $filetype
@param array $parameters
@param array $data
@return \Railken\Lem\Contracts\ResultContract | [
"Render",
"an",
"email",
"."
] | 211d696dd5636b85e44ab27061f72a4f792b128c | https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L56-L73 | train |
railken/amethyst-template | src/Managers/TemplateManager.php | TemplateManager.renderRaw | public function renderRaw(string $filetype, string $content, array $data)
{
$generator = $this->getGeneratorOrFail($filetype);
$generator = new $generator();
return $generator->generateAndRender($content, $data);
} | php | public function renderRaw(string $filetype, string $content, array $data)
{
$generator = $this->getGeneratorOrFail($filetype);
$generator = new $generator();
return $generator->generateAndRender($content, $data);
} | [
"public",
"function",
"renderRaw",
"(",
"string",
"$",
"filetype",
",",
"string",
"$",
"content",
",",
"array",
"$",
"data",
")",
"{",
"$",
"generator",
"=",
"$",
"this",
"->",
"getGeneratorOrFail",
"(",
"$",
"filetype",
")",
";",
"$",
"generator",
"=",
... | Render given template with data.
@param string $filetype
@param string $content
@param array $data
@return mixed | [
"Render",
"given",
"template",
"with",
"data",
"."
] | 211d696dd5636b85e44ab27061f72a4f792b128c | https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L84-L90 | train |
railken/amethyst-template | src/Managers/TemplateManager.php | TemplateManager.renderMock | public function renderMock(Template $template)
{
return $this->render($template->data_builder, $template->filetype, ['content' => $template->content], Yaml::parse((string) $template->data_builder->mock_data));
} | php | public function renderMock(Template $template)
{
return $this->render($template->data_builder, $template->filetype, ['content' => $template->content], Yaml::parse((string) $template->data_builder->mock_data));
} | [
"public",
"function",
"renderMock",
"(",
"Template",
"$",
"template",
")",
"{",
"return",
"$",
"this",
"->",
"render",
"(",
"$",
"template",
"->",
"data_builder",
",",
"$",
"template",
"->",
"filetype",
",",
"[",
"'content'",
"=>",
"$",
"template",
"->",
... | Render mock template.
@param Template $template
@return mixed | [
"Render",
"mock",
"template",
"."
] | 211d696dd5636b85e44ab27061f72a4f792b128c | https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L99-L102 | train |
railken/amethyst-template | src/Managers/TemplateManager.php | TemplateManager.checksumByPath | public function checksumByPath(string $path)
{
return file_exists($path) ? $this->checksum((string) file_get_contents($path)) : null;
} | php | public function checksumByPath(string $path)
{
return file_exists($path) ? $this->checksum((string) file_get_contents($path)) : null;
} | [
"public",
"function",
"checksumByPath",
"(",
"string",
"$",
"path",
")",
"{",
"return",
"file_exists",
"(",
"$",
"path",
")",
"?",
"$",
"this",
"->",
"checksum",
"(",
"(",
"string",
")",
"file_get_contents",
"(",
"$",
"path",
")",
")",
":",
"null",
";"... | Calculate checksum by path file.
@param string $path
@return string|null | [
"Calculate",
"checksum",
"by",
"path",
"file",
"."
] | 211d696dd5636b85e44ab27061f72a4f792b128c | https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L121-L124 | train |
TheBnl/silverstripe-pageslices | src/controller/PageSliceControllerExtension.php | PageSliceControllerExtension.handleSlice | public function handleSlice()
{
if (!$id = $this->owner->getRequest()->param('ID')) {
return false;
}
$sliceRelations = array();
if (!$hasManyRelations = $this->owner->data()->hasMany()) {
return false;
}
foreach ($hasManyRelations as $relationName => $relationClass) {
if ($relationClass == PageSlice::class || is_subclass_of($relationClass, PageSlice::class)) {
$sliceRelations[] = $relationName;
}
}
$slice = null;
foreach ($sliceRelations as $sliceRelation) {
if ($slice) {
break;
}
/** @var PageSlice $slice */
$slice = $this->owner->data()->$sliceRelation()->find('ID', $id);
}
if (!$slice) {
user_error('No slice found', E_USER_ERROR);
}
return $slice->getController();
} | php | public function handleSlice()
{
if (!$id = $this->owner->getRequest()->param('ID')) {
return false;
}
$sliceRelations = array();
if (!$hasManyRelations = $this->owner->data()->hasMany()) {
return false;
}
foreach ($hasManyRelations as $relationName => $relationClass) {
if ($relationClass == PageSlice::class || is_subclass_of($relationClass, PageSlice::class)) {
$sliceRelations[] = $relationName;
}
}
$slice = null;
foreach ($sliceRelations as $sliceRelation) {
if ($slice) {
break;
}
/** @var PageSlice $slice */
$slice = $this->owner->data()->$sliceRelation()->find('ID', $id);
}
if (!$slice) {
user_error('No slice found', E_USER_ERROR);
}
return $slice->getController();
} | [
"public",
"function",
"handleSlice",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"id",
"=",
"$",
"this",
"->",
"owner",
"->",
"getRequest",
"(",
")",
"->",
"param",
"(",
"'ID'",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"sliceRelations",
"=",
"array... | Handle the slice
@return bool|PageSliceController | [
"Handle",
"the",
"slice"
] | 5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b | https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/controller/PageSliceControllerExtension.php#L27-L58 | train |
railken/amethyst-common | src/ConfigurableModel.php | ConfigurableModel.ini | public function ini($config)
{
$this->table = Config::get($config.'.table');
$classSchema = Config::get($config.'.schema');
$schema = new $classSchema();
$attributes = collect(($schema)->getAttributes());
$this->internalAttributes = new Bag();
$this->iniFillable($attributes);
$this->iniDates($attributes);
$this->iniCasts($attributes);
} | php | public function ini($config)
{
$this->table = Config::get($config.'.table');
$classSchema = Config::get($config.'.schema');
$schema = new $classSchema();
$attributes = collect(($schema)->getAttributes());
$this->internalAttributes = new Bag();
$this->iniFillable($attributes);
$this->iniDates($attributes);
$this->iniCasts($attributes);
} | [
"public",
"function",
"ini",
"(",
"$",
"config",
")",
"{",
"$",
"this",
"->",
"table",
"=",
"Config",
"::",
"get",
"(",
"$",
"config",
".",
"'.table'",
")",
";",
"$",
"classSchema",
"=",
"Config",
"::",
"get",
"(",
"$",
"config",
".",
"'.schema'",
... | Initialize the model by the configuration.
@param string $config | [
"Initialize",
"the",
"model",
"by",
"the",
"configuration",
"."
] | ee89a31531e267d454352e2caf02fd73be5babfe | https://github.com/railken/amethyst-common/blob/ee89a31531e267d454352e2caf02fd73be5babfe/src/ConfigurableModel.php#L20-L34 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.