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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
railken/amethyst-common | src/ConfigurableModel.php | ConfigurableModel.iniFillable | public function iniFillable(Collection $attributes)
{
$this->fillable = $attributes->filter(function ($attribute) {
return $attribute->getFillable();
})->map(function ($attribute) {
return $attribute->getName();
})->toArray();
} | php | public function iniFillable(Collection $attributes)
{
$this->fillable = $attributes->filter(function ($attribute) {
return $attribute->getFillable();
})->map(function ($attribute) {
return $attribute->getName();
})->toArray();
} | [
"public",
"function",
"iniFillable",
"(",
"Collection",
"$",
"attributes",
")",
"{",
"$",
"this",
"->",
"fillable",
"=",
"$",
"attributes",
"->",
"filter",
"(",
"function",
"(",
"$",
"attribute",
")",
"{",
"return",
"$",
"attribute",
"->",
"getFillable",
"... | Initialize fillable by attributes.
@param Collection $attributes | [
"Initialize",
"fillable",
"by",
"attributes",
"."
] | ee89a31531e267d454352e2caf02fd73be5babfe | https://github.com/railken/amethyst-common/blob/ee89a31531e267d454352e2caf02fd73be5babfe/src/ConfigurableModel.php#L41-L48 | train |
hail-framework/framework | src/Debugger/Bar.php | Bar.addPanel | public function addPanel(Bar\PanelInterface $panel, string $id = null): self
{
if ($id === null) {
$c = 0;
do {
$id = \get_class($panel) . ($c++ ? "-$c" : '');
} while (isset($this->panels[$id]));
}
$this->panels[$id] = $panel;
return $this;
} | php | public function addPanel(Bar\PanelInterface $panel, string $id = null): self
{
if ($id === null) {
$c = 0;
do {
$id = \get_class($panel) . ($c++ ? "-$c" : '');
} while (isset($this->panels[$id]));
}
$this->panels[$id] = $panel;
return $this;
} | [
"public",
"function",
"addPanel",
"(",
"Bar",
"\\",
"PanelInterface",
"$",
"panel",
",",
"string",
"$",
"id",
"=",
"null",
")",
":",
"self",
"{",
"if",
"(",
"$",
"id",
"===",
"null",
")",
"{",
"$",
"c",
"=",
"0",
";",
"do",
"{",
"$",
"id",
"=",... | Add custom panel.
@param Bar\PanelInterface $panel
@param string $id
@return static | [
"Add",
"custom",
"panel",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Bar.php#L35-L46 | train |
hail-framework/framework | src/Debugger/Bar.php | Bar.render | public function render(): void
{
$useSession = $this->useSession && \session_status() === PHP_SESSION_ACTIVE;
$redirectQueue = &$_SESSION['_tracy']['redirect'];
foreach (['bar', 'redirect', 'bluescreen'] as $key) {
$queue = &$_SESSION['_tracy'][$key];
$queue = \array_slice((array) $queue, -10, null, true);
$queue = \array_filter($queue, function ($item) {
return isset($item['time']) && $item['time'] > \time() - 60;
});
}
$rows = [];
if (Helpers::isAjax()) {
if ($useSession) {
$rows[] = (object) ['type' => 'ajax', 'panels' => $this->renderPanels('-ajax')];
$contentId = $_SERVER['HTTP_X_TRACY_AJAX'] . '-ajax';
$_SESSION['_tracy']['bar'][$contentId] = ['content' => self::renderHtmlRows($rows), 'dumps' => Dumper::fetchLiveData(), 'time' => \time()];
}
} elseif (Helpers::isRedirect()) { // redirect
if ($useSession) {
Dumper::fetchLiveData();
Dumper::$livePrefix = \count($redirectQueue) . 'p';
$redirectQueue[] = [
'panels' => $this->renderPanels('-r' . \count($redirectQueue)),
'dumps' => Dumper::fetchLiveData(),
'time' => \time(),
];
}
} elseif (Helpers::isHtmlMode()) {
$rows[] = (object) ['type' => 'main', 'panels' => $this->renderPanels()];
$dumps = Dumper::fetchLiveData();
foreach (\array_reverse((array) $redirectQueue) as $info) {
$rows[] = (object) ['type' => 'redirect', 'panels' => $info['panels']];
$dumps += $info['dumps'];
}
$redirectQueue = null;
$content = self::renderHtmlRows($rows);
if ($this->contentId) {
$_SESSION['_tracy']['bar'][$this->contentId] = ['content' => $content, 'dumps' => $dumps, 'time' => time()];
} else {
$contentId = \substr(\md5(\uniqid('', true)), 0, 10);
$nonce = Helpers::getNonce();
$async = false;
require __DIR__ . '/assets/Bar/loader.phtml';
}
}
} | php | public function render(): void
{
$useSession = $this->useSession && \session_status() === PHP_SESSION_ACTIVE;
$redirectQueue = &$_SESSION['_tracy']['redirect'];
foreach (['bar', 'redirect', 'bluescreen'] as $key) {
$queue = &$_SESSION['_tracy'][$key];
$queue = \array_slice((array) $queue, -10, null, true);
$queue = \array_filter($queue, function ($item) {
return isset($item['time']) && $item['time'] > \time() - 60;
});
}
$rows = [];
if (Helpers::isAjax()) {
if ($useSession) {
$rows[] = (object) ['type' => 'ajax', 'panels' => $this->renderPanels('-ajax')];
$contentId = $_SERVER['HTTP_X_TRACY_AJAX'] . '-ajax';
$_SESSION['_tracy']['bar'][$contentId] = ['content' => self::renderHtmlRows($rows), 'dumps' => Dumper::fetchLiveData(), 'time' => \time()];
}
} elseif (Helpers::isRedirect()) { // redirect
if ($useSession) {
Dumper::fetchLiveData();
Dumper::$livePrefix = \count($redirectQueue) . 'p';
$redirectQueue[] = [
'panels' => $this->renderPanels('-r' . \count($redirectQueue)),
'dumps' => Dumper::fetchLiveData(),
'time' => \time(),
];
}
} elseif (Helpers::isHtmlMode()) {
$rows[] = (object) ['type' => 'main', 'panels' => $this->renderPanels()];
$dumps = Dumper::fetchLiveData();
foreach (\array_reverse((array) $redirectQueue) as $info) {
$rows[] = (object) ['type' => 'redirect', 'panels' => $info['panels']];
$dumps += $info['dumps'];
}
$redirectQueue = null;
$content = self::renderHtmlRows($rows);
if ($this->contentId) {
$_SESSION['_tracy']['bar'][$this->contentId] = ['content' => $content, 'dumps' => $dumps, 'time' => time()];
} else {
$contentId = \substr(\md5(\uniqid('', true)), 0, 10);
$nonce = Helpers::getNonce();
$async = false;
require __DIR__ . '/assets/Bar/loader.phtml';
}
}
} | [
"public",
"function",
"render",
"(",
")",
":",
"void",
"{",
"$",
"useSession",
"=",
"$",
"this",
"->",
"useSession",
"&&",
"\\",
"session_status",
"(",
")",
"===",
"PHP_SESSION_ACTIVE",
";",
"$",
"redirectQueue",
"=",
"&",
"$",
"_SESSION",
"[",
"'_tracy'",... | Renders debug bar.
@return void | [
"Renders",
"debug",
"bar",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Bar.php#L82-L132 | train |
hail-framework/framework | src/Debugger/Bar.php | Bar.dispatchAssets | public function dispatchAssets(): ?ResponseInterface
{
$asset = $_GET['_tracy_bar'] ?? null;
if ($asset === 'js') {
\ob_start();
$this->renderAssets();
$body = \ob_get_clean();
return Factory::response(200, $body, [
'Content-Type' => 'application/javascript',
'Cache-Control' => 'max-age=864000',
]);
}
$this->useSession = \session_status() === PHP_SESSION_ACTIVE;
$headers = [];
if ($this->useSession && Helpers::isAjax()) {
$headers['X-Tracy-Ajax'] = '1'; // session must be already locked
}
if ($this->useSession && $asset && \preg_match('#^content(-ajax)?\.(\w+)$#', $asset, $m)) {
$session = &$_SESSION['_tracy']['bar'][$m[2] . $m[1]];
$headers['Content-Type'] = 'application/javascript';
$headers['Cache-Control'] = 'max-age=60';
\ob_start();
if (!$m[1]) {
$this->renderAssets();
}
if ($session) {
$method = $m[1] ? 'loadAjax' : 'init';
echo "Tracy.Debug.$method(", \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');';
$session = null;
}
$session = &$_SESSION['_tracy']['bluescreen'][$m[2]];
if ($session) {
echo 'Tracy.BlueScreen.loadAjax(', \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');';
$session = null;
}
$body = \ob_get_clean();
return Factory::response(200, $body, $headers);
}
return null;
} | php | public function dispatchAssets(): ?ResponseInterface
{
$asset = $_GET['_tracy_bar'] ?? null;
if ($asset === 'js') {
\ob_start();
$this->renderAssets();
$body = \ob_get_clean();
return Factory::response(200, $body, [
'Content-Type' => 'application/javascript',
'Cache-Control' => 'max-age=864000',
]);
}
$this->useSession = \session_status() === PHP_SESSION_ACTIVE;
$headers = [];
if ($this->useSession && Helpers::isAjax()) {
$headers['X-Tracy-Ajax'] = '1'; // session must be already locked
}
if ($this->useSession && $asset && \preg_match('#^content(-ajax)?\.(\w+)$#', $asset, $m)) {
$session = &$_SESSION['_tracy']['bar'][$m[2] . $m[1]];
$headers['Content-Type'] = 'application/javascript';
$headers['Cache-Control'] = 'max-age=60';
\ob_start();
if (!$m[1]) {
$this->renderAssets();
}
if ($session) {
$method = $m[1] ? 'loadAjax' : 'init';
echo "Tracy.Debug.$method(", \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');';
$session = null;
}
$session = &$_SESSION['_tracy']['bluescreen'][$m[2]];
if ($session) {
echo 'Tracy.BlueScreen.loadAjax(', \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');';
$session = null;
}
$body = \ob_get_clean();
return Factory::response(200, $body, $headers);
}
return null;
} | [
"public",
"function",
"dispatchAssets",
"(",
")",
":",
"?",
"ResponseInterface",
"{",
"$",
"asset",
"=",
"$",
"_GET",
"[",
"'_tracy_bar'",
"]",
"??",
"null",
";",
"if",
"(",
"$",
"asset",
"===",
"'js'",
")",
"{",
"\\",
"ob_start",
"(",
")",
";",
"$",... | Renders debug bar assets.
@return ResponseInterface|null | [
"Renders",
"debug",
"bar",
"assets",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Bar.php#L182-L231 | train |
hail-framework/framework | src/Cache/Simple/AbstractAdapter.php | AbstractAdapter.prefixValue | protected function prefixValue(&$key)
{
if (null === ($version = $this->namespaceVersion)) {
$version = $this->getNamespaceVersion();
}
// namespace#[version]#key
$key = $this->namespace . self::SEPARATOR .
$version . self::SEPARATOR . $key;
} | php | protected function prefixValue(&$key)
{
if (null === ($version = $this->namespaceVersion)) {
$version = $this->getNamespaceVersion();
}
// namespace#[version]#key
$key = $this->namespace . self::SEPARATOR .
$version . self::SEPARATOR . $key;
} | [
"protected",
"function",
"prefixValue",
"(",
"&",
"$",
"key",
")",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"version",
"=",
"$",
"this",
"->",
"namespaceVersion",
")",
")",
"{",
"$",
"version",
"=",
"$",
"this",
"->",
"getNamespaceVersion",
"(",
")",
... | Add namespace prefix on the key.
@param string $key | [
"Add",
"namespace",
"prefix",
"on",
"the",
"key",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L110-L119 | train |
hail-framework/framework | src/Cache/Simple/AbstractAdapter.php | AbstractAdapter.getMultiple | public function getMultiple($keys, $default = null)
{
if (empty($keys)) {
return [];
}
// note: the array_combine() is in place to keep an association between our $keys and the $namespacedKeys
\array_walk($keys, [$this, 'validateKey']);
$prefixed = $keys;
$this->namespace && \array_walk($prefixed, [$this, 'prefixValue']);
$namespacedKeys = \array_combine($keys, $prefixed);
$items = $this->doGetMultiple($namespacedKeys);
$return = [];
// no internal array function supports this sort of mapping: needs to be iterative
// this filters and combines keys in one pass
foreach ($namespacedKeys as $k => $v) {
[$found, $value] = $items[$v] ?? [false, null];
$return[$k] = $found === true ? $value : $default;
}
return $return;
} | php | public function getMultiple($keys, $default = null)
{
if (empty($keys)) {
return [];
}
// note: the array_combine() is in place to keep an association between our $keys and the $namespacedKeys
\array_walk($keys, [$this, 'validateKey']);
$prefixed = $keys;
$this->namespace && \array_walk($prefixed, [$this, 'prefixValue']);
$namespacedKeys = \array_combine($keys, $prefixed);
$items = $this->doGetMultiple($namespacedKeys);
$return = [];
// no internal array function supports this sort of mapping: needs to be iterative
// this filters and combines keys in one pass
foreach ($namespacedKeys as $k => $v) {
[$found, $value] = $items[$v] ?? [false, null];
$return[$k] = $found === true ? $value : $default;
}
return $return;
} | [
"public",
"function",
"getMultiple",
"(",
"$",
"keys",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"keys",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"// note: the array_combine() is in place to keep an association between our $ke... | Returns an associative array of values for keys is found in cache.
@param string[] $keys Array of keys to retrieve from cache
@param mixed $default
@return mixed[] Array of retrieved values, indexed by the specified keys.
Values that couldn't be retrieved are not contained in this array. | [
"Returns",
"an",
"associative",
"array",
"of",
"values",
"for",
"keys",
"is",
"found",
"in",
"cache",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L199-L223 | train |
hail-framework/framework | src/Cache/Simple/AbstractAdapter.php | AbstractAdapter.setMultiple | public function setMultiple($values, $ttl = null)
{
[$ttl, $expireTime] = $this->ttl($ttl);
$namespacedValues = [];
foreach ($values as $key => $value) {
$this->validateKey($key);
$this->namespace && $this->prefixValue($key);
$namespacedValues[$key] = [true, $value, [], $expireTime];
}
return $this->doSetMultiple($namespacedValues, $ttl);
} | php | public function setMultiple($values, $ttl = null)
{
[$ttl, $expireTime] = $this->ttl($ttl);
$namespacedValues = [];
foreach ($values as $key => $value) {
$this->validateKey($key);
$this->namespace && $this->prefixValue($key);
$namespacedValues[$key] = [true, $value, [], $expireTime];
}
return $this->doSetMultiple($namespacedValues, $ttl);
} | [
"public",
"function",
"setMultiple",
"(",
"$",
"values",
",",
"$",
"ttl",
"=",
"null",
")",
"{",
"[",
"$",
"ttl",
",",
"$",
"expireTime",
"]",
"=",
"$",
"this",
"->",
"ttl",
"(",
"$",
"ttl",
")",
";",
"$",
"namespacedValues",
"=",
"[",
"]",
";",
... | Returns a boolean value indicating if the operation succeeded.
@param iterable $values Array of keys and values to save in cache
@param null|int|\DateInterval $ttl The lifetime. If != 0, sets a specific lifetime for these
cache entries (0 => infinite lifeTime).
@return bool TRUE if the operation was successful, FALSE if it wasn't. | [
"Returns",
"a",
"boolean",
"value",
"indicating",
"if",
"the",
"operation",
"succeeded",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L249-L262 | train |
hail-framework/framework | src/Cache/Simple/AbstractAdapter.php | AbstractAdapter.deleteMultiple | public function deleteMultiple($keys)
{
\array_walk($keys, [$this, 'validateKey']);
$this->namespace && \array_walk($keys, [$this, 'prefixValue']);
return $this->doDeleteMultiple($keys);
} | php | public function deleteMultiple($keys)
{
\array_walk($keys, [$this, 'validateKey']);
$this->namespace && \array_walk($keys, [$this, 'prefixValue']);
return $this->doDeleteMultiple($keys);
} | [
"public",
"function",
"deleteMultiple",
"(",
"$",
"keys",
")",
"{",
"\\",
"array_walk",
"(",
"$",
"keys",
",",
"[",
"$",
"this",
",",
"'validateKey'",
"]",
")",
";",
"$",
"this",
"->",
"namespace",
"&&",
"\\",
"array_walk",
"(",
"$",
"keys",
",",
"["... | Deletes several cache entries.
@param string[] $keys Array of keys to delete from cache
@return bool TRUE if the operation was successful, FALSE if it wasn't. | [
"Deletes",
"several",
"cache",
"entries",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L319-L325 | train |
hail-framework/framework | src/Cache/Simple/AbstractAdapter.php | AbstractAdapter.deleteAll | public function deleteAll()
{
if (!$this->namespace) {
return $this->clear();
}
$namespaceCacheKey = $this->getNamespaceCacheKey();
$namespaceVersion = $this->getNamespaceVersion() + 1;
if ($this->doSet($namespaceCacheKey, [true, $namespaceVersion, [], 0])) {
$this->namespaceVersion = $namespaceVersion;
return true;
}
return false;
} | php | public function deleteAll()
{
if (!$this->namespace) {
return $this->clear();
}
$namespaceCacheKey = $this->getNamespaceCacheKey();
$namespaceVersion = $this->getNamespaceVersion() + 1;
if ($this->doSet($namespaceCacheKey, [true, $namespaceVersion, [], 0])) {
$this->namespaceVersion = $namespaceVersion;
return true;
}
return false;
} | [
"public",
"function",
"deleteAll",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"namespace",
")",
"{",
"return",
"$",
"this",
"->",
"clear",
"(",
")",
";",
"}",
"$",
"namespaceCacheKey",
"=",
"$",
"this",
"->",
"getNamespaceCacheKey",
"(",
")",
... | Deletes all cache entries in the current cache namespace.
@return bool TRUE if the cache entries were successfully deleted, FALSE otherwise. | [
"Deletes",
"all",
"cache",
"entries",
"in",
"the",
"current",
"cache",
"namespace",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L342-L358 | train |
hail-framework/framework | src/Cache/Simple/AbstractAdapter.php | AbstractAdapter.doGetMultiple | protected function doGetMultiple(iterable $keys)
{
$return = [];
foreach ($keys as $key) {
$return[$key] = $this->doGet($key);
}
return $return;
} | php | protected function doGetMultiple(iterable $keys)
{
$return = [];
foreach ($keys as $key) {
$return[$key] = $this->doGet($key);
}
return $return;
} | [
"protected",
"function",
"doGetMultiple",
"(",
"iterable",
"$",
"keys",
")",
"{",
"$",
"return",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"$",
"return",
"[",
"$",
"key",
"]",
"=",
"$",
"this",
"->",
"doGet",
"(... | Default implementation of doGetMultiple. Each driver that supports multi-get should owerwrite it.
@param array $keys Array of keys to retrieve from cache
@return array Array of values retrieved for the given keys. | [
"Default",
"implementation",
"of",
"doGetMultiple",
".",
"Each",
"driver",
"that",
"supports",
"multi",
"-",
"get",
"should",
"owerwrite",
"it",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L431-L440 | train |
hail-framework/framework | src/Cache/Simple/AbstractAdapter.php | AbstractAdapter.doDeleteMultiple | protected function doDeleteMultiple(iterable $keys)
{
$success = true;
foreach ($keys as $key) {
if (!$this->doDelete($key)) {
$success = false;
}
}
return $success;
} | php | protected function doDeleteMultiple(iterable $keys)
{
$success = true;
foreach ($keys as $key) {
if (!$this->doDelete($key)) {
$success = false;
}
}
return $success;
} | [
"protected",
"function",
"doDeleteMultiple",
"(",
"iterable",
"$",
"keys",
")",
"{",
"$",
"success",
"=",
"true",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"doDelete",
"(",
"$",
"key",
")",
")"... | Default implementation of doDeleteMultiple. Each driver that supports multi-delete should override it.
@param array $keys Array of keys to delete from cache
@return bool TRUE if the operation was successful, FALSE if it wasn't | [
"Default",
"implementation",
"of",
"doDeleteMultiple",
".",
"Each",
"driver",
"that",
"supports",
"multi",
"-",
"delete",
"should",
"override",
"it",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L449-L460 | train |
hail-framework/framework | src/Debugger/ChromeLogger.php | ChromeLogger.writeToResponse | public function writeToResponse(ResponseInterface $response): ResponseInterface
{
if ($this->entries !== []) {
$value = $this->getHeaderValue();
$this->entries = [];
return $response->withHeader(self::HEADER_NAME, $value);
}
return $response;
} | php | public function writeToResponse(ResponseInterface $response): ResponseInterface
{
if ($this->entries !== []) {
$value = $this->getHeaderValue();
$this->entries = [];
return $response->withHeader(self::HEADER_NAME, $value);
}
return $response;
} | [
"public",
"function",
"writeToResponse",
"(",
"ResponseInterface",
"$",
"response",
")",
":",
"ResponseInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"entries",
"!==",
"[",
"]",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"getHeaderValue",
"(",
")",
... | Adds headers for recorded log-entries in the ChromeLogger format, and clear the internal log-buffer.
(You should call this at the end of the request/response cycle in your PSR-7 project, e.g.
immediately before emitting the Response.)
@param ResponseInterface $response
@return ResponseInterface | [
"Adds",
"headers",
"for",
"recorded",
"log",
"-",
"entries",
"in",
"the",
"ChromeLogger",
"format",
"and",
"clear",
"the",
"internal",
"log",
"-",
"buffer",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L97-L108 | train |
hail-framework/framework | src/Debugger/ChromeLogger.php | ChromeLogger.createData | protected function createData(array $entries): array
{
$rows = [];
foreach ($entries as $entry) {
$rows[] = $this->createEntryData($entry);
}
return [
'version' => self::VERSION,
'columns' => [self::COLUMN_LOG, self::COLUMN_TYPE, self::COLUMN_BACKTRACE],
'rows' => $rows,
];
} | php | protected function createData(array $entries): array
{
$rows = [];
foreach ($entries as $entry) {
$rows[] = $this->createEntryData($entry);
}
return [
'version' => self::VERSION,
'columns' => [self::COLUMN_LOG, self::COLUMN_TYPE, self::COLUMN_BACKTRACE],
'rows' => $rows,
];
} | [
"protected",
"function",
"createData",
"(",
"array",
"$",
"entries",
")",
":",
"array",
"{",
"$",
"rows",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"entries",
"as",
"$",
"entry",
")",
"{",
"$",
"rows",
"[",
"]",
"=",
"$",
"this",
"->",
"createEntryD... | Internally builds the ChromeLogger-compatible data-structure from internal log-entries.
@param array[][] $entries
@return array | [
"Internally",
"builds",
"the",
"ChromeLogger",
"-",
"compatible",
"data",
"-",
"structure",
"from",
"internal",
"log",
"-",
"entries",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L186-L199 | train |
hail-framework/framework | src/Debugger/ChromeLogger.php | ChromeLogger.createEntryData | protected function createEntryData(array $entry): array
{
// NOTE: "log" level type is deliberately omitted from the following map, since
// it's the default entry-type in ChromeLogger, and can be omitted.
static $LEVELS = [
LogLevel::DEBUG => self::LOG,
LogLevel::INFO => self::INFO,
LogLevel::NOTICE => self::INFO,
LogLevel::WARNING => self::WARN,
LogLevel::ERROR => self::ERROR,
LogLevel::CRITICAL => self::ERROR,
LogLevel::ALERT => self::ERROR,
LogLevel::EMERGENCY => self::ERROR,
];
$row = [];
[$level, $message, $context] = $entry;
$data = [
\str_replace('%', '%%', Dumper::interpolate($message, $context)),
];
if (\count($context)) {
$context = $this->sanitize($context);
$data = \array_merge($data, $context);
}
$row[] = $data;
$row[] = $LEVELS[$level] ?? self::LOG;
if (isset($context['exception'])) {
// NOTE: per PSR-3, this reserved key could be anything, but if it is an Exception, we
// can use that Exception to obtain a stack-trace for output in ChromeLogger.
$exception = $context['exception'];
if ($exception instanceof \Throwable) {
$row[] = $exception->__toString();
}
}
// Optimization: ChromeLogger defaults to "log" if no entry-type is specified.
if ($row[1] === self::LOG) {
if (\count($row) === 2) {
unset($row[1]);
} else {
$row[1] = '';
}
}
return $row;
} | php | protected function createEntryData(array $entry): array
{
// NOTE: "log" level type is deliberately omitted from the following map, since
// it's the default entry-type in ChromeLogger, and can be omitted.
static $LEVELS = [
LogLevel::DEBUG => self::LOG,
LogLevel::INFO => self::INFO,
LogLevel::NOTICE => self::INFO,
LogLevel::WARNING => self::WARN,
LogLevel::ERROR => self::ERROR,
LogLevel::CRITICAL => self::ERROR,
LogLevel::ALERT => self::ERROR,
LogLevel::EMERGENCY => self::ERROR,
];
$row = [];
[$level, $message, $context] = $entry;
$data = [
\str_replace('%', '%%', Dumper::interpolate($message, $context)),
];
if (\count($context)) {
$context = $this->sanitize($context);
$data = \array_merge($data, $context);
}
$row[] = $data;
$row[] = $LEVELS[$level] ?? self::LOG;
if (isset($context['exception'])) {
// NOTE: per PSR-3, this reserved key could be anything, but if it is an Exception, we
// can use that Exception to obtain a stack-trace for output in ChromeLogger.
$exception = $context['exception'];
if ($exception instanceof \Throwable) {
$row[] = $exception->__toString();
}
}
// Optimization: ChromeLogger defaults to "log" if no entry-type is specified.
if ($row[1] === self::LOG) {
if (\count($row) === 2) {
unset($row[1]);
} else {
$row[1] = '';
}
}
return $row;
} | [
"protected",
"function",
"createEntryData",
"(",
"array",
"$",
"entry",
")",
":",
"array",
"{",
"// NOTE: \"log\" level type is deliberately omitted from the following map, since",
"// it's the default entry-type in ChromeLogger, and can be omitted.",
"static",
"$",
"LEVELS",
"... | Encode an individual LogEntry in ChromeLogger-compatible format
@param array $entry
@return array log entry in ChromeLogger row-format | [
"Encode",
"an",
"individual",
"LogEntry",
"in",
"ChromeLogger",
"-",
"compatible",
"format"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L208-L262 | train |
hail-framework/framework | src/Debugger/ChromeLogger.php | ChromeLogger.sanitize | protected function sanitize($data, array &$processed = [])
{
if (\is_array($data)) {
/**
* @var array $data
*/
foreach ($data as $name => $value) {
$data[$name] = $this->sanitize($value, $processed);
}
return $data;
}
if (\is_object($data)) {
/**
* @var object $data
*/
$class_name = \get_class($data);
$hash = \spl_object_hash($data);
if (isset($processed[$hash])) {
// NOTE: duplicate objects (circular references) are omitted to prevent recursion.
return [self::CLASS_NAME => $class_name];
}
$processed[$hash] = true;
if ($data instanceof \JsonSerializable) {
// NOTE: this doesn't serialize to JSON, it only marshalls to a JSON-compatible data-structure
$data = $this->sanitize($data->jsonSerialize(), $processed);
} elseif ($data instanceof \DateTimeInterface) {
$data = $this->extractDateTimeProperties($data);
} elseif ($data instanceof \Throwable) {
$data = $this->extractExceptionProperties($data);
} else {
$data = $this->sanitize($this->extractObjectProperties($data), $processed);
}
return \array_merge([self::CLASS_NAME => $class_name], $data);
}
if (\is_scalar($data)) {
return $data; // bool, int, float
}
if (\is_resource($data)) {
$resource = \explode('#', (string) $data);
return [
self::CLASS_NAME => 'resource<' . \get_resource_type($data) . '>',
'id' => \array_pop($resource),
];
}
return null; // omit any other unsupported types (e.g. resource handles)
} | php | protected function sanitize($data, array &$processed = [])
{
if (\is_array($data)) {
/**
* @var array $data
*/
foreach ($data as $name => $value) {
$data[$name] = $this->sanitize($value, $processed);
}
return $data;
}
if (\is_object($data)) {
/**
* @var object $data
*/
$class_name = \get_class($data);
$hash = \spl_object_hash($data);
if (isset($processed[$hash])) {
// NOTE: duplicate objects (circular references) are omitted to prevent recursion.
return [self::CLASS_NAME => $class_name];
}
$processed[$hash] = true;
if ($data instanceof \JsonSerializable) {
// NOTE: this doesn't serialize to JSON, it only marshalls to a JSON-compatible data-structure
$data = $this->sanitize($data->jsonSerialize(), $processed);
} elseif ($data instanceof \DateTimeInterface) {
$data = $this->extractDateTimeProperties($data);
} elseif ($data instanceof \Throwable) {
$data = $this->extractExceptionProperties($data);
} else {
$data = $this->sanitize($this->extractObjectProperties($data), $processed);
}
return \array_merge([self::CLASS_NAME => $class_name], $data);
}
if (\is_scalar($data)) {
return $data; // bool, int, float
}
if (\is_resource($data)) {
$resource = \explode('#', (string) $data);
return [
self::CLASS_NAME => 'resource<' . \get_resource_type($data) . '>',
'id' => \array_pop($resource),
];
}
return null; // omit any other unsupported types (e.g. resource handles)
} | [
"protected",
"function",
"sanitize",
"(",
"$",
"data",
",",
"array",
"&",
"$",
"processed",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"/**\n * @var array $data\n */",
"foreach",
"(",
"$",
... | Internally marshall and sanitize context values, producing a JSON-compatible data-structure.
@param mixed $data any PHP object, array or value
@param true[] $processed map where SPL object-hash => TRUE (eliminates duplicate objects from data-structures)
@return mixed marshalled and sanitized context | [
"Internally",
"marshall",
"and",
"sanitize",
"context",
"values",
"producing",
"a",
"JSON",
"-",
"compatible",
"data",
"-",
"structure",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L272-L328 | train |
hail-framework/framework | src/Image/Commands/TextCommand.php | TextCommand.execute | public function execute($image)
{
$text = $this->argument(0)->required()->value();
$x = $this->argument(1)->type('numeric')->value(0);
$y = $this->argument(2)->type('numeric')->value(0);
$callback = $this->argument(3)->type('closure')->value();
$namespace = $image->getDriver()->getNamespace();
$fontclassname = "\{$namespace}\Font";
$font = new $fontclassname($text);
if ($callback instanceof Closure) {
$callback($font);
}
$font->applyToImage($image, $x, $y);
return true;
} | php | public function execute($image)
{
$text = $this->argument(0)->required()->value();
$x = $this->argument(1)->type('numeric')->value(0);
$y = $this->argument(2)->type('numeric')->value(0);
$callback = $this->argument(3)->type('closure')->value();
$namespace = $image->getDriver()->getNamespace();
$fontclassname = "\{$namespace}\Font";
$font = new $fontclassname($text);
if ($callback instanceof Closure) {
$callback($font);
}
$font->applyToImage($image, $x, $y);
return true;
} | [
"public",
"function",
"execute",
"(",
"$",
"image",
")",
"{",
"$",
"text",
"=",
"$",
"this",
"->",
"argument",
"(",
"0",
")",
"->",
"required",
"(",
")",
"->",
"value",
"(",
")",
";",
"$",
"x",
"=",
"$",
"this",
"->",
"argument",
"(",
"1",
")",... | Write text on given image
@param \Hail\Image\Image $image
@return bool | [
"Write",
"text",
"on",
"given",
"image"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Commands/TextCommand.php#L16-L35 | train |
DoSomething/gateway | src/AuthorizesWithApiKey.php | AuthorizesWithApiKey.getAuthorizationHeader | protected function getAuthorizationHeader()
{
if (empty($this->apiKeyHeader) || empty($this->apiKey)) {
throw new \Exception('API key is not set.');
}
return [$this->apiKeyHeader => $this->apiKey];
} | php | protected function getAuthorizationHeader()
{
if (empty($this->apiKeyHeader) || empty($this->apiKey)) {
throw new \Exception('API key is not set.');
}
return [$this->apiKeyHeader => $this->apiKey];
} | [
"protected",
"function",
"getAuthorizationHeader",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"apiKeyHeader",
")",
"||",
"empty",
"(",
"$",
"this",
"->",
"apiKey",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'API key is not set.... | Get the authorization header for a request
@return null|array
@throws \Exception | [
"Get",
"the",
"authorization",
"header",
"for",
"a",
"request"
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithApiKey.php#L34-L41 | train |
htmlburger/wpemerge-cli | src/Presets/FrontEndPresetTrait.php | FrontEndPresetTrait.installNodePackage | protected function installNodePackage( $directory, OutputInterface $output, $package, $version = null, $dev = false ) {
$package_manager = new Proxy();
if ( $package_manager->installed( $directory, $package ) ) {
throw new RuntimeException( 'Package is already installed.' );
}
$package_manager->install( $directory, $output, $package, $version, $dev );
} | php | protected function installNodePackage( $directory, OutputInterface $output, $package, $version = null, $dev = false ) {
$package_manager = new Proxy();
if ( $package_manager->installed( $directory, $package ) ) {
throw new RuntimeException( 'Package is already installed.' );
}
$package_manager->install( $directory, $output, $package, $version, $dev );
} | [
"protected",
"function",
"installNodePackage",
"(",
"$",
"directory",
",",
"OutputInterface",
"$",
"output",
",",
"$",
"package",
",",
"$",
"version",
"=",
"null",
",",
"$",
"dev",
"=",
"false",
")",
"{",
"$",
"package_manager",
"=",
"new",
"Proxy",
"(",
... | Install a node package.
@param string $directory
@param OutputInterface $output
@param string $package
@param string|null $version
@param boolean $dev
@return void | [
"Install",
"a",
"node",
"package",
"."
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/FrontEndPresetTrait.php#L22-L30 | train |
htmlburger/wpemerge-cli | src/Presets/FrontEndPresetTrait.php | FrontEndPresetTrait.addJsVendorImport | protected function addJsVendorImport( $directory, $import ) {
$filepath = $this->path( $directory, 'resources', 'scripts', 'theme', 'vendor.js' );
$statement = "import '$import';";
$this->appendUniqueStatement( $filepath, $statement );
} | php | protected function addJsVendorImport( $directory, $import ) {
$filepath = $this->path( $directory, 'resources', 'scripts', 'theme', 'vendor.js' );
$statement = "import '$import';";
$this->appendUniqueStatement( $filepath, $statement );
} | [
"protected",
"function",
"addJsVendorImport",
"(",
"$",
"directory",
",",
"$",
"import",
")",
"{",
"$",
"filepath",
"=",
"$",
"this",
"->",
"path",
"(",
"$",
"directory",
",",
"'resources'",
",",
"'scripts'",
",",
"'theme'",
",",
"'vendor.js'",
")",
";",
... | Add an import statement to the vendor.js file.
@param string $directory
@param string $import
@return void | [
"Add",
"an",
"import",
"statement",
"to",
"the",
"vendor",
".",
"js",
"file",
"."
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/FrontEndPresetTrait.php#L53-L58 | train |
Kajna/K-Core | Core/Util/Util.php | Util.base | public static function base($path = '')
{
// Check for cached version of base path
if (null !== self::$base) {
return self::$base . $path;
}
if (isset($_SERVER['HTTP_HOST'])) {
$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$base_url .= '://' . $_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
self::$base = $base_url;
return $base_url . $path;
}
return '';
} | php | public static function base($path = '')
{
// Check for cached version of base path
if (null !== self::$base) {
return self::$base . $path;
}
if (isset($_SERVER['HTTP_HOST'])) {
$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$base_url .= '://' . $_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
self::$base = $base_url;
return $base_url . $path;
}
return '';
} | [
"public",
"static",
"function",
"base",
"(",
"$",
"path",
"=",
"''",
")",
"{",
"// Check for cached version of base path",
"if",
"(",
"null",
"!==",
"self",
"::",
"$",
"base",
")",
"{",
"return",
"self",
"::",
"$",
"base",
".",
"$",
"path",
";",
"}",
"... | Get site base url.
@param string $path
@return string | [
"Get",
"site",
"base",
"url",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Util/Util.php#L29-L45 | train |
Kajna/K-Core | Core/Http/Response.php | Response.setStatusCode | public function setStatusCode($code, $reasonPhrase = null)
{
$this->statusCode = $code;
$this->reasonPhrase = $reasonPhrase;
return $this;
} | php | public function setStatusCode($code, $reasonPhrase = null)
{
$this->statusCode = $code;
$this->reasonPhrase = $reasonPhrase;
return $this;
} | [
"public",
"function",
"setStatusCode",
"(",
"$",
"code",
",",
"$",
"reasonPhrase",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"statusCode",
"=",
"$",
"code",
";",
"$",
"this",
"->",
"reasonPhrase",
"=",
"$",
"reasonPhrase",
";",
"return",
"$",
"this",
"... | Set the response Status-Code
@param integer $code The 3-digit integer result code to set.
@param null|string $reasonPhrase The reason phrase to use with the
provided status code; if none is provided default one associated with code will be used
@return self | [
"Set",
"the",
"response",
"Status",
"-",
"Code"
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Http/Response.php#L178-L183 | train |
Kajna/K-Core | Core/Http/Response.php | Response.send | public function send()
{
// Check if headers are sent already.
if (headers_sent() === false) {
// Determine reason phrase
if ($this->reasonPhrase === null) {
$this->reasonPhrase = self::$messages[$this->statusCode];
}
// Send status code.
header(sprintf('%s %s', $this->protocolVersion, $this->reasonPhrase), true, $this->statusCode);
// Send headers.
foreach ($this->headers as $header => $value) {
header(sprintf('%s: %s', $header, $value), true, $this->statusCode);
}
// Send cookies.
foreach ($this->cookies as $cookie) {
setcookie($cookie['name'], $cookie['value'], $cookie['expire'],
$cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
}
// Send body.
echo $this->body;
}
return $this;
} | php | public function send()
{
// Check if headers are sent already.
if (headers_sent() === false) {
// Determine reason phrase
if ($this->reasonPhrase === null) {
$this->reasonPhrase = self::$messages[$this->statusCode];
}
// Send status code.
header(sprintf('%s %s', $this->protocolVersion, $this->reasonPhrase), true, $this->statusCode);
// Send headers.
foreach ($this->headers as $header => $value) {
header(sprintf('%s: %s', $header, $value), true, $this->statusCode);
}
// Send cookies.
foreach ($this->cookies as $cookie) {
setcookie($cookie['name'], $cookie['value'], $cookie['expire'],
$cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
}
// Send body.
echo $this->body;
}
return $this;
} | [
"public",
"function",
"send",
"(",
")",
"{",
"// Check if headers are sent already.",
"if",
"(",
"headers_sent",
"(",
")",
"===",
"false",
")",
"{",
"// Determine reason phrase",
"if",
"(",
"$",
"this",
"->",
"reasonPhrase",
"===",
"null",
")",
"{",
"$",
"this... | Send final status, headers, cookies and body.
@return self | [
"Send",
"final",
"status",
"headers",
"cookies",
"and",
"body",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Http/Response.php#L268-L297 | train |
hail-framework/framework | src/Database/Event/Event.php | Event.dump | public function dump($result = null)
{
static $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT';
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';
// insert new lines
$sql = " $result ";
$sql = \preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i", "\n\$1", $sql);
// reduce spaces
$sql = \preg_replace('#[ \t]{2,}#', ' ', $sql);
$sql = \wordwrap($sql, 100);
$sql = \preg_replace("#([ \t]*\r?\n){2,}#", "\n", $sql);
// syntax highlight
$highlighter = "#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])($keywords1)(?=[\\s,)])|(?<=[\\s,(=])($keywords2)(?=[\\s,)=])#is";
$sql = \htmlspecialchars($sql);
$sql = \preg_replace_callback($highlighter, function ($m) {
if (!empty($m[1])) { // comment
return '<em style="color:gray">' . $m[1] . '</em>';
}
if (!empty($m[2])) { // error
return '<strong style="color:red">' . $m[2] . '</strong>';
}
if (!empty($m[3])) { // most important keywords
return '<strong style="color:blue">' . $m[3] . '</strong>';
}
if (!empty($m[4])) { // other keywords
return '<strong style="color:green">' . $m[4] . '</strong>';
}
return '';
}, $sql);
return '<pre class="dump">' . \trim($sql) . "</pre>\n\n";
} | php | public function dump($result = null)
{
static $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT';
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';
// insert new lines
$sql = " $result ";
$sql = \preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i", "\n\$1", $sql);
// reduce spaces
$sql = \preg_replace('#[ \t]{2,}#', ' ', $sql);
$sql = \wordwrap($sql, 100);
$sql = \preg_replace("#([ \t]*\r?\n){2,}#", "\n", $sql);
// syntax highlight
$highlighter = "#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])($keywords1)(?=[\\s,)])|(?<=[\\s,(=])($keywords2)(?=[\\s,)=])#is";
$sql = \htmlspecialchars($sql);
$sql = \preg_replace_callback($highlighter, function ($m) {
if (!empty($m[1])) { // comment
return '<em style="color:gray">' . $m[1] . '</em>';
}
if (!empty($m[2])) { // error
return '<strong style="color:red">' . $m[2] . '</strong>';
}
if (!empty($m[3])) { // most important keywords
return '<strong style="color:blue">' . $m[3] . '</strong>';
}
if (!empty($m[4])) { // other keywords
return '<strong style="color:green">' . $m[4] . '</strong>';
}
return '';
}, $sql);
return '<pre class="dump">' . \trim($sql) . "</pre>\n\n";
} | [
"public",
"function",
"dump",
"(",
"$",
"result",
"=",
"null",
")",
"{",
"static",
"$",
"keywords1",
"=",
"'SELECT|(?:ON\\s+DUPLICATE\\s+KEY)?UPDATE|INSERT(?:\\s+INTO)?|REPLACE(?:\\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\\s+BY|ORDER\\s+BY|LIMIT|OFFSET|FETCH\\s+NEXT|SET|VALUES|... | Prints out a syntax highlighted version of the SQL command or Result.
@param string $result
@return string | [
"Prints",
"out",
"a",
"syntax",
"highlighted",
"version",
"of",
"the",
"SQL",
"command",
"or",
"Result",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Event/Event.php#L243-L280 | train |
hail-framework/framework | src/Console/Command.php | Command.getApplication | public function getApplication(): ?Application
{
if ($this->application) {
return $this->application;
}
if ($p = $this->parent) {
return $this->application = $p->getApplication();
}
return null;
} | php | public function getApplication(): ?Application
{
if ($this->application) {
return $this->application;
}
if ($p = $this->parent) {
return $this->application = $p->getApplication();
}
return null;
} | [
"public",
"function",
"getApplication",
"(",
")",
":",
"?",
"Application",
"{",
"if",
"(",
"$",
"this",
"->",
"application",
")",
"{",
"return",
"$",
"this",
"->",
"application",
";",
"}",
"if",
"(",
"$",
"p",
"=",
"$",
"this",
"->",
"parent",
")",
... | Get the main application object from parents
@return Application|null | [
"Get",
"the",
"main",
"application",
"object",
"from",
"parents"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Command.php#L51-L62 | train |
hail-framework/framework | src/Console/Command.php | Command.addExtension | public function addExtension(AbstractExtension $extension)
{
if (!$extension->isAvailable()) {
throw new ExtensionException('Extension ' . get_class($extension) . ' is not available', $extension);
}
$this->extensions[] = $extension->bind($this);
} | php | public function addExtension(AbstractExtension $extension)
{
if (!$extension->isAvailable()) {
throw new ExtensionException('Extension ' . get_class($extension) . ' is not available', $extension);
}
$this->extensions[] = $extension->bind($this);
} | [
"public",
"function",
"addExtension",
"(",
"AbstractExtension",
"$",
"extension",
")",
"{",
"if",
"(",
"!",
"$",
"extension",
"->",
"isAvailable",
"(",
")",
")",
"{",
"throw",
"new",
"ExtensionException",
"(",
"'Extension '",
".",
"get_class",
"(",
"$",
"ext... | Register and bind the extension
@param AbstractExtension $extension
@throws ExtensionException | [
"Register",
"and",
"bind",
"the",
"extension"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Command.php#L76-L83 | train |
hail-framework/framework | src/Console/Command.php | Command.extension | public function extension($extension)
{
if (is_string($extension)) {
$extension = new $extension;
} elseif (!$extension instanceof AbstractExtension) {
throw new \LogicException('Not an extension object or an extension class name.');
}
$this->addExtension($extension);
} | php | public function extension($extension)
{
if (is_string($extension)) {
$extension = new $extension;
} elseif (!$extension instanceof AbstractExtension) {
throw new \LogicException('Not an extension object or an extension class name.');
}
$this->addExtension($extension);
} | [
"public",
"function",
"extension",
"(",
"$",
"extension",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"extension",
")",
")",
"{",
"$",
"extension",
"=",
"new",
"$",
"extension",
";",
"}",
"elseif",
"(",
"!",
"$",
"extension",
"instanceof",
"AbstractExten... | method `extension` is an alias of addExtension
@param AbstractExtension|string $extension
@throws ExtensionException | [
"method",
"extension",
"is",
"an",
"alias",
"of",
"addExtension"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Command.php#L92-L101 | train |
hail-framework/framework | src/Console/Component/Prompter.php | Prompter.ask | public function ask(string $prompt, array $validAnswers = [], string $default = null)
{
if ($validAnswers) {
$answers = [];
foreach ($validAnswers as $v) {
if ($default && $default === $v) {
$answers[] = '[' . $v . ']';
} else {
$answers[] = $v;
}
}
$prompt .= ' (' . implode('/', $answers) . ')';
}
$prompt .= ' ';
if ($this->style) {
echo $this->formatter->getStartMark($this->style);
}
$answer = null;
while (true) {
$answer = trim($this->console->readLine($prompt));
if ($validAnswers) {
if (in_array($answer, $validAnswers, true)) {
break;
}
if (trim($answer) === '' && $default) {
$answer = $default;
break;
}
continue;
}
break;
}
if ($this->style) {
echo $this->formatter->getClearMark();
}
return $answer;
} | php | public function ask(string $prompt, array $validAnswers = [], string $default = null)
{
if ($validAnswers) {
$answers = [];
foreach ($validAnswers as $v) {
if ($default && $default === $v) {
$answers[] = '[' . $v . ']';
} else {
$answers[] = $v;
}
}
$prompt .= ' (' . implode('/', $answers) . ')';
}
$prompt .= ' ';
if ($this->style) {
echo $this->formatter->getStartMark($this->style);
}
$answer = null;
while (true) {
$answer = trim($this->console->readLine($prompt));
if ($validAnswers) {
if (in_array($answer, $validAnswers, true)) {
break;
}
if (trim($answer) === '' && $default) {
$answer = $default;
break;
}
continue;
}
break;
}
if ($this->style) {
echo $this->formatter->getClearMark();
}
return $answer;
} | [
"public",
"function",
"ask",
"(",
"string",
"$",
"prompt",
",",
"array",
"$",
"validAnswers",
"=",
"[",
"]",
",",
"string",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"validAnswers",
")",
"{",
"$",
"answers",
"=",
"[",
"]",
";",
"foreac... | Show prompt with message, you can provide valid options
for the simple validation.
@param string $prompt
@param array $validAnswers an array of valid values (optional)
@param string|null $default
@return null|string | [
"Show",
"prompt",
"with",
"message",
"you",
"can",
"provide",
"valid",
"options",
"for",
"the",
"simple",
"validation",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Prompter.php#L72-L114 | train |
hail-framework/framework | src/Console/Component/Prompter.php | Prompter.password | public function password(string $prompt)
{
if ($this->style) {
echo $this->formatter->getStartMark($this->style);
}
$result = $this->console->readPassword($prompt);
if ($this->style) {
echo $this->formatter->getClearMark();
}
return $result;
} | php | public function password(string $prompt)
{
if ($this->style) {
echo $this->formatter->getStartMark($this->style);
}
$result = $this->console->readPassword($prompt);
if ($this->style) {
echo $this->formatter->getClearMark();
}
return $result;
} | [
"public",
"function",
"password",
"(",
"string",
"$",
"prompt",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"style",
")",
"{",
"echo",
"$",
"this",
"->",
"formatter",
"->",
"getStartMark",
"(",
"$",
"this",
"->",
"style",
")",
";",
"}",
"$",
"result",
... | Show password prompt with a message.
@param string $prompt
@return mixed|string | [
"Show",
"password",
"prompt",
"with",
"a",
"message",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Prompter.php#L123-L136 | train |
hail-framework/framework | src/Console/Component/Prompter.php | Prompter.choose | public function choose(string $prompt, array $choices)
{
echo "$prompt: \n";
$choicesMap = [];
$i = 0;
if (Arrays::isAssoc($choices)) {
foreach ($choices as $choice => $value) {
$choicesMap[++$i] = $value;
echo "\t$i: " . $choice . ' => ' . $value . "\n";
}
} else {
//is sequential
foreach ($choices as $choice) {
$choicesMap[++$i] = $choice;
echo "\t$i: $choice\n";
}
}
if ($this->style) {
echo $this->formatter->getStartMark($this->style);
}
$completionItems = array_keys($choicesMap);
$choosePrompt = "Please Choose 1-$i > ";
if (ReadlineConsole::isAvailable()) {
readline_completion_function(function () use ($completionItems) {
return $completionItems;
});
}
while (true) {
$answer = (int) trim($this->console->readLine($choosePrompt));
if (isset($choicesMap[$answer])) {
if ($this->style) {
echo $this->formatter->getClearMark();
}
return $choicesMap[$answer];
}
}
} | php | public function choose(string $prompt, array $choices)
{
echo "$prompt: \n";
$choicesMap = [];
$i = 0;
if (Arrays::isAssoc($choices)) {
foreach ($choices as $choice => $value) {
$choicesMap[++$i] = $value;
echo "\t$i: " . $choice . ' => ' . $value . "\n";
}
} else {
//is sequential
foreach ($choices as $choice) {
$choicesMap[++$i] = $choice;
echo "\t$i: $choice\n";
}
}
if ($this->style) {
echo $this->formatter->getStartMark($this->style);
}
$completionItems = array_keys($choicesMap);
$choosePrompt = "Please Choose 1-$i > ";
if (ReadlineConsole::isAvailable()) {
readline_completion_function(function () use ($completionItems) {
return $completionItems;
});
}
while (true) {
$answer = (int) trim($this->console->readLine($choosePrompt));
if (isset($choicesMap[$answer])) {
if ($this->style) {
echo $this->formatter->getClearMark();
}
return $choicesMap[$answer];
}
}
} | [
"public",
"function",
"choose",
"(",
"string",
"$",
"prompt",
",",
"array",
"$",
"choices",
")",
"{",
"echo",
"\"$prompt: \\n\"",
";",
"$",
"choicesMap",
"=",
"[",
"]",
";",
"$",
"i",
"=",
"0",
";",
"if",
"(",
"Arrays",
"::",
"isAssoc",
"(",
"$",
"... | Provide a simple console menu for choices,
which gives values an index number for user to choose items.
@code
$val = $app->choose('Your versions' , array(
'php-5.4.0' => '5.4.0',
'php-5.4.1' => '5.4.1',
'system' => '5.3.0',
));
var_dump($val);
@code
@param string $prompt Prompt message
@param array $choices
@return mixed value | [
"Provide",
"a",
"simple",
"console",
"menu",
"for",
"choices",
"which",
"gives",
"values",
"an",
"index",
"number",
"for",
"user",
"to",
"choose",
"items",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Prompter.php#L158-L202 | train |
htmlburger/wpemerge-cli | src/Templates/Template.php | Template.storeOnDisc | public function storeOnDisc( $name, $namespace, $contents, $directory ) {
$filepath = implode( DIRECTORY_SEPARATOR, [$directory, 'app', 'src', $namespace, $name . '.php'] );
if ( file_exists( $filepath ) ) {
throw new InvalidArgumentException( 'Class file already exists (' . $filepath . ')' );
}
file_put_contents( $filepath, $contents );
return $filepath;
} | php | public function storeOnDisc( $name, $namespace, $contents, $directory ) {
$filepath = implode( DIRECTORY_SEPARATOR, [$directory, 'app', 'src', $namespace, $name . '.php'] );
if ( file_exists( $filepath ) ) {
throw new InvalidArgumentException( 'Class file already exists (' . $filepath . ')' );
}
file_put_contents( $filepath, $contents );
return $filepath;
} | [
"public",
"function",
"storeOnDisc",
"(",
"$",
"name",
",",
"$",
"namespace",
",",
"$",
"contents",
",",
"$",
"directory",
")",
"{",
"$",
"filepath",
"=",
"implode",
"(",
"DIRECTORY_SEPARATOR",
",",
"[",
"$",
"directory",
",",
"'app'",
",",
"'src'",
",",... | Store file on disc returning the filepath
@param string $name
@param string $namespace
@param string $contents
@param string $directory
@return string | [
"Store",
"file",
"on",
"disc",
"returning",
"the",
"filepath"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Templates/Template.php#L26-L36 | train |
hail-framework/framework | src/Filesystem/Adapter/Ftp.php | Ftp.disconnect | public function disconnect()
{
if (\is_resource($this->connection)) {
\ftp_close($this->connection);
}
$this->connection = null;
} | php | public function disconnect()
{
if (\is_resource($this->connection)) {
\ftp_close($this->connection);
}
$this->connection = null;
} | [
"public",
"function",
"disconnect",
"(",
")",
"{",
"if",
"(",
"\\",
"is_resource",
"(",
"$",
"this",
"->",
"connection",
")",
")",
"{",
"\\",
"ftp_close",
"(",
"$",
"this",
"->",
"connection",
")",
";",
"}",
"$",
"this",
"->",
"connection",
"=",
"nul... | Disconnect from the FTP server. | [
"Disconnect",
"from",
"the",
"FTP",
"server",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Ftp.php#L221-L228 | train |
hail-framework/framework | src/Filesystem/Adapter/Ftp.php | Ftp.isConnected | public function isConnected()
{
try {
return \is_resource($this->connection) && \ftp_rawlist($this->connection, $this->getRoot()) !== false;
} catch (\ErrorException $e) {
if (\strpos($e->getMessage(), 'ftp_rawlist') === false) {
throw $e;
}
return false;
}
} | php | public function isConnected()
{
try {
return \is_resource($this->connection) && \ftp_rawlist($this->connection, $this->getRoot()) !== false;
} catch (\ErrorException $e) {
if (\strpos($e->getMessage(), 'ftp_rawlist') === false) {
throw $e;
}
return false;
}
} | [
"public",
"function",
"isConnected",
"(",
")",
"{",
"try",
"{",
"return",
"\\",
"is_resource",
"(",
"$",
"this",
"->",
"connection",
")",
"&&",
"\\",
"ftp_rawlist",
"(",
"$",
"this",
"->",
"connection",
",",
"$",
"this",
"->",
"getRoot",
"(",
")",
")",... | Check if the connection is open.
@return bool | [
"Check",
"if",
"the",
"connection",
"is",
"open",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Ftp.php#L528-L539 | train |
cfxmarkets/php-public-models | src/Brokerage/AclEntriesCollection.php | AclEntriesCollection.actorHasPermissionsOnTarget | public function actorHasPermissionsOnTarget(string $actorType, string $actorId, string $targetType, string $targetId, int $permissions)
{
foreach($this->elements as $k => $v) {
if (
$v->getActor()->getResourceType() === $actorType &&
$v->getActor()->getId() === $actorId &&
$v->getTarget()->getResourceType() === $targetType &&
$v->getTarget()->getId() === $targetId &&
$v->hasPermissions($permissions)
) {
return true;
}
}
return false;
} | php | public function actorHasPermissionsOnTarget(string $actorType, string $actorId, string $targetType, string $targetId, int $permissions)
{
foreach($this->elements as $k => $v) {
if (
$v->getActor()->getResourceType() === $actorType &&
$v->getActor()->getId() === $actorId &&
$v->getTarget()->getResourceType() === $targetType &&
$v->getTarget()->getId() === $targetId &&
$v->hasPermissions($permissions)
) {
return true;
}
}
return false;
} | [
"public",
"function",
"actorHasPermissionsOnTarget",
"(",
"string",
"$",
"actorType",
",",
"string",
"$",
"actorId",
",",
"string",
"$",
"targetType",
",",
"string",
"$",
"targetId",
",",
"int",
"$",
"permissions",
")",
"{",
"foreach",
"(",
"$",
"this",
"->"... | Searches all available AclEntries in collection for one that matches the given actor and target and then checks permissions
@param string $actorType
@param string $actorId
@param string $targetType
@param string $targetId
@param int $permissions A bitmask defining the permissions to check | [
"Searches",
"all",
"available",
"AclEntries",
"in",
"collection",
"for",
"one",
"that",
"matches",
"the",
"given",
"actor",
"and",
"target",
"and",
"then",
"checks",
"permissions"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/Brokerage/AclEntriesCollection.php#L15-L30 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.validateType | protected function validateType($field, $val, $type, $required = true)
{
if ($val !== null) {
if ($type === 'string') {
$result = is_string($val);
} elseif ($type === 'non-numeric string') {
$result = is_string($val) && !is_numeric($val);
} elseif ($type === 'int' || $type === 'integer') {
$result = is_int($val);
} elseif ($type === "numeric") {
$result = is_numeric($val);
} elseif ($type === 'non-string numeric') {
$result = !is_string($val) && is_numeric($val);
} elseif ($type === 'string or int') {
$result = is_string($val) || is_int($val);
} elseif ($type === 'boolean' || $type === 'bool') {
$result = is_bool($val);
} elseif ($type === 'datetime') {
$result = ($val instanceof \DateTime);
} elseif ($type === 'email') {
$result = is_string($val) && preg_match($this->getKnownFormat("email"), $val);
} elseif ($type === 'uri') {
$result = is_string($val) && preg_match($this->getKnownFormat("uri"), $val);
} elseif ($type === 'url') {
$result = is_string($val) && preg_match($this->getKnownFormat("url"), $val) && $val !== "";
} else {
throw new \RuntimeException("Programmer: Don't know how to validate for type `$type`!");
}
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'validType');
return true;
} else {
$this->setError($field, 'validType', [
"title" => "Invalid Value for Field `$field`",
"detail" => "Field `$field` must be a(n) $type value."
]);
return false;
}
} | php | protected function validateType($field, $val, $type, $required = true)
{
if ($val !== null) {
if ($type === 'string') {
$result = is_string($val);
} elseif ($type === 'non-numeric string') {
$result = is_string($val) && !is_numeric($val);
} elseif ($type === 'int' || $type === 'integer') {
$result = is_int($val);
} elseif ($type === "numeric") {
$result = is_numeric($val);
} elseif ($type === 'non-string numeric') {
$result = !is_string($val) && is_numeric($val);
} elseif ($type === 'string or int') {
$result = is_string($val) || is_int($val);
} elseif ($type === 'boolean' || $type === 'bool') {
$result = is_bool($val);
} elseif ($type === 'datetime') {
$result = ($val instanceof \DateTime);
} elseif ($type === 'email') {
$result = is_string($val) && preg_match($this->getKnownFormat("email"), $val);
} elseif ($type === 'uri') {
$result = is_string($val) && preg_match($this->getKnownFormat("uri"), $val);
} elseif ($type === 'url') {
$result = is_string($val) && preg_match($this->getKnownFormat("url"), $val) && $val !== "";
} else {
throw new \RuntimeException("Programmer: Don't know how to validate for type `$type`!");
}
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'validType');
return true;
} else {
$this->setError($field, 'validType', [
"title" => "Invalid Value for Field `$field`",
"detail" => "Field `$field` must be a(n) $type value."
]);
return false;
}
} | [
"protected",
"function",
"validateType",
"(",
"$",
"field",
",",
"$",
"val",
",",
"$",
"type",
",",
"$",
"required",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"val",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"'string'",
")",
"{",
"$",
... | Validates that the value for a given field is of the specified type
@param string $field The name of the field (attribute or relationship) being validated
@param mixed $val The value to validate
@param string $type The type that the value should be
@param bool $required Whether or not the value is required (this affects how `null` is handled)
@return bool Whether or not the validation has passed | [
"Validates",
"that",
"the",
"value",
"for",
"a",
"given",
"field",
"is",
"of",
"the",
"specified",
"type"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L18-L60 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.validateFormat | protected function validateFormat($field, ?string $val, $format, $required = true)
{
if ($val !== null) {
$regexp = $this->getKnownFormat($format);
if (!$regexp) {
$regexp = $format;
}
$result = preg_match($regexp, $val);
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'validFormat');
return true;
} else {
$error = [
"title" => "Invalid Format for Field `$field`",
"detail" => "Value for field `$field` must be a(n) $format."
];
if ($format === $regexp) {
$error["detail"] = "Value for field `$field` must match $format.";
}
$this->setError($field, 'validFormat', $error);
return false;
}
} | php | protected function validateFormat($field, ?string $val, $format, $required = true)
{
if ($val !== null) {
$regexp = $this->getKnownFormat($format);
if (!$regexp) {
$regexp = $format;
}
$result = preg_match($regexp, $val);
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'validFormat');
return true;
} else {
$error = [
"title" => "Invalid Format for Field `$field`",
"detail" => "Value for field `$field` must be a(n) $format."
];
if ($format === $regexp) {
$error["detail"] = "Value for field `$field` must match $format.";
}
$this->setError($field, 'validFormat', $error);
return false;
}
} | [
"protected",
"function",
"validateFormat",
"(",
"$",
"field",
",",
"?",
"string",
"$",
"val",
",",
"$",
"format",
",",
"$",
"required",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"val",
"!==",
"null",
")",
"{",
"$",
"regexp",
"=",
"$",
"this",
"->",
... | Validates that the value for a given field is of the specified format
@param string $field The name of the field (attribute or relationship) being validated
@param mixed $val The value to validate
@param string $format Either a named format or regexp string
@param bool $required Whether or not the value is required (this affects how `null` is handled)
@return bool Whether or not the validation has passed | [
"Validates",
"that",
"the",
"value",
"for",
"a",
"given",
"field",
"is",
"of",
"the",
"specified",
"format"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L72-L98 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.validateAmong | protected function validateAmong($field, $val, array $validOptions, $required = true)
{
if ($val !== null) {
$result = in_array($val, $validOptions, true);
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'validAmongOptions');
return true;
} else {
$this->setError($field, 'validAmongOptions', [
"title" => "Invalid Value for Field `$field`",
"detail" => "Field `$field` must be one of the accepted options: `".implode("`, `", $validOptions)."`"
]);
return false;
}
} | php | protected function validateAmong($field, $val, array $validOptions, $required = true)
{
if ($val !== null) {
$result = in_array($val, $validOptions, true);
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'validAmongOptions');
return true;
} else {
$this->setError($field, 'validAmongOptions', [
"title" => "Invalid Value for Field `$field`",
"detail" => "Field `$field` must be one of the accepted options: `".implode("`, `", $validOptions)."`"
]);
return false;
}
} | [
"protected",
"function",
"validateAmong",
"(",
"$",
"field",
",",
"$",
"val",
",",
"array",
"$",
"validOptions",
",",
"$",
"required",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"val",
"!==",
"null",
")",
"{",
"$",
"result",
"=",
"in_array",
"(",
"$",
... | Validates that the value for a given field is in the given array of valid options
@param string $field The name of the field (attribute or relationship) being validated
@param mixed $val The value to validate
@param array $validOptions The collection of valid options among which the value should be found
@param bool $required Whether or not the value is required (this affects how `null` is handled)
@return bool Whether or not the validation has passed | [
"Validates",
"that",
"the",
"value",
"for",
"a",
"given",
"field",
"is",
"in",
"the",
"given",
"array",
"of",
"valid",
"options"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L111-L129 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.validateStrlen | protected function validateStrlen(string $field, ?string $val, int $min, int $max, bool $required = true)
{
if ($val !== null) {
$strlen = strlen($val);
$result = !($strlen < $min || $strlen > $max);
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, "length");
} else {
$this->setError($field, "length", [
"title" => "Length of `$field` Out of Bounds",
"detail" => "Field `$field` must be between $min and $max characters long."
]);
}
return $result;
} | php | protected function validateStrlen(string $field, ?string $val, int $min, int $max, bool $required = true)
{
if ($val !== null) {
$strlen = strlen($val);
$result = !($strlen < $min || $strlen > $max);
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, "length");
} else {
$this->setError($field, "length", [
"title" => "Length of `$field` Out of Bounds",
"detail" => "Field `$field` must be between $min and $max characters long."
]);
}
return $result;
} | [
"protected",
"function",
"validateStrlen",
"(",
"string",
"$",
"field",
",",
"?",
"string",
"$",
"val",
",",
"int",
"$",
"min",
",",
"int",
"$",
"max",
",",
"bool",
"$",
"required",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"val",
"!==",
"null",
")",
... | Validates that the given value conforms to the given length specifications
@param string $field The name of the field being validated
@param string|null $val The value being evaluated
@param int $min The minimum length of the string (defaults to 0)
@param int $max The maximum length of the string
@param bool $required Whether or not the value is required
@return bool Whether or not the validation has passed | [
"Validates",
"that",
"the",
"given",
"value",
"conforms",
"to",
"the",
"given",
"length",
"specifications"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L169-L187 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.validateRelatedResourceExists | protected function validateRelatedResourceExists($field, \CFX\JsonApi\ResourceInterface $r, $required = true)
{
if ($r !== null) {
try {
$r->initialize();
$result = true;
} catch (ResourceNotFoundException $e) {
$result = false;
}
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'exists');
return true;
} else {
$this->setError($field, 'exists', [
"title" => "Invalid Relationship `$field`",
"detail" => "The `$field` you've indicated for this order is not currently in our system."
]);
return false;
}
} | php | protected function validateRelatedResourceExists($field, \CFX\JsonApi\ResourceInterface $r, $required = true)
{
if ($r !== null) {
try {
$r->initialize();
$result = true;
} catch (ResourceNotFoundException $e) {
$result = false;
}
} else {
$result = !$required;
}
if ($result) {
$this->clearError($field, 'exists');
return true;
} else {
$this->setError($field, 'exists', [
"title" => "Invalid Relationship `$field`",
"detail" => "The `$field` you've indicated for this order is not currently in our system."
]);
return false;
}
} | [
"protected",
"function",
"validateRelatedResourceExists",
"(",
"$",
"field",
",",
"\\",
"CFX",
"\\",
"JsonApi",
"\\",
"ResourceInterface",
"$",
"r",
",",
"$",
"required",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"r",
"!==",
"null",
")",
"{",
"try",
"{",
... | Validates that the given resource actually exists in the database
@param string $field The name of the field (attribute or relationship) being validated
@param \CFX\JsonApi\ResourceInterface $r The resource to validate
@param bool $required Whether or not the resource is required (this affects how `null` is handled)
@return bool Whether or not the validation has passed | [
"Validates",
"that",
"the",
"given",
"resource",
"actually",
"exists",
"in",
"the",
"database"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L197-L220 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.validateImmutable | protected function validateImmutable($field, $val, $required = true)
{
if ($this->getInitial($field) && $this->valueDiffersFromInitial($field, $val)) {
$this->setError($field, 'immutable', [
"title" => "`$field` is Immutable",
"detail" => "You can't change the `$field` field of this resource once it's been set.",
]);
return false;
} else {
$this->clearError($field, 'immutable');
return true;
}
} | php | protected function validateImmutable($field, $val, $required = true)
{
if ($this->getInitial($field) && $this->valueDiffersFromInitial($field, $val)) {
$this->setError($field, 'immutable', [
"title" => "`$field` is Immutable",
"detail" => "You can't change the `$field` field of this resource once it's been set.",
]);
return false;
} else {
$this->clearError($field, 'immutable');
return true;
}
} | [
"protected",
"function",
"validateImmutable",
"(",
"$",
"field",
",",
"$",
"val",
",",
"$",
"required",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getInitial",
"(",
"$",
"field",
")",
"&&",
"$",
"this",
"->",
"valueDiffersFromInitial",
"(",
... | Validates that the given value has not been changed since the first time it was set
@param string $field The name of the field (attribute or relationship) being validated
@param mixed $val The value to validate
@param bool $required Whether or not the resource is required (this affects how `null` is handled)
@return bool Whether or not the validation has passed | [
"Validates",
"that",
"the",
"given",
"value",
"has",
"not",
"been",
"changed",
"since",
"the",
"first",
"time",
"it",
"was",
"set"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L230-L242 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.cleanStringValue | protected function cleanStringValue($val)
{
if ($val !== null) {
if (is_string($val)) {
$val = trim($val);
if ($val === '') {
$val = null;
}
} elseif (is_int($val)) {
$val = (string)$val;
}
}
return $val;
} | php | protected function cleanStringValue($val)
{
if ($val !== null) {
if (is_string($val)) {
$val = trim($val);
if ($val === '') {
$val = null;
}
} elseif (is_int($val)) {
$val = (string)$val;
}
}
return $val;
} | [
"protected",
"function",
"cleanStringValue",
"(",
"$",
"val",
")",
"{",
"if",
"(",
"$",
"val",
"!==",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"val",
")",
")",
"{",
"$",
"val",
"=",
"trim",
"(",
"$",
"val",
")",
";",
"if",
"(",
"$",
... | Cleans a value that is expected to be a string
If the value _is_ a string, this trims it and sets it to null if it's an empty string. If the value
is an integer, it coerces it into a string. Otherwise, it leaves the value alone.
@param mixed $val The value to clean
@return mixed The cleaned string or null or the original value, if not stringish | [
"Cleans",
"a",
"value",
"that",
"is",
"expected",
"to",
"be",
"a",
"string"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L253-L266 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.cleanBooleanValue | protected function cleanBooleanValue($val)
{
if ($val !== null) {
if ($val === 1 || $val === '1' || $val === 0 || $val === '0') {
$val = (bool)$val;
} elseif (is_string($val) && trim($val) === '') {
$val = null;
}
}
return $val;
} | php | protected function cleanBooleanValue($val)
{
if ($val !== null) {
if ($val === 1 || $val === '1' || $val === 0 || $val === '0') {
$val = (bool)$val;
} elseif (is_string($val) && trim($val) === '') {
$val = null;
}
}
return $val;
} | [
"protected",
"function",
"cleanBooleanValue",
"(",
"$",
"val",
")",
"{",
"if",
"(",
"$",
"val",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"val",
"===",
"1",
"||",
"$",
"val",
"===",
"'1'",
"||",
"$",
"val",
"===",
"0",
"||",
"$",
"val",
"===",
"... | Cleans a value that is expected to be a boolean
If the value is a string or integer that can evaluate to a boolean, this coerces it into a boolean. Otherwise,
it leaves the value alone.
@param mixed $val The value to clean
@return mixed A boolean value or the original value, if not boolish | [
"Cleans",
"a",
"value",
"that",
"is",
"expected",
"to",
"be",
"a",
"boolean"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L277-L287 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.cleanNumberValue | protected function cleanNumberValue($val)
{
if ($val !== null) {
if (is_string($val)) {
if (trim($val) === '') {
$val = null;
} elseif (is_numeric($val)) {
$val = $val*1;
}
}
}
return $val;
} | php | protected function cleanNumberValue($val)
{
if ($val !== null) {
if (is_string($val)) {
if (trim($val) === '') {
$val = null;
} elseif (is_numeric($val)) {
$val = $val*1;
}
}
}
return $val;
} | [
"protected",
"function",
"cleanNumberValue",
"(",
"$",
"val",
")",
"{",
"if",
"(",
"$",
"val",
"!==",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"val",
")",
")",
"{",
"if",
"(",
"trim",
"(",
"$",
"val",
")",
"===",
"''",
")",
"{",
"$",... | Cleans a value that is expected to be a number
If the value is a string, this coerces it into an int or float by multiplying by 1. Otherwise,
it leaves the value alone.
@param mixed $val The value to clean
@return mixed An int or float value or the original value, if not numeric | [
"Cleans",
"a",
"value",
"that",
"is",
"expected",
"to",
"be",
"a",
"number"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L298-L310 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.cleanDateTimeValue | protected function cleanDateTimeValue($val)
{
// Uninterpretable values get returned as is
if ((is_string($val) && substr($val, 0, 4) === '0000') || $val === false) {
return $val;
}
// null and null-equivalent get returned as null
if ($val === '' || $val === null) {
return null;
}
// For everything else, we try to make a date out of it
try {
if (is_numeric($val)) {
$val = new \DateTime("@".$val);
} else {
$val = new \DateTime($val);
}
return $val;
} catch (\Throwable $e) {
return $val;
}
} | php | protected function cleanDateTimeValue($val)
{
// Uninterpretable values get returned as is
if ((is_string($val) && substr($val, 0, 4) === '0000') || $val === false) {
return $val;
}
// null and null-equivalent get returned as null
if ($val === '' || $val === null) {
return null;
}
// For everything else, we try to make a date out of it
try {
if (is_numeric($val)) {
$val = new \DateTime("@".$val);
} else {
$val = new \DateTime($val);
}
return $val;
} catch (\Throwable $e) {
return $val;
}
} | [
"protected",
"function",
"cleanDateTimeValue",
"(",
"$",
"val",
")",
"{",
"// Uninterpretable values get returned as is",
"if",
"(",
"(",
"is_string",
"(",
"$",
"val",
")",
"&&",
"substr",
"(",
"$",
"val",
",",
"0",
",",
"4",
")",
"===",
"'0000'",
")",
"||... | Attempts to convert an integer or string into a DateTime object
@param mixed $val The value to clean
@return mixed A DateTime object or the original value, if not coercible | [
"Attempts",
"to",
"convert",
"an",
"integer",
"or",
"string",
"into",
"a",
"DateTime",
"object"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L318-L341 | train |
cfxmarkets/php-public-models | src/ResourceValidationsTrait.php | ResourceValidationsTrait.getKnownFormat | protected function getKnownFormat(string $formatName)
{
$knownFormats = [
"email" => "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,}$/ix",
"swiftCode" => "/^[A-Za-z]{6}[A-Za-z0-9]{2}[0-9A-Za-z]{0,3}$/",
"uri" => "/^\w+:(\/\/)?[^\s]+$/",
"url" => "/^((\w+:)?\/\/[^\s\/]+)?(\/[^\s]+)*\/?$/",
];
if (array_key_exists($formatName, $knownFormats)) {
return $knownFormats[$formatName];
} else {
return null;
}
} | php | protected function getKnownFormat(string $formatName)
{
$knownFormats = [
"email" => "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,}$/ix",
"swiftCode" => "/^[A-Za-z]{6}[A-Za-z0-9]{2}[0-9A-Za-z]{0,3}$/",
"uri" => "/^\w+:(\/\/)?[^\s]+$/",
"url" => "/^((\w+:)?\/\/[^\s\/]+)?(\/[^\s]+)*\/?$/",
];
if (array_key_exists($formatName, $knownFormats)) {
return $knownFormats[$formatName];
} else {
return null;
}
} | [
"protected",
"function",
"getKnownFormat",
"(",
"string",
"$",
"formatName",
")",
"{",
"$",
"knownFormats",
"=",
"[",
"\"email\"",
"=>",
"\"/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*@([a-z0-9\\-]+\\.)+[a-z]{2,}$/ix\"",
",",
"\"swiftCode\"",
"=>",
"\"/^[A-Za-z]{6}[A-Za-z0-9]{2}[... | Returns a list of known formats for validation
@param string $formatName The name of the format to get
@return string|null The regexp string representing the requested format, or null if format is not known | [
"Returns",
"a",
"list",
"of",
"known",
"formats",
"for",
"validation"
] | b91a58f7d9519b98b29c58f0911e976e361a5f65 | https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L349-L363 | train |
htmlburger/wpemerge-cli | src/Presets/PresetEnablerTrait.php | PresetEnablerTrait.enablePreset | protected function enablePreset( $filepath, $preset ) {
$begin = sprintf( '~^\s*/\* @preset-begin\(%1$s\).*?\r?\n~mi', preg_quote( $preset, '~' ) );
$end = sprintf( '~^\s*@preset-end\(%1$s\) \*/\s*?\r?\n~mi', preg_quote( $preset, '~' ) );
$contents = file_get_contents( $filepath );
if ( ! preg_match( $begin, $contents ) || ! preg_match( $end, $contents ) ) {
return;
}
$contents = preg_replace( $begin, '', $contents );
$contents = preg_replace( $end, '', $contents );
file_put_contents( $filepath, $contents );
} | php | protected function enablePreset( $filepath, $preset ) {
$begin = sprintf( '~^\s*/\* @preset-begin\(%1$s\).*?\r?\n~mi', preg_quote( $preset, '~' ) );
$end = sprintf( '~^\s*@preset-end\(%1$s\) \*/\s*?\r?\n~mi', preg_quote( $preset, '~' ) );
$contents = file_get_contents( $filepath );
if ( ! preg_match( $begin, $contents ) || ! preg_match( $end, $contents ) ) {
return;
}
$contents = preg_replace( $begin, '', $contents );
$contents = preg_replace( $end, '', $contents );
file_put_contents( $filepath, $contents );
} | [
"protected",
"function",
"enablePreset",
"(",
"$",
"filepath",
",",
"$",
"preset",
")",
"{",
"$",
"begin",
"=",
"sprintf",
"(",
"'~^\\s*/\\* @preset-begin\\(%1$s\\).*?\\r?\\n~mi'",
",",
"preg_quote",
"(",
"$",
"preset",
",",
"'~'",
")",
")",
";",
"$",
"end",
... | Uncomment preset statements in file.
@param string $filepath
@param string $preset
@return void | [
"Uncomment",
"preset",
"statements",
"in",
"file",
"."
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/PresetEnablerTrait.php#L13-L26 | train |
Kuestenschmiede/TrackingBundle | Resources/contao/dca/tl_page.php | tl_c4gtracking_page.getTrackingConfigurations | public function getTrackingConfigurations()
{
/*if (!$this->User->isAdmin && !is_array($this->User->forms))
{
return array();
}*/
$arrTrackingConfigurations = array();
$objTrackingConfigurations = $this->Database->execute("SELECT id, name FROM tl_c4g_tracking ORDER BY name");
while ($objTrackingConfigurations->next())
{
//if ($this->User->isAdmin || $this->User->hasAccess($objForms->id, 'forms'))
//{
$arrTrackingConfigurations[$objTrackingConfigurations->id] = $objTrackingConfigurations->name . ' (ID ' . $objTrackingConfigurations->id . ')';
//}
}
return $arrTrackingConfigurations;
} | php | public function getTrackingConfigurations()
{
/*if (!$this->User->isAdmin && !is_array($this->User->forms))
{
return array();
}*/
$arrTrackingConfigurations = array();
$objTrackingConfigurations = $this->Database->execute("SELECT id, name FROM tl_c4g_tracking ORDER BY name");
while ($objTrackingConfigurations->next())
{
//if ($this->User->isAdmin || $this->User->hasAccess($objForms->id, 'forms'))
//{
$arrTrackingConfigurations[$objTrackingConfigurations->id] = $objTrackingConfigurations->name . ' (ID ' . $objTrackingConfigurations->id . ')';
//}
}
return $arrTrackingConfigurations;
} | [
"public",
"function",
"getTrackingConfigurations",
"(",
")",
"{",
"/*if (!$this->User->isAdmin && !is_array($this->User->forms))\n \t\t{\n \t\t\treturn array();\n \t\t}*/",
"$",
"arrTrackingConfigurations",
"=",
"array",
"(",
")",
";",
"$",
"objTrackingConfigurations",
"=",
"... | Get all trcking-configurations and return them as array
@return array | [
"Get",
"all",
"trcking",
"-",
"configurations",
"and",
"return",
"them",
"as",
"array"
] | 7ad1b8ef3103854dfce8309d2eed7060febaa4ee | https://github.com/Kuestenschmiede/TrackingBundle/blob/7ad1b8ef3103854dfce8309d2eed7060febaa4ee/Resources/contao/dca/tl_page.php#L48-L67 | train |
hail-framework/framework | src/Template/Extension/URI.php | URI.runUri | public function runUri($var1 = null, $var2 = null, $var3 = null, $var4 = null)
{
if (null === $var1) {
return $this->uri;
}
if (\is_numeric($var1) && null === $var2) {
return $this->parts[$var1] ?? null;
}
if (\is_numeric($var1) && \is_string($var2)) {
return $this->checkUriSegmentMatch($var1, $var2, $var3, $var4);
}
if (\is_string($var1)) {
return $this->checkUriRegexMatch($var1, $var2, $var3);
}
throw new \LogicException('Invalid use of the uri function.');
} | php | public function runUri($var1 = null, $var2 = null, $var3 = null, $var4 = null)
{
if (null === $var1) {
return $this->uri;
}
if (\is_numeric($var1) && null === $var2) {
return $this->parts[$var1] ?? null;
}
if (\is_numeric($var1) && \is_string($var2)) {
return $this->checkUriSegmentMatch($var1, $var2, $var3, $var4);
}
if (\is_string($var1)) {
return $this->checkUriRegexMatch($var1, $var2, $var3);
}
throw new \LogicException('Invalid use of the uri function.');
} | [
"public",
"function",
"runUri",
"(",
"$",
"var1",
"=",
"null",
",",
"$",
"var2",
"=",
"null",
",",
"$",
"var3",
"=",
"null",
",",
"$",
"var4",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"var1",
")",
"{",
"return",
"$",
"this",
"->",
... | Perform URI check.
@param null|int|string $var1
@param mixed $var2
@param mixed $var3
@param mixed $var4
@return mixed | [
"Perform",
"URI",
"check",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Extension/URI.php#L60-L79 | train |
hail-framework/framework | src/Template/Extension/URI.php | URI.checkUriSegmentMatch | protected function checkUriSegmentMatch($key, $string, $returnOnTrue = null, $returnOnFalse = null)
{
if (\array_key_exists($key, $this->parts) && $this->parts[$key] === $string) {
return $returnOnTrue ?? true;
}
return $returnOnFalse ?? false;
} | php | protected function checkUriSegmentMatch($key, $string, $returnOnTrue = null, $returnOnFalse = null)
{
if (\array_key_exists($key, $this->parts) && $this->parts[$key] === $string) {
return $returnOnTrue ?? true;
}
return $returnOnFalse ?? false;
} | [
"protected",
"function",
"checkUriSegmentMatch",
"(",
"$",
"key",
",",
"$",
"string",
",",
"$",
"returnOnTrue",
"=",
"null",
",",
"$",
"returnOnFalse",
"=",
"null",
")",
"{",
"if",
"(",
"\\",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
... | Perform a URI segment match.
@param integer $key
@param string $string
@param mixed $returnOnTrue
@param mixed $returnOnFalse
@return mixed | [
"Perform",
"a",
"URI",
"segment",
"match",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Extension/URI.php#L89-L96 | train |
hail-framework/framework | src/Template/Extension/URI.php | URI.checkUriRegexMatch | protected function checkUriRegexMatch($regex, $returnOnTrue = null, $returnOnFalse = null)
{
if (\preg_match('#^' . $regex . '$#', $this->uri) === 1) {
return $returnOnTrue ?? true;
}
return $returnOnFalse ?? false;
} | php | protected function checkUriRegexMatch($regex, $returnOnTrue = null, $returnOnFalse = null)
{
if (\preg_match('#^' . $regex . '$#', $this->uri) === 1) {
return $returnOnTrue ?? true;
}
return $returnOnFalse ?? false;
} | [
"protected",
"function",
"checkUriRegexMatch",
"(",
"$",
"regex",
",",
"$",
"returnOnTrue",
"=",
"null",
",",
"$",
"returnOnFalse",
"=",
"null",
")",
"{",
"if",
"(",
"\\",
"preg_match",
"(",
"'#^'",
".",
"$",
"regex",
".",
"'$#'",
",",
"$",
"this",
"->... | Perform a regular express match.
@param string $regex
@param mixed $returnOnTrue
@param mixed $returnOnFalse
@return mixed | [
"Perform",
"a",
"regular",
"express",
"match",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Extension/URI.php#L105-L112 | train |
systemson/collection | src/Base/NoKeysTrait.php | NoKeysTrait.add | public function add($value): bool
{
if ($this->has($value)) {
return false;
}
$this->set($value);
return true;
} | php | public function add($value): bool
{
if ($this->has($value)) {
return false;
}
$this->set($value);
return true;
} | [
"public",
"function",
"add",
"(",
"$",
"value",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"set",
"(",
"$",
"value",
")",
";",
"return",
"true",
... | Adds a new item to the collection.
@param mixed $value
@return bool true on success, false if the item already exists. | [
"Adds",
"a",
"new",
"item",
"to",
"the",
"collection",
"."
] | fb3ae1a78806aafabc0562db96822e8b99dc2a64 | https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/NoKeysTrait.php#L38-L47 | train |
hail-framework/framework | src/Database/Migration/Adapter/SqlServerAdapter.php | SqlServerAdapter.migrated | public function migrated(MigrationInterface $migration, $direction, $startTime, $endTime)
{
$startTime = str_replace(' ', 'T', $startTime);
$endTime = str_replace(' ', 'T', $endTime);
return parent::migrated($migration, $direction, $startTime, $endTime);
} | php | public function migrated(MigrationInterface $migration, $direction, $startTime, $endTime)
{
$startTime = str_replace(' ', 'T', $startTime);
$endTime = str_replace(' ', 'T', $endTime);
return parent::migrated($migration, $direction, $startTime, $endTime);
} | [
"public",
"function",
"migrated",
"(",
"MigrationInterface",
"$",
"migration",
",",
"$",
"direction",
",",
"$",
"startTime",
",",
"$",
"endTime",
")",
"{",
"$",
"startTime",
"=",
"str_replace",
"(",
"' '",
",",
"'T'",
",",
"$",
"startTime",
")",
";",
"$"... | Records a migration being run.
@param MigrationInterface $migration Migration
@param string $direction Direction
@param int $startTime Start Time
@param int $endTime End Time
@return AdapterInterface | [
"Records",
"a",
"migration",
"being",
"run",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/SqlServerAdapter.php#L1138-L1144 | train |
htmlburger/wpemerge-cli | src/Presets/CarbonFields.php | CarbonFields.getCopyList | protected function getCopyList( $directory ) {
$copy_list = [
$this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'Carbon_Rich_Text_Widget.php' )
=> $this->path( $directory, 'app', 'src', 'Widgets', 'Carbon_Rich_Text_Widget.php' ),
$this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields.php' )
=> $this->path( $directory, 'app', 'helpers', 'carbon-fields.php' ),
];
$source_dir = $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields' ) . DIRECTORY_SEPARATOR;
$destination_dir = $this->path( $directory, 'app', 'setup', 'carbon-fields' ) . DIRECTORY_SEPARATOR;
$files = scandir( $source_dir );
$files = array_filter( $files, function( $file ) {
return preg_match( '~\.php$~', $file );
} );
foreach ( $files as $file ) {
$copy_list[ $source_dir . $file ] = $destination_dir . $file;
}
return $copy_list;
} | php | protected function getCopyList( $directory ) {
$copy_list = [
$this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'Carbon_Rich_Text_Widget.php' )
=> $this->path( $directory, 'app', 'src', 'Widgets', 'Carbon_Rich_Text_Widget.php' ),
$this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields.php' )
=> $this->path( $directory, 'app', 'helpers', 'carbon-fields.php' ),
];
$source_dir = $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields' ) . DIRECTORY_SEPARATOR;
$destination_dir = $this->path( $directory, 'app', 'setup', 'carbon-fields' ) . DIRECTORY_SEPARATOR;
$files = scandir( $source_dir );
$files = array_filter( $files, function( $file ) {
return preg_match( '~\.php$~', $file );
} );
foreach ( $files as $file ) {
$copy_list[ $source_dir . $file ] = $destination_dir . $file;
}
return $copy_list;
} | [
"protected",
"function",
"getCopyList",
"(",
"$",
"directory",
")",
"{",
"$",
"copy_list",
"=",
"[",
"$",
"this",
"->",
"path",
"(",
"WPEMERGE_CLI_DIR",
",",
"'src'",
",",
"'CarbonFields'",
",",
"'Carbon_Rich_Text_Widget.php'",
")",
"=>",
"$",
"this",
"->",
... | Get array of files to copy
@param string $directory
@return array | [
"Get",
"array",
"of",
"files",
"to",
"copy"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/CarbonFields.php#L69-L91 | train |
htmlburger/wpemerge-cli | src/Presets/CarbonFields.php | CarbonFields.addHooks | protected function addHooks( $directory ) {
$hooks_filepath = $this->path( $directory, 'app', 'hooks.php' );
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
/**
* Carbon Fields
*/
EOT
);
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
add_action( 'after_setup_theme', 'app_bootstrap_carbon_fields', 100 );
EOT
);
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
add_action( 'carbon_fields_register_fields', 'app_bootstrap_carbon_fields_register_fields' );
EOT
);
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
add_filter( 'carbon_fields_map_field_api_key', 'app_filter_carbon_fields_google_maps_api_key' );
EOT
);
} | php | protected function addHooks( $directory ) {
$hooks_filepath = $this->path( $directory, 'app', 'hooks.php' );
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
/**
* Carbon Fields
*/
EOT
);
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
add_action( 'after_setup_theme', 'app_bootstrap_carbon_fields', 100 );
EOT
);
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
add_action( 'carbon_fields_register_fields', 'app_bootstrap_carbon_fields_register_fields' );
EOT
);
$this->appendUniqueStatement(
$hooks_filepath,
<<<'EOT'
add_filter( 'carbon_fields_map_field_api_key', 'app_filter_carbon_fields_google_maps_api_key' );
EOT
);
} | [
"protected",
"function",
"addHooks",
"(",
"$",
"directory",
")",
"{",
"$",
"hooks_filepath",
"=",
"$",
"this",
"->",
"path",
"(",
"$",
"directory",
",",
"'app'",
",",
"'hooks.php'",
")",
";",
"$",
"this",
"->",
"appendUniqueStatement",
"(",
"$",
"hooks_fil... | Add hook statements
@param string $directory
@return void | [
"Add",
"hook",
"statements"
] | 075f1982b7dd87039a4e7bbc05caf676a10fe862 | https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/CarbonFields.php#L114-L147 | train |
hail-framework/framework | src/Filesystem/MountManager.php | MountManager.forceRename | public function forceRename(string $path, string $newpath)
{
$deleted = true;
if ($this->has($newpath)) {
try {
$deleted = $this->delete($newpath);
} catch (FileNotFoundException $e) {
// The destination path does not exist. That's ok.
$deleted = true;
}
}
if ($deleted) {
return $this->move($path, $newpath);
}
return false;
} | php | public function forceRename(string $path, string $newpath)
{
$deleted = true;
if ($this->has($newpath)) {
try {
$deleted = $this->delete($newpath);
} catch (FileNotFoundException $e) {
// The destination path does not exist. That's ok.
$deleted = true;
}
}
if ($deleted) {
return $this->move($path, $newpath);
}
return false;
} | [
"public",
"function",
"forceRename",
"(",
"string",
"$",
"path",
",",
"string",
"$",
"newpath",
")",
"{",
"$",
"deleted",
"=",
"true",
";",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"newpath",
")",
")",
"{",
"try",
"{",
"$",
"deleted",
"=",
... | Renames a file, overwriting the destination if it exists.
@param string $path Path to the existing file.
@param string $newpath The new path of the file.
@return bool True on success, false on failure.
@throws FileNotFoundException Thrown if $path does not exist.
@throws FilesystemNotFoundException
@throws FileExistsException | [
"Renames",
"a",
"file",
"overwriting",
"the",
"destination",
"if",
"it",
"exists",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L267-L284 | train |
hail-framework/framework | src/Filesystem/MountManager.php | MountManager.readStream | public function readStream($path)
{
[$prefix, $path] = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->readStream($path);
} | php | public function readStream($path)
{
[$prefix, $path] = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->readStream($path);
} | [
"public",
"function",
"readStream",
"(",
"$",
"path",
")",
"{",
"[",
"$",
"prefix",
",",
"$",
"path",
"]",
"=",
"$",
"this",
"->",
"getPrefixAndPath",
"(",
"$",
"path",
")",
";",
"return",
"$",
"this",
"->",
"getFilesystem",
"(",
"$",
"prefix",
")",
... | Retrieves a read-stream for a path.
@param string $path The path to the file.
@throws FileNotFoundException
@return resource|false The path resource or false on failure. | [
"Retrieves",
"a",
"read",
"-",
"stream",
"for",
"a",
"path",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L347-L352 | train |
hail-framework/framework | src/Filesystem/MountManager.php | MountManager.getTimestamp | public function getTimestamp($path)
{
[$prefix, $path] = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->getTimestamp($path);
} | php | public function getTimestamp($path)
{
[$prefix, $path] = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->getTimestamp($path);
} | [
"public",
"function",
"getTimestamp",
"(",
"$",
"path",
")",
"{",
"[",
"$",
"prefix",
",",
"$",
"path",
"]",
"=",
"$",
"this",
"->",
"getPrefixAndPath",
"(",
"$",
"path",
")",
";",
"return",
"$",
"this",
"->",
"getFilesystem",
"(",
"$",
"prefix",
")"... | Get a file's timestamp.
@param string $path The path to the file.
@throws FileNotFoundException
@return string|false The timestamp or false on failure. | [
"Get",
"a",
"file",
"s",
"timestamp",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L411-L416 | train |
hail-framework/framework | src/Filesystem/MountManager.php | MountManager.readAndDelete | public function readAndDelete($path)
{
[$prefix, $path] = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->readAndDelete($path);
} | php | public function readAndDelete($path)
{
[$prefix, $path] = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->readAndDelete($path);
} | [
"public",
"function",
"readAndDelete",
"(",
"$",
"path",
")",
"{",
"[",
"$",
"prefix",
",",
"$",
"path",
"]",
"=",
"$",
"this",
"->",
"getPrefixAndPath",
"(",
"$",
"path",
")",
";",
"return",
"$",
"this",
"->",
"getFilesystem",
"(",
"$",
"prefix",
")... | Read and delete a file.
@param string $path The path to the file.
@throws FileNotFoundException
@return string|false The file contents, or false on failure. | [
"Read",
"and",
"delete",
"a",
"file",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L633-L638 | train |
Becklyn/RadBundle | src/Form/FormErrorMapper.php | FormErrorMapper.addChildErrors | private function addChildErrors (FormInterface $form, string $fieldPrefix, string $translationDomain, array &$allErrors) : void
{
foreach ($form->all() as $children)
{
$childErrors = $children->getErrors();
$fieldName = \ltrim("{$fieldPrefix}{$children->getName()}");
if (0 < \count($childErrors))
{
$allErrors[$fieldName] = \array_map(
function (FormError $error) use ($translationDomain)
{
return $this->translator->trans($error->getMessage(), [], $translationDomain);
},
\iterator_to_array($childErrors)
);
}
$this->addChildErrors($children, "{$fieldName}_", $translationDomain, $allErrors);
}
} | php | private function addChildErrors (FormInterface $form, string $fieldPrefix, string $translationDomain, array &$allErrors) : void
{
foreach ($form->all() as $children)
{
$childErrors = $children->getErrors();
$fieldName = \ltrim("{$fieldPrefix}{$children->getName()}");
if (0 < \count($childErrors))
{
$allErrors[$fieldName] = \array_map(
function (FormError $error) use ($translationDomain)
{
return $this->translator->trans($error->getMessage(), [], $translationDomain);
},
\iterator_to_array($childErrors)
);
}
$this->addChildErrors($children, "{$fieldName}_", $translationDomain, $allErrors);
}
} | [
"private",
"function",
"addChildErrors",
"(",
"FormInterface",
"$",
"form",
",",
"string",
"$",
"fieldPrefix",
",",
"string",
"$",
"translationDomain",
",",
"array",
"&",
"$",
"allErrors",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"form",
"->",
"all",
"(... | Adds all child errors to the mapping of errors.
@param FormInterface $form
@param string $fieldPrefix
@param array $allErrors | [
"Adds",
"all",
"child",
"errors",
"to",
"the",
"mapping",
"of",
"errors",
"."
] | 34d5887e13f5a4018843b77dcbefc2eb2f3169f4 | https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Form/FormErrorMapper.php#L61-L81 | train |
hail-framework/framework | src/Filesystem/Filesystem.php | Filesystem.getMetadataByName | protected function getMetadataByName(array $object, $key)
{
$method = 'get' . \ucfirst($key);
if (!\method_exists($this, $method)) {
throw new \InvalidArgumentException('Could not get meta-data for key: ' . $key);
}
$object[$key] = $this->{$method}($object['path']);
return $object;
} | php | protected function getMetadataByName(array $object, $key)
{
$method = 'get' . \ucfirst($key);
if (!\method_exists($this, $method)) {
throw new \InvalidArgumentException('Could not get meta-data for key: ' . $key);
}
$object[$key] = $this->{$method}($object['path']);
return $object;
} | [
"protected",
"function",
"getMetadataByName",
"(",
"array",
"$",
"object",
",",
"$",
"key",
")",
"{",
"$",
"method",
"=",
"'get'",
".",
"\\",
"ucfirst",
"(",
"$",
"key",
")",
";",
"if",
"(",
"!",
"\\",
"method_exists",
"(",
"$",
"this",
",",
"$",
"... | Get a meta-data value by key name.
@param array $object
@param string $key
@return array | [
"Get",
"a",
"meta",
"-",
"data",
"value",
"by",
"key",
"name",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Filesystem.php#L632-L643 | train |
Kajna/K-Core | Core/Http/Request.php | Request.getUriSegment | public function getUriSegment($index)
{
$segments = explode('/', $this->server->get('REQUEST_URI'));
if (isset($segments[$index])) {
return $segments[$index];
}
return false;
} | php | public function getUriSegment($index)
{
$segments = explode('/', $this->server->get('REQUEST_URI'));
if (isset($segments[$index])) {
return $segments[$index];
}
return false;
} | [
"public",
"function",
"getUriSegment",
"(",
"$",
"index",
")",
"{",
"$",
"segments",
"=",
"explode",
"(",
"'/'",
",",
"$",
"this",
"->",
"server",
"->",
"get",
"(",
"'REQUEST_URI'",
")",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"segments",
"[",
"$",
... | Get request URI segment.
@param int $index
@return string|bool | [
"Get",
"request",
"URI",
"segment",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Http/Request.php#L190-L197 | train |
Kajna/K-Core | Core/Http/Request.php | Request.isAjax | public function isAjax()
{
if ($this->headers->get('HTTP_X_REQUESTED_WITH') !== null
&& strtolower($this->headers->get('HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest'
) {
return true;
}
return false;
} | php | public function isAjax()
{
if ($this->headers->get('HTTP_X_REQUESTED_WITH') !== null
&& strtolower($this->headers->get('HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest'
) {
return true;
}
return false;
} | [
"public",
"function",
"isAjax",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"headers",
"->",
"get",
"(",
"'HTTP_X_REQUESTED_WITH'",
")",
"!==",
"null",
"&&",
"strtolower",
"(",
"$",
"this",
"->",
"headers",
"->",
"get",
"(",
"'HTTP_X_REQUESTED_WITH'",
")"... | Check if it is AJAX request.
@return bool | [
"Check",
"if",
"it",
"is",
"AJAX",
"request",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Http/Request.php#L226-L234 | train |
hail-framework/framework | src/Filesystem/Adapter/Zip.php | Zip.reopenArchive | protected function reopenArchive()
{
$path = $this->archive->filename;
$this->archive->close();
$this->openArchive($path);
} | php | protected function reopenArchive()
{
$path = $this->archive->filename;
$this->archive->close();
$this->openArchive($path);
} | [
"protected",
"function",
"reopenArchive",
"(",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"archive",
"->",
"filename",
";",
"$",
"this",
"->",
"archive",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"openArchive",
"(",
"$",
"path",
")",
";",
... | Re-open an archive to ensure persistence. | [
"Re",
"-",
"open",
"an",
"archive",
"to",
"ensure",
"persistence",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Zip.php#L50-L55 | train |
hail-framework/framework | src/Filesystem/Adapter/Zip.php | Zip.normalizeObject | protected function normalizeObject(array $object)
{
if (\substr($object['name'], -1) === '/') {
return [
'path' => $this->removePathPrefix(\trim($object['name'], '/')),
'type' => 'dir',
];
}
$result = ['type' => 'file'];
$normalised = Util::map($object, static::$resultMap);
$normalised['path'] = $this->removePathPrefix($normalised['path']);
return \array_merge($result, $normalised);
} | php | protected function normalizeObject(array $object)
{
if (\substr($object['name'], -1) === '/') {
return [
'path' => $this->removePathPrefix(\trim($object['name'], '/')),
'type' => 'dir',
];
}
$result = ['type' => 'file'];
$normalised = Util::map($object, static::$resultMap);
$normalised['path'] = $this->removePathPrefix($normalised['path']);
return \array_merge($result, $normalised);
} | [
"protected",
"function",
"normalizeObject",
"(",
"array",
"$",
"object",
")",
"{",
"if",
"(",
"\\",
"substr",
"(",
"$",
"object",
"[",
"'name'",
"]",
",",
"-",
"1",
")",
"===",
"'/'",
")",
"{",
"return",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"rem... | Normalize a zip response array.
@param array $object
@return array | [
"Normalize",
"a",
"zip",
"response",
"array",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Zip.php#L264-L278 | train |
hail-framework/framework | src/I18n/Gettext/Extractors/Jed.php | Jed.extract | public static function extract(array $content, Translations $translations)
{
$messages = \current($content);
$headers = $messages[''] ?? null;
unset($messages['']);
if (!empty($headers['domain'])) {
$translations->setDomain($headers['domain']);
}
if (!empty($headers['lang'])) {
$translations->setLanguage($headers['lang']);
}
if (!empty($headers['plural-forms'])) {
$translations->setHeader(Translations::HEADER_PLURAL, $headers['plural-forms']);
}
$context_glue = '\u0004';
foreach ($messages as $key => $translation) {
$key = \explode($context_glue, $key);
$context = isset($key[1]) ? \array_shift($key) : '';
$translations->insert($context, \array_shift($key))
->setTranslation(\array_shift($translation))
->setPluralTranslations($translation);
}
} | php | public static function extract(array $content, Translations $translations)
{
$messages = \current($content);
$headers = $messages[''] ?? null;
unset($messages['']);
if (!empty($headers['domain'])) {
$translations->setDomain($headers['domain']);
}
if (!empty($headers['lang'])) {
$translations->setLanguage($headers['lang']);
}
if (!empty($headers['plural-forms'])) {
$translations->setHeader(Translations::HEADER_PLURAL, $headers['plural-forms']);
}
$context_glue = '\u0004';
foreach ($messages as $key => $translation) {
$key = \explode($context_glue, $key);
$context = isset($key[1]) ? \array_shift($key) : '';
$translations->insert($context, \array_shift($key))
->setTranslation(\array_shift($translation))
->setPluralTranslations($translation);
}
} | [
"public",
"static",
"function",
"extract",
"(",
"array",
"$",
"content",
",",
"Translations",
"$",
"translations",
")",
"{",
"$",
"messages",
"=",
"\\",
"current",
"(",
"$",
"content",
")",
";",
"$",
"headers",
"=",
"$",
"messages",
"[",
"''",
"]",
"??... | Handle an array of translations and append to the Translations instance.
@param array $content
@param Translations $translations | [
"Handle",
"an",
"array",
"of",
"translations",
"and",
"append",
"to",
"the",
"Translations",
"instance",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Extractors/Jed.php#L26-L54 | train |
hail-framework/framework | src/Event/EventManager.php | EventManager.addSubscriber | public function addSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_string($params)) {
$this->attach($eventName, [$subscriber, $params]);
} elseif (\is_array($params)) {
if (\is_string($params[0])) {
$this->attach($eventName, [$subscriber, $params[0]], $params[1] ?? 0);
} else {
foreach ($params as $listener) {
$this->attach($eventName, [$subscriber, $listener[0]], $listener[1] ?? 0);
}
}
}
}
return $this;
} | php | public function addSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_string($params)) {
$this->attach($eventName, [$subscriber, $params]);
} elseif (\is_array($params)) {
if (\is_string($params[0])) {
$this->attach($eventName, [$subscriber, $params[0]], $params[1] ?? 0);
} else {
foreach ($params as $listener) {
$this->attach($eventName, [$subscriber, $listener[0]], $listener[1] ?? 0);
}
}
}
}
return $this;
} | [
"public",
"function",
"addSubscriber",
"(",
"EventSubscriberInterface",
"$",
"subscriber",
")",
"{",
"foreach",
"(",
"$",
"subscriber",
"->",
"getSubscribedEvents",
"(",
")",
"as",
"$",
"eventName",
"=>",
"$",
"params",
")",
"{",
"if",
"(",
"\\",
"is_string",
... | Adds an event subscriber.
The subscriber is asked for all the events he is
interested in and added as a listener for these events.
@param EventSubscriberInterface $subscriber The subscriber
@return $this | [
"Adds",
"an",
"event",
"subscriber",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Event/EventManager.php#L195-L212 | train |
hail-framework/framework | src/Event/EventManager.php | EventManager.removeSubscriber | public function removeSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_array($params) && \is_array($params[0])) {
foreach ($params as $listener) {
$this->detach($eventName, [$subscriber, $listener[0]]);
}
} else {
$this->detach($eventName, [$subscriber, \is_string($params) ? $params : $params[0]]);
}
}
return $this;
} | php | public function removeSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_array($params) && \is_array($params[0])) {
foreach ($params as $listener) {
$this->detach($eventName, [$subscriber, $listener[0]]);
}
} else {
$this->detach($eventName, [$subscriber, \is_string($params) ? $params : $params[0]]);
}
}
return $this;
} | [
"public",
"function",
"removeSubscriber",
"(",
"EventSubscriberInterface",
"$",
"subscriber",
")",
"{",
"foreach",
"(",
"$",
"subscriber",
"->",
"getSubscribedEvents",
"(",
")",
"as",
"$",
"eventName",
"=>",
"$",
"params",
")",
"{",
"if",
"(",
"\\",
"is_array"... | Removes an event subscriber.
@param EventSubscriberInterface $subscriber The subscriber
@return $this | [
"Removes",
"an",
"event",
"subscriber",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Event/EventManager.php#L221-L234 | train |
hiqdev/hipanel-module-server | src/models/Server.php | Server.canFullRefuse | public function canFullRefuse()
{
if (!is_numeric($this->last_expires)) {
return null; // In case server is not sold
}
return (time() - Yii::$app->formatter->asTimestamp($this->last_expires)) / 3600 / 24 < 5;
} | php | public function canFullRefuse()
{
if (!is_numeric($this->last_expires)) {
return null; // In case server is not sold
}
return (time() - Yii::$app->formatter->asTimestamp($this->last_expires)) / 3600 / 24 < 5;
} | [
"public",
"function",
"canFullRefuse",
"(",
")",
"{",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"this",
"->",
"last_expires",
")",
")",
"{",
"return",
"null",
";",
"// In case server is not sold",
"}",
"return",
"(",
"time",
"(",
")",
"-",
"Yii",
"::",
"$"... | During 5 days after the last expiration client is able to refuse server with full refund.
Method checks, whether 5 days passed.
@return bool | [
"During",
"5",
"days",
"after",
"the",
"last",
"expiration",
"client",
"is",
"able",
"to",
"refuse",
"server",
"with",
"full",
"refund",
".",
"Method",
"checks",
"whether",
"5",
"days",
"passed",
"."
] | e40c3601952cf1fd420ebb97093ee17a33ff3207 | https://github.com/hiqdev/hipanel-module-server/blob/e40c3601952cf1fd420ebb97093ee17a33ff3207/src/models/Server.php#L240-L247 | train |
hail-framework/framework | src/Http/Message/MessageTrait.php | MessageTrait.validateProtocolVersion | private function validateProtocolVersion($version): void
{
if (empty($version)) {
throw new \InvalidArgumentException(
'HTTP protocol version can not be empty'
);
}
if (!\is_string($version)) {
throw new \InvalidArgumentException(sprintf(
'Unsupported HTTP protocol version; must be a string, received %s',
(\is_object($version) ? \get_class($version) : \gettype($version))
));
}
// HTTP/1 uses a "<major>.<minor>" numbering scheme to indicate
// versions of the protocol, while HTTP/2 does not.
if (!\preg_match('#^(1\.[01]|2)$#', $version)) {
throw new \InvalidArgumentException(\sprintf(
'Unsupported HTTP protocol version "%s" provided',
$version
));
}
} | php | private function validateProtocolVersion($version): void
{
if (empty($version)) {
throw new \InvalidArgumentException(
'HTTP protocol version can not be empty'
);
}
if (!\is_string($version)) {
throw new \InvalidArgumentException(sprintf(
'Unsupported HTTP protocol version; must be a string, received %s',
(\is_object($version) ? \get_class($version) : \gettype($version))
));
}
// HTTP/1 uses a "<major>.<minor>" numbering scheme to indicate
// versions of the protocol, while HTTP/2 does not.
if (!\preg_match('#^(1\.[01]|2)$#', $version)) {
throw new \InvalidArgumentException(\sprintf(
'Unsupported HTTP protocol version "%s" provided',
$version
));
}
} | [
"private",
"function",
"validateProtocolVersion",
"(",
"$",
"version",
")",
":",
"void",
"{",
"if",
"(",
"empty",
"(",
"$",
"version",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'HTTP protocol version can not be empty'",
")",
";",
"}"... | Validate the HTTP protocol version
@param string $version
@throws \InvalidArgumentException on invalid HTTP protocol version | [
"Validate",
"the",
"HTTP",
"protocol",
"version"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Message/MessageTrait.php#L193-L215 | train |
hail-framework/framework | src/I18n/Gettext/Extractors/Po.php | Po.fixMultiLines | private static function fixMultiLines($line, array $lines, &$i)
{
for ($j = $i, $t = \count($lines); $j < $t; ++$j) {
if (\substr($line, -1, 1) == '"'
&& isset($lines[$j + 1])
&& \substr(\trim($lines[$j + 1]), 0, 1) == '"'
) {
$line = \substr($line, 0, -1) . \substr(\trim($lines[$j + 1]), 1);
} else {
$i = $j;
break;
}
}
return $line;
} | php | private static function fixMultiLines($line, array $lines, &$i)
{
for ($j = $i, $t = \count($lines); $j < $t; ++$j) {
if (\substr($line, -1, 1) == '"'
&& isset($lines[$j + 1])
&& \substr(\trim($lines[$j + 1]), 0, 1) == '"'
) {
$line = \substr($line, 0, -1) . \substr(\trim($lines[$j + 1]), 1);
} else {
$i = $j;
break;
}
}
return $line;
} | [
"private",
"static",
"function",
"fixMultiLines",
"(",
"$",
"line",
",",
"array",
"$",
"lines",
",",
"&",
"$",
"i",
")",
"{",
"for",
"(",
"$",
"j",
"=",
"$",
"i",
",",
"$",
"t",
"=",
"\\",
"count",
"(",
"$",
"lines",
")",
";",
"$",
"j",
"<",
... | Gets one string from multiline strings.
@param string $line
@param array $lines
@param int &$i
@return string | [
"Gets",
"one",
"string",
"from",
"multiline",
"strings",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Extractors/Po.php#L162-L177 | train |
mirko-pagliai/php-tools | src/Entity.php | Entity.set | public function set($property, $value = null)
{
if (is_string($property) && $value != '') {
$property = [$property => $value];
}
foreach ($property as $name => $value) {
$this->properties[$name] = $value;
}
return $this;
} | php | public function set($property, $value = null)
{
if (is_string($property) && $value != '') {
$property = [$property => $value];
}
foreach ($property as $name => $value) {
$this->properties[$name] = $value;
}
return $this;
} | [
"public",
"function",
"set",
"(",
"$",
"property",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"property",
")",
"&&",
"$",
"value",
"!=",
"''",
")",
"{",
"$",
"property",
"=",
"[",
"$",
"property",
"=>",
"$",
"valu... | Sets a single property inside this entity
@param string|array $property The name of property to set or a list of
properties with their respective values
@param mixed $value The value to set to the property
@return $this
@uses $properties | [
"Sets",
"a",
"single",
"property",
"inside",
"this",
"entity"
] | 46003b05490de4b570b46c6377f1e09139ffe43b | https://github.com/mirko-pagliai/php-tools/blob/46003b05490de4b570b46c6377f1e09139ffe43b/src/Entity.php#L140-L151 | train |
hail-framework/framework | src/Database/Model.php | Model.dirty | public function dirty(array $dirty = [])
{
$this->dirty = $dirty;
$this->data = \array_merge($this->data, $dirty);
return $this;
} | php | public function dirty(array $dirty = [])
{
$this->dirty = $dirty;
$this->data = \array_merge($this->data, $dirty);
return $this;
} | [
"public",
"function",
"dirty",
"(",
"array",
"$",
"dirty",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"dirty",
"=",
"$",
"dirty",
";",
"$",
"this",
"->",
"data",
"=",
"\\",
"array_merge",
"(",
"$",
"this",
"->",
"data",
",",
"$",
"dirty",
")",
... | function to SET or RESET the dirty data.
@param array $dirty The dirty data will be set, or empty array to reset the dirty data.
@return self return $this, can using chain method calls. | [
"function",
"to",
"SET",
"or",
"RESET",
"the",
"dirty",
"data",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Model.php#L165-L171 | train |
hail-framework/framework | src/Database/Model.php | Model.get | public function get($id = null)
{
if ($id !== null) {
$this->eq($this->primary, $id);
}
$this->defaultTable();
DB::get($this->sql, PDO::FETCH_INTO, $this->reset());
return $this->dirty();
} | php | public function get($id = null)
{
if ($id !== null) {
$this->eq($this->primary, $id);
}
$this->defaultTable();
DB::get($this->sql, PDO::FETCH_INTO, $this->reset());
return $this->dirty();
} | [
"public",
"function",
"get",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"id",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"eq",
"(",
"$",
"this",
"->",
"primary",
",",
"$",
"id",
")",
";",
"}",
"$",
"this",
"->",
"defaultTable",
"... | function to find one record and assign in to current object.
@param int $id If call this function using this param, will find record by using this id. If not set, just find
the first record in database.
@return bool|self if find record, assign in to current object and return it, other wise return "false". | [
"function",
"to",
"find",
"one",
"record",
"and",
"assign",
"in",
"to",
"current",
"object",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Model.php#L188-L198 | train |
hail-framework/framework | src/Database/Model.php | Model.all | public function all()
{
$this->defaultTable();
$sql = $this->sql;
$this->reset();
return DB::select($sql, PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, static::class);
} | php | public function all()
{
$this->defaultTable();
$sql = $this->sql;
$this->reset();
return DB::select($sql, PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, static::class);
} | [
"public",
"function",
"all",
"(",
")",
"{",
"$",
"this",
"->",
"defaultTable",
"(",
")",
";",
"$",
"sql",
"=",
"$",
"this",
"->",
"sql",
";",
"$",
"this",
"->",
"reset",
"(",
")",
";",
"return",
"DB",
"::",
"select",
"(",
"$",
"sql",
",",
"PDO"... | function to find all records in database.
@return array return array of ORM | [
"function",
"to",
"find",
"all",
"records",
"in",
"database",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Model.php#L205-L212 | train |
hail-framework/framework | src/Database/Model.php | Model.delete | public function delete()
{
$this->defaultTable();
$this->eq($this->primary, $this->__get($this->primary));
return DB::delete($this->sql);
} | php | public function delete()
{
$this->defaultTable();
$this->eq($this->primary, $this->__get($this->primary));
return DB::delete($this->sql);
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"$",
"this",
"->",
"defaultTable",
"(",
")",
";",
"$",
"this",
"->",
"eq",
"(",
"$",
"this",
"->",
"primary",
",",
"$",
"this",
"->",
"__get",
"(",
"$",
"this",
"->",
"primary",
")",
")",
";",
"retur... | function to delete current record in database.
@return bool | [
"function",
"to",
"delete",
"current",
"record",
"in",
"database",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Model.php#L219-L225 | train |
hail-framework/framework | src/Database/Model.php | Model.update | public function update()
{
if ($this->dirty === []) {
return true;
}
$this->defaultTable();
$this->sql['SET'] = $this->dirty;
$this->eq($this->primary, $this->__get($this->primary));
if (DB::update($this->sql)) {
return $this->dirty()->reset();
}
return false;
} | php | public function update()
{
if ($this->dirty === []) {
return true;
}
$this->defaultTable();
$this->sql['SET'] = $this->dirty;
$this->eq($this->primary, $this->__get($this->primary));
if (DB::update($this->sql)) {
return $this->dirty()->reset();
}
return false;
} | [
"public",
"function",
"update",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"dirty",
"===",
"[",
"]",
")",
"{",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"defaultTable",
"(",
")",
";",
"$",
"this",
"->",
"sql",
"[",
"'SET'",
"]",
"=",
"$"... | function to build update SQL, and update current record in database, just write the dirty data into database.
@return bool|self if update success return current object, other wise return false. | [
"function",
"to",
"build",
"update",
"SQL",
"and",
"update",
"current",
"record",
"in",
"database",
"just",
"write",
"the",
"dirty",
"data",
"into",
"database",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Model.php#L232-L247 | train |
hail-framework/framework | src/Database/Model.php | Model.insert | public function insert()
{
if (\count($this->dirty) === 0) {
return true;
}
$this->defaultTable();
$this->sql['VALUES'] = $this->dirty;
if ($return = DB::insert($this->sql)) {
$this->__set($this->primary, $return);
return $this->dirty()->reset();
}
return false;
} | php | public function insert()
{
if (\count($this->dirty) === 0) {
return true;
}
$this->defaultTable();
$this->sql['VALUES'] = $this->dirty;
if ($return = DB::insert($this->sql)) {
$this->__set($this->primary, $return);
return $this->dirty()->reset();
}
return false;
} | [
"public",
"function",
"insert",
"(",
")",
"{",
"if",
"(",
"\\",
"count",
"(",
"$",
"this",
"->",
"dirty",
")",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"defaultTable",
"(",
")",
";",
"$",
"this",
"->",
"sql",
"[",
"'... | function to build insert SQL, and insert current record into database.
@return bool|self if insert success return current object, other wise return false. | [
"function",
"to",
"build",
"insert",
"SQL",
"and",
"insert",
"current",
"record",
"into",
"database",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Model.php#L254-L270 | train |
hail-framework/framework | src/Database/Model.php | Model.addWhere | public function addWhere($field, $value, $op = 'AND')
{
if (!isset($this->sql['WHERE'])) {
$this->sql['WHERE'] = [];
}
if (isset($this->sql['WHERE'][$op])) {
$this->sql['WHERE'][$op][$field] = $value;
} else {
$this->sql['WHERE'][$field] = $value;
$this->sql['WHERE'][$op] = $this->sql['WHERE'];
}
} | php | public function addWhere($field, $value, $op = 'AND')
{
if (!isset($this->sql['WHERE'])) {
$this->sql['WHERE'] = [];
}
if (isset($this->sql['WHERE'][$op])) {
$this->sql['WHERE'][$op][$field] = $value;
} else {
$this->sql['WHERE'][$field] = $value;
$this->sql['WHERE'][$op] = $this->sql['WHERE'];
}
} | [
"public",
"function",
"addWhere",
"(",
"$",
"field",
",",
"$",
"value",
",",
"$",
"op",
"=",
"'AND'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"sql",
"[",
"'WHERE'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"sql",
"[",
"'WHERE'"... | helper function to add condition into WHERE.
create the SQL Expressions.
@param string $field The field name, the source of Expressions
@param mixed $value the target of the Expressions
@param string $op the operator to concat this Expressions into WHERE or SET statment. | [
"helper",
"function",
"to",
"add",
"condition",
"into",
"WHERE",
".",
"create",
"the",
"SQL",
"Expressions",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Model.php#L383-L395 | train |
DoSomething/gateway | src/Northstar.php | Northstar.getUser | public function getUser($type, $id)
{
$response = $this->get('v1/users/'.$type.'/'.$id);
if (is_null($response)) {
return null;
}
return new NorthstarUser($response['data']);
} | php | public function getUser($type, $id)
{
$response = $this->get('v1/users/'.$type.'/'.$id);
if (is_null($response)) {
return null;
}
return new NorthstarUser($response['data']);
} | [
"public",
"function",
"getUser",
"(",
"$",
"type",
",",
"$",
"id",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"get",
"(",
"'v1/users/'",
".",
"$",
"type",
".",
"'/'",
".",
"$",
"id",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"response",
... | Send a GET request to return a user with that id.
@param string $type - 'id', 'email', 'mobile'
@param string $id - ID, email, id, phone
@return NorthstarUser | [
"Send",
"a",
"GET",
"request",
"to",
"return",
"a",
"user",
"with",
"that",
"id",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Northstar.php#L57-L66 | train |
DoSomething/gateway | src/Northstar.php | Northstar.updateUser | public function updateUser($id, $input)
{
$response = $this->put('v1/users/_id/'.$id, $input);
return new NorthstarUser($response['data']);
} | php | public function updateUser($id, $input)
{
$response = $this->put('v1/users/_id/'.$id, $input);
return new NorthstarUser($response['data']);
} | [
"public",
"function",
"updateUser",
"(",
"$",
"id",
",",
"$",
"input",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"put",
"(",
"'v1/users/_id/'",
".",
"$",
"id",
",",
"$",
"input",
")",
";",
"return",
"new",
"NorthstarUser",
"(",
"$",
"respons... | Send a PUT request to update a user in Northstar.
@param string $id - Northstar User ID
@param array $input - Fields to update in profile
@return mixed | [
"Send",
"a",
"PUT",
"request",
"to",
"update",
"a",
"user",
"in",
"Northstar",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Northstar.php#L89-L94 | train |
DoSomething/gateway | src/Northstar.php | Northstar.mergeUsers | public function mergeUsers($id, $duplicateId, $pretend = false)
{
$pretendParam = $pretend ? '?pretend=true' : null;
$response = $this->post('v1/users/'.$id.'/merge'.$pretendParam, ['id' => $duplicateId]);
return new NorthstarUser($response['data']);
} | php | public function mergeUsers($id, $duplicateId, $pretend = false)
{
$pretendParam = $pretend ? '?pretend=true' : null;
$response = $this->post('v1/users/'.$id.'/merge'.$pretendParam, ['id' => $duplicateId]);
return new NorthstarUser($response['data']);
} | [
"public",
"function",
"mergeUsers",
"(",
"$",
"id",
",",
"$",
"duplicateId",
",",
"$",
"pretend",
"=",
"false",
")",
"{",
"$",
"pretendParam",
"=",
"$",
"pretend",
"?",
"'?pretend=true'",
":",
"null",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"post... | Send a POST request to merge two users in Northstar.
@param string $id - Northstar User ID.
@param string $duplicateId - Northstar User ID of duplicate user.
@param bool $pretend - Whether to persist the merge or not.
@return mixed | [
"Send",
"a",
"POST",
"request",
"to",
"merge",
"two",
"users",
"in",
"Northstar",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Northstar.php#L118-L125 | train |
DoSomething/gateway | src/Northstar.php | Northstar.updateClient | public function updateClient($client_id, $input)
{
$response = $this->put('v2/clients/'.$client_id, $input);
return new NorthstarClient($response['data']);
} | php | public function updateClient($client_id, $input)
{
$response = $this->put('v2/clients/'.$client_id, $input);
return new NorthstarClient($response['data']);
} | [
"public",
"function",
"updateClient",
"(",
"$",
"client_id",
",",
"$",
"input",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"put",
"(",
"'v2/clients/'",
".",
"$",
"client_id",
",",
"$",
"input",
")",
";",
"return",
"new",
"NorthstarClient",
"(",
... | Send a POST request to generate new keys to northstar
Requires an `admin` scoped API key.
@param string $client_id - API key
@param array $input - key values
@return NorthstarClient | [
"Send",
"a",
"POST",
"request",
"to",
"generate",
"new",
"keys",
"to",
"northstar",
"Requires",
"an",
"admin",
"scoped",
"API",
"key",
"."
] | 89c1c59c6af038dff790df6d5aaa9fc703246568 | https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Northstar.php#L189-L194 | train |
hail-framework/framework | src/Http/Client/AbstractCurl.php | AbstractCurl.createHandle | protected function createHandle()
{
$curl = $this->handles ? \array_pop($this->handles) : \curl_init();
if (false === $curl) {
throw new ClientException('Unable to create a new cURL handle');
}
return $curl;
} | php | protected function createHandle()
{
$curl = $this->handles ? \array_pop($this->handles) : \curl_init();
if (false === $curl) {
throw new ClientException('Unable to create a new cURL handle');
}
return $curl;
} | [
"protected",
"function",
"createHandle",
"(",
")",
"{",
"$",
"curl",
"=",
"$",
"this",
"->",
"handles",
"?",
"\\",
"array_pop",
"(",
"$",
"this",
"->",
"handles",
")",
":",
"\\",
"curl_init",
"(",
")",
";",
"if",
"(",
"false",
"===",
"$",
"curl",
"... | Creates a new cURL resource.
@return resource A new cURL resource
@throws ClientException If unable to create a cURL resource | [
"Creates",
"a",
"new",
"cURL",
"resource",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Client/AbstractCurl.php#L38-L46 | train |
hail-framework/framework | src/Http/Client/AbstractCurl.php | AbstractCurl.prepare | protected function prepare($curl, RequestInterface $request, array $options): ResponseInterface
{
if (\defined('CURLOPT_PROTOCOLS')) {
\curl_setopt($curl, \CURLOPT_PROTOCOLS, \CURLPROTO_HTTP | \CURLPROTO_HTTPS);
\curl_setopt($curl, \CURLOPT_REDIR_PROTOCOLS, \CURLPROTO_HTTP | \CURLPROTO_HTTPS);
}
\curl_setopt($curl, \CURLOPT_HEADER, false);
\curl_setopt($curl, \CURLOPT_RETURNTRANSFER, false);
\curl_setopt($curl, \CURLOPT_FAILONERROR, false);
$this->setOptionsFromParameter($curl, $options);
$this->setOptionsFromRequest($curl, $request);
$response = Factory::response();
\curl_setopt($curl, \CURLOPT_HEADERFUNCTION, function ($ch, $data) use ($response) {
$str = \trim($data);
if ('' !== $str) {
if (0 === \stripos($str, 'http/')) {
$this->setStatus($response, $str);
} else {
$this->addHeader($response, $str);
}
}
return \strlen($data);
});
\curl_setopt($curl, \CURLOPT_WRITEFUNCTION, function ($ch, $data) use ($response) {
return $response->getBody()->write($data);
});
// apply additional options
if ($options['curl'] !== []) {
\curl_setopt_array($curl, $options['curl']);
}
return $response;
} | php | protected function prepare($curl, RequestInterface $request, array $options): ResponseInterface
{
if (\defined('CURLOPT_PROTOCOLS')) {
\curl_setopt($curl, \CURLOPT_PROTOCOLS, \CURLPROTO_HTTP | \CURLPROTO_HTTPS);
\curl_setopt($curl, \CURLOPT_REDIR_PROTOCOLS, \CURLPROTO_HTTP | \CURLPROTO_HTTPS);
}
\curl_setopt($curl, \CURLOPT_HEADER, false);
\curl_setopt($curl, \CURLOPT_RETURNTRANSFER, false);
\curl_setopt($curl, \CURLOPT_FAILONERROR, false);
$this->setOptionsFromParameter($curl, $options);
$this->setOptionsFromRequest($curl, $request);
$response = Factory::response();
\curl_setopt($curl, \CURLOPT_HEADERFUNCTION, function ($ch, $data) use ($response) {
$str = \trim($data);
if ('' !== $str) {
if (0 === \stripos($str, 'http/')) {
$this->setStatus($response, $str);
} else {
$this->addHeader($response, $str);
}
}
return \strlen($data);
});
\curl_setopt($curl, \CURLOPT_WRITEFUNCTION, function ($ch, $data) use ($response) {
return $response->getBody()->write($data);
});
// apply additional options
if ($options['curl'] !== []) {
\curl_setopt_array($curl, $options['curl']);
}
return $response;
} | [
"protected",
"function",
"prepare",
"(",
"$",
"curl",
",",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
")",
":",
"ResponseInterface",
"{",
"if",
"(",
"\\",
"defined",
"(",
"'CURLOPT_PROTOCOLS'",
")",
")",
"{",
"\\",
"curl_setopt",
"(",
... | Prepares a cURL resource to send a request.
@param resource $curl
@param RequestInterface $request
@param array $options
@return ResponseInterface | [
"Prepares",
"a",
"cURL",
"resource",
"to",
"send",
"a",
"request",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Client/AbstractCurl.php#L83-L121 | train |
hiqdev/hipanel-module-server | src/controllers/ServerController.php | ServerController.getVNCInfo | public function getVNCInfo($model, $enable = false)
{
if ($enable) {
try {
$vnc = Server::perform('enable-VNC', ['id' => $model->id]);
$vnc['endTime'] = time() + 28800;
Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
$vnc['enabled'] = true;
} catch (ResponseErrorException $e) {
if ($e->getMessage() !== 'vds_has_tasks') {
throw $e;
}
}
} else {
if ($model->statuses['serverEnableVNC'] !== null && strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time()) {
$vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
return ArrayHelper::merge([
'endTime' => strtotime($model->statuses['serverEnableVNC']) + 28800,
], Server::perform('enable-VNC', ['id' => $model->id]));
}, 28800);
}
$vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
}
return $vnc;
} | php | public function getVNCInfo($model, $enable = false)
{
if ($enable) {
try {
$vnc = Server::perform('enable-VNC', ['id' => $model->id]);
$vnc['endTime'] = time() + 28800;
Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
$vnc['enabled'] = true;
} catch (ResponseErrorException $e) {
if ($e->getMessage() !== 'vds_has_tasks') {
throw $e;
}
}
} else {
if ($model->statuses['serverEnableVNC'] !== null && strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time()) {
$vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
return ArrayHelper::merge([
'endTime' => strtotime($model->statuses['serverEnableVNC']) + 28800,
], Server::perform('enable-VNC', ['id' => $model->id]));
}, 28800);
}
$vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
}
return $vnc;
} | [
"public",
"function",
"getVNCInfo",
"(",
"$",
"model",
",",
"$",
"enable",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"enable",
")",
"{",
"try",
"{",
"$",
"vnc",
"=",
"Server",
"::",
"perform",
"(",
"'enable-VNC'",
",",
"[",
"'id'",
"=>",
"$",
"model"... | Gets info of VNC on the server.
@param Server $model
@param bool $enable
@throws ResponseErrorException
@return array | [
"Gets",
"info",
"of",
"VNC",
"on",
"the",
"server",
"."
] | e40c3601952cf1fd420ebb97093ee17a33ff3207 | https://github.com/hiqdev/hipanel-module-server/blob/e40c3601952cf1fd420ebb97093ee17a33ff3207/src/controllers/ServerController.php#L829-L854 | train |
hiqdev/hipanel-module-server | src/controllers/ServerController.php | ServerController.getOsimages | protected function getOsimages(Server $model = null)
{
if ($model !== null) {
$type = $model->type;
} else {
$type = null;
}
$models = ServerHelper::getOsimages($type);
if ($models === null) {
throw new NotFoundHttpException('The requested page does not exist.');
}
return $models;
} | php | protected function getOsimages(Server $model = null)
{
if ($model !== null) {
$type = $model->type;
} else {
$type = null;
}
$models = ServerHelper::getOsimages($type);
if ($models === null) {
throw new NotFoundHttpException('The requested page does not exist.');
}
return $models;
} | [
"protected",
"function",
"getOsimages",
"(",
"Server",
"$",
"model",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"model",
"!==",
"null",
")",
"{",
"$",
"type",
"=",
"$",
"model",
"->",
"type",
";",
"}",
"else",
"{",
"$",
"type",
"=",
"null",
";",
"}",... | Gets OS images.
@param Server $model
@throws NotFoundHttpException
@return array | [
"Gets",
"OS",
"images",
"."
] | e40c3601952cf1fd420ebb97093ee17a33ff3207 | https://github.com/hiqdev/hipanel-module-server/blob/e40c3601952cf1fd420ebb97093ee17a33ff3207/src/controllers/ServerController.php#L887-L902 | train |
hail-framework/framework | src/Http/Cookie.php | Cookie.getExpiresTime | private function getExpiresTime($time): int
{
if ($time instanceof \DateTimeInterface) {
return (int) $time->format('U');
}
if (\is_numeric($time)) {
// average year in seconds
if ($time <= 31557600) {
$time += \time();
}
return (int) $time;
}
return (int) (new \DateTime($time))->format('U');
} | php | private function getExpiresTime($time): int
{
if ($time instanceof \DateTimeInterface) {
return (int) $time->format('U');
}
if (\is_numeric($time)) {
// average year in seconds
if ($time <= 31557600) {
$time += \time();
}
return (int) $time;
}
return (int) (new \DateTime($time))->format('U');
} | [
"private",
"function",
"getExpiresTime",
"(",
"$",
"time",
")",
":",
"int",
"{",
"if",
"(",
"$",
"time",
"instanceof",
"\\",
"DateTimeInterface",
")",
"{",
"return",
"(",
"int",
")",
"$",
"time",
"->",
"format",
"(",
"'U'",
")",
";",
"}",
"if",
"(",
... | Convert to unix timestamp
@param string|int|\DateTimeInterface $time
@return int | [
"Convert",
"to",
"unix",
"timestamp"
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Cookie.php#L188-L204 | train |
hail-framework/framework | src/Container/Container.php | Container.get | public function get($name)
{
switch (true) {
case isset($this->active[$name]):
return $this->values[$name];
case isset($this->values[$name]):
break;
case \array_key_exists($name, $this->values):
break;
case isset($this->alias[$name]):
$this->active[$name] = true;
return $this->values[$name] = $this->get($this->alias[$name]);
case isset($this->factory[$name]):
$factory = $this->factory[$name];
if (\is_string($factory) && \class_exists($factory)) {
$this->values[$name] = $this->create($factory, $this->factoryMap[$name]);
} else {
$this->values[$name] = $this->call($factory, $this->factoryMap[$name]);
}
break;
case \class_exists($name):
return $this->build($name);
default:
throw new NotFoundException($name);
}
$this->active[$name] = true;
if (null !== $configures = $this->getConfigure($name)) {
foreach ($configures as $index => $config) {
$value = $this->call($config, $this->configMap[$name][$index]);
if ($value !== null) {
$this->values[$name] = $value;
}
}
}
return $this->values[$name];
} | php | public function get($name)
{
switch (true) {
case isset($this->active[$name]):
return $this->values[$name];
case isset($this->values[$name]):
break;
case \array_key_exists($name, $this->values):
break;
case isset($this->alias[$name]):
$this->active[$name] = true;
return $this->values[$name] = $this->get($this->alias[$name]);
case isset($this->factory[$name]):
$factory = $this->factory[$name];
if (\is_string($factory) && \class_exists($factory)) {
$this->values[$name] = $this->create($factory, $this->factoryMap[$name]);
} else {
$this->values[$name] = $this->call($factory, $this->factoryMap[$name]);
}
break;
case \class_exists($name):
return $this->build($name);
default:
throw new NotFoundException($name);
}
$this->active[$name] = true;
if (null !== $configures = $this->getConfigure($name)) {
foreach ($configures as $index => $config) {
$value = $this->call($config, $this->configMap[$name][$index]);
if ($value !== null) {
$this->values[$name] = $value;
}
}
}
return $this->values[$name];
} | [
"public",
"function",
"get",
"(",
"$",
"name",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"isset",
"(",
"$",
"this",
"->",
"active",
"[",
"$",
"name",
"]",
")",
":",
"return",
"$",
"this",
"->",
"values",
"[",
"$",
"name",
"]",
";",
"ca... | Resolve the registered component with the given name.
@param string $name component name
@return mixed
@throws NotFoundException
@throws InvalidArgumentException | [
"Resolve",
"the",
"registered",
"component",
"with",
"the",
"given",
"name",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Container.php#L90-L138 | train |
hail-framework/framework | src/Container/Container.php | Container.has | public function has($name): bool
{
return isset($this->values[$name]) ||
isset($this->factory[$name]) ||
isset($this->alias[$name]) ||
\array_key_exists($name, $this->values);
} | php | public function has($name): bool
{
return isset($this->values[$name]) ||
isset($this->factory[$name]) ||
isset($this->alias[$name]) ||
\array_key_exists($name, $this->values);
} | [
"public",
"function",
"has",
"(",
"$",
"name",
")",
":",
"bool",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"name",
"]",
")",
"||",
"isset",
"(",
"$",
"this",
"->",
"factory",
"[",
"$",
"name",
"]",
")",
"||",
"isset",
... | Check for the existence of a component with a given name.
@param string $name component name
@return bool true, if a component with the given name has been defined | [
"Check",
"for",
"the",
"existence",
"of",
"a",
"component",
"with",
"a",
"given",
"name",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Container.php#L148-L154 | train |
hail-framework/framework | src/Container/Container.php | Container.inject | public function inject(string $name, $value): void
{
if ($this->has($name)) {
throw new InvalidArgumentException("Attempted override of existing component: {$name}");
}
$this->values[$name] = $value;
$this->active[$name] = true;
} | php | public function inject(string $name, $value): void
{
if ($this->has($name)) {
throw new InvalidArgumentException("Attempted override of existing component: {$name}");
}
$this->values[$name] = $value;
$this->active[$name] = true;
} | [
"public",
"function",
"inject",
"(",
"string",
"$",
"name",
",",
"$",
"value",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Attempted override of existing c... | Dynamically inject a component into this Container.
Enables implementation of "auto-wiring" patterns, where missing components are injected
at run-time into a live `Container` instance.
You should always test with {@see has()} prior to injecting a component - attempting to
override an existing component will generate an exception.
@throws InvalidArgumentException if the specified component has already been defined
@param string $name component name
@param mixed $value | [
"Dynamically",
"inject",
"a",
"component",
"into",
"this",
"Container",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Container.php#L211-L219 | train |
hail-framework/framework | src/Container/Container.php | Container.register | public function register(string $name, $define = null, array $map = []): void
{
if (isset($this->active[$name])) {
throw new InvalidArgumentException("Attempted override of existing component: {$name}");
}
if ($define instanceof \Closure) {
$func = $define;
} elseif (\is_callable($define)) {
// second argument is a creation function
$func = \Closure::fromCallable($define);
} elseif (\is_string($define)) {
// second argument is a class-name
$func = $define;
} elseif (\is_array($define)) {
$func = $name;
$map = $define;
} elseif (null === $define) {
// first argument is both the component and class-name
$func = $name;
$map = [];
} else {
throw new InvalidArgumentException('Unexpected argument type for $define: ' . \gettype($define));
}
$this->factory[$name] = $func;
$this->factoryMap[$name] = $map;
unset($this->values[$name]);
} | php | public function register(string $name, $define = null, array $map = []): void
{
if (isset($this->active[$name])) {
throw new InvalidArgumentException("Attempted override of existing component: {$name}");
}
if ($define instanceof \Closure) {
$func = $define;
} elseif (\is_callable($define)) {
// second argument is a creation function
$func = \Closure::fromCallable($define);
} elseif (\is_string($define)) {
// second argument is a class-name
$func = $define;
} elseif (\is_array($define)) {
$func = $name;
$map = $define;
} elseif (null === $define) {
// first argument is both the component and class-name
$func = $name;
$map = [];
} else {
throw new InvalidArgumentException('Unexpected argument type for $define: ' . \gettype($define));
}
$this->factory[$name] = $func;
$this->factoryMap[$name] = $map;
unset($this->values[$name]);
} | [
"public",
"function",
"register",
"(",
"string",
"$",
"name",
",",
"$",
"define",
"=",
"null",
",",
"array",
"$",
"map",
"=",
"[",
"]",
")",
":",
"void",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"active",
"[",
"$",
"name",
"]",
")",
")"... | Register a component for dependency injection.
There are numerous valid ways to register components.
* `register(Foo::class)` registers a component by it's class-name, and will try to
automatically resolve all of it's constructor arguments.
* `register(Foo::class, ['bar'])` registers a component by it's class-name, and will
use `'bar'` as the first constructor argument, and try to resolve the rest.
* `register(Foo::class, [$container->ref(Bar::class)])` creates a boxed reference to
a registered component `Bar` and provides that as the first argument.
* `register(Foo::class, ['bat' => 'zap'])` registers a component by it's class-name
and will use `'zap'` for the constructor argument named `$bat`, and try to resolve
any other arguments.
* `register(Bar::class, Foo::class)` registers a component `Foo` under another name
`Bar`, which might be an interface or an abstract class.
* `register(Bar::class, Foo::class, ['bar'])` same as above, but uses `'bar'` as the
first argument.
* `register(Bar::class, Foo::class, ['bat' => 'zap'])` same as above, but, well, guess.
* `register(Bar::class, function (Foo $foo) { return new Bar(...); })` registers a
component with a custom creation function.
* `register(Bar::class, function ($name) { ... }, [$container->ref('db.name')]);`
registers a component creation function with a reference to a component "db.name"
as the first argument.
In effect, you can think of `$func` as being an optional argument.
The provided parameter values may include any `\Closure`, such as the boxed
component referenced created by {@see Container::ref()} - these will be unboxed as late
as possible.
@param string $name component name
@param callable|mixed|mixed[]|null $define creation function or class-name, or, if the first
argument is a class-name, a map of constructor arguments
@param array $map mixed list/map of parameter values (and/or boxed values)
@return void
@throws InvalidArgumentException | [
"Register",
"a",
"component",
"for",
"dependency",
"injection",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Container.php#L294-L323 | train |
hail-framework/framework | src/Container/Container.php | Container.set | public function set(string $name, $value): void
{
if (isset($this->active[$name])) {
throw new InvalidArgumentException("Attempted override of existing component: {$name}");
}
$this->values[$name] = $value;
unset(
$this->factory[$name],
$this->factoryMap[$name],
$this->alias[$name]
);
$this->removeAbstractAlias($name);
} | php | public function set(string $name, $value): void
{
if (isset($this->active[$name])) {
throw new InvalidArgumentException("Attempted override of existing component: {$name}");
}
$this->values[$name] = $value;
unset(
$this->factory[$name],
$this->factoryMap[$name],
$this->alias[$name]
);
$this->removeAbstractAlias($name);
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"name",
",",
"$",
"value",
")",
":",
"void",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"active",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Attempt... | Directly inject a component into the container - use this to register components that
have already been created for some reason; for example, the Composer ClassLoader.
@param string $name component name
@param mixed $value
@return void
@throws InvalidArgumentException | [
"Directly",
"inject",
"a",
"component",
"into",
"the",
"container",
"-",
"use",
"this",
"to",
"register",
"components",
"that",
"have",
"already",
"been",
"created",
"for",
"some",
"reason",
";",
"for",
"example",
"the",
"Composer",
"ClassLoader",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Container.php#L336-L351 | train |
hail-framework/framework | src/Container/Container.php | Container.alias | public function alias(string $alias, string $abstract): void
{
if (\array_key_exists($alias, $this->values) || isset($this->factory[$alias])) {
throw new InvalidArgumentException("Already defined in container: $alias");
}
if ($alias === $abstract) {
throw new InvalidArgumentException('Alias cannot be the same as the original name');
}
$this->alias[$alias] = $abstract;
if (!isset($this->abstractAlias[$abstract])) {
$this->abstractAlias[$abstract] = [];
}
$this->abstractAlias[$abstract][] = $alias;
} | php | public function alias(string $alias, string $abstract): void
{
if (\array_key_exists($alias, $this->values) || isset($this->factory[$alias])) {
throw new InvalidArgumentException("Already defined in container: $alias");
}
if ($alias === $abstract) {
throw new InvalidArgumentException('Alias cannot be the same as the original name');
}
$this->alias[$alias] = $abstract;
if (!isset($this->abstractAlias[$abstract])) {
$this->abstractAlias[$abstract] = [];
}
$this->abstractAlias[$abstract][] = $alias;
} | [
"public",
"function",
"alias",
"(",
"string",
"$",
"alias",
",",
"string",
"$",
"abstract",
")",
":",
"void",
"{",
"if",
"(",
"\\",
"array_key_exists",
"(",
"$",
"alias",
",",
"$",
"this",
"->",
"values",
")",
"||",
"isset",
"(",
"$",
"this",
"->",
... | Register a component as an alias of another registered component.
@param string $alias new component name
@param string $abstract referenced existing component name
@throws InvalidArgumentException | [
"Register",
"a",
"component",
"as",
"an",
"alias",
"of",
"another",
"registered",
"component",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Container.php#L361-L378 | train |
hail-framework/framework | src/Container/Container.php | Container.ref | public function ref(string $name)
{
if (isset($this->active[$name])) {
return $this->values[$name];
}
return function () use ($name) {
return $this->get($name);
};
} | php | public function ref(string $name)
{
if (isset($this->active[$name])) {
return $this->values[$name];
}
return function () use ($name) {
return $this->get($name);
};
} | [
"public",
"function",
"ref",
"(",
"string",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"active",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"values",
"[",
"$",
"name",
"]",
";",
"}",
"return",
"fu... | Creates a boxed reference to a component with a given name.
You can use this in conjunction with `register()` to provide a component reference
without expanding that reference until first use - for example:
$container->register(UserRepo::class, [$container->ref('cache')]);
This will reference the "cache" component and provide it as the first argument to the
constructor of `UserRepo` - compared with using `$container->get('cache')`, this has
the advantage of not actually activating the "cache" component until `UserRepo` is
used for the first time.
Another reason (besides performance) to use references, is to defer the reference:
$container->register(FileCache::class, ['root_path' => $container->ref('cache.path')]);
In this example, the component "cache.path" will be fetched from the container on
first use of `FileCache`, giving you a chance to configure "cache.path" later.
@param string $name component name
@return mixed|\Closure component reference | [
"Creates",
"a",
"boxed",
"reference",
"to",
"a",
"component",
"with",
"a",
"given",
"name",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Container.php#L514-L523 | train |
hail-framework/framework | src/Filesystem/Adapter/Polyfill/StreamedReadingTrait.php | StreamedReadingTrait.readStream | public function readStream($path)
{
if ( ! $data = $this->read($path)) {
return false;
}
$stream = \fopen('php://temp', 'w+b');
\fwrite($stream, $data['contents']);
\rewind($stream);
$data['stream'] = $stream;
unset($data['contents']);
return $data;
} | php | public function readStream($path)
{
if ( ! $data = $this->read($path)) {
return false;
}
$stream = \fopen('php://temp', 'w+b');
\fwrite($stream, $data['contents']);
\rewind($stream);
$data['stream'] = $stream;
unset($data['contents']);
return $data;
} | [
"public",
"function",
"readStream",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"$",
"data",
"=",
"$",
"this",
"->",
"read",
"(",
"$",
"path",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"stream",
"=",
"\\",
"fopen",
"(",
"'php://temp'",
","... | Reads a file as a stream.
@param string $path
@return array|false
@see \Hail\Filesystem\ReadInterface::readStream() | [
"Reads",
"a",
"file",
"as",
"a",
"stream",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Polyfill/StreamedReadingTrait.php#L19-L32 | train |
hail-framework/framework | src/Filesystem/Adapter/AbstractFtpAdapter.php | AbstractFtpAdapter.sortListing | protected function sortListing(array $result)
{
$compare = function ($one, $two) {
return \strnatcmp($one['path'], $two['path']);
};
\usort($result, $compare);
return $result;
} | php | protected function sortListing(array $result)
{
$compare = function ($one, $two) {
return \strnatcmp($one['path'], $two['path']);
};
\usort($result, $compare);
return $result;
} | [
"protected",
"function",
"sortListing",
"(",
"array",
"$",
"result",
")",
"{",
"$",
"compare",
"=",
"function",
"(",
"$",
"one",
",",
"$",
"two",
")",
"{",
"return",
"\\",
"strnatcmp",
"(",
"$",
"one",
"[",
"'path'",
"]",
",",
"$",
"two",
"[",
"'pa... | Sort a directory listing.
@param array $result
@return array sorted listing | [
"Sort",
"a",
"directory",
"listing",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/AbstractFtpAdapter.php#L324-L333 | train |
jormin/aliyun | sdk/aliyun-mns-php-sdk/AliyunMNS/Http/HttpClient.php | HttpClient.parseEndpoint | private function parseEndpoint()
{
$pieces = explode("//", $this->endpoint);
$host = end($pieces);
$host_pieces = explode(".", $host);
$this->accountId = $host_pieces[0];
$region_pieces = explode("-internal", $host_pieces[2]);
$this->region = $region_pieces[0];
} | php | private function parseEndpoint()
{
$pieces = explode("//", $this->endpoint);
$host = end($pieces);
$host_pieces = explode(".", $host);
$this->accountId = $host_pieces[0];
$region_pieces = explode("-internal", $host_pieces[2]);
$this->region = $region_pieces[0];
} | [
"private",
"function",
"parseEndpoint",
"(",
")",
"{",
"$",
"pieces",
"=",
"explode",
"(",
"\"//\"",
",",
"$",
"this",
"->",
"endpoint",
")",
";",
"$",
"host",
"=",
"end",
"(",
"$",
"pieces",
")",
";",
"$",
"host_pieces",
"=",
"explode",
"(",
"\".\""... | This function is for SDK internal use | [
"This",
"function",
"is",
"for",
"SDK",
"internal",
"use"
] | c0eb19f5c265dba1f463af1db7347acdcfddb240 | https://github.com/jormin/aliyun/blob/c0eb19f5c265dba1f463af1db7347acdcfddb240/sdk/aliyun-mns-php-sdk/AliyunMNS/Http/HttpClient.php#L64-L73 | train |
Kajna/K-Core | Core/Auth/Auth.php | Auth.changePassword | public function changePassword($username, $newPass)
{
$password = $this->hasher->HashPassword($newPass);
return $this
->conn
->prepare(sprintf("UPDATE %s SET user_pass=:newPass WHERE user_name = :username", $this->table))
->execute(['newPass' => $password, 'username' => $username]);
} | php | public function changePassword($username, $newPass)
{
$password = $this->hasher->HashPassword($newPass);
return $this
->conn
->prepare(sprintf("UPDATE %s SET user_pass=:newPass WHERE user_name = :username", $this->table))
->execute(['newPass' => $password, 'username' => $username]);
} | [
"public",
"function",
"changePassword",
"(",
"$",
"username",
",",
"$",
"newPass",
")",
"{",
"$",
"password",
"=",
"$",
"this",
"->",
"hasher",
"->",
"HashPassword",
"(",
"$",
"newPass",
")",
";",
"return",
"$",
"this",
"->",
"conn",
"->",
"prepare",
"... | Change user password.
@param string $username
@param string $newPass
@return bool | [
"Change",
"user",
"password",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Auth/Auth.php#L112-L119 | train |
Kajna/K-Core | Core/Auth/Auth.php | Auth.login | public function login($username, $password)
{
$stmt = $this->conn->prepare(
sprintf("SELECT user_id, user_name, user_pass
FROM %s WHERE user_name = :name LIMIT 1", $this->table));
$stmt->execute(['name' => $username]);
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
if ($result['user_name'] !== $username) {
return false;
}
if ($this->hasher->CheckPassword($password, $result['user_pass'])) {
// Clear previous session
$this->session->regenerate();
// Write new data to session
$data = [
'id' => $result['user_id'],
'logged_' . $this->table => true
];
$this->session->set('user', $data);
return true;
}
return false;
} | php | public function login($username, $password)
{
$stmt = $this->conn->prepare(
sprintf("SELECT user_id, user_name, user_pass
FROM %s WHERE user_name = :name LIMIT 1", $this->table));
$stmt->execute(['name' => $username]);
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
if ($result['user_name'] !== $username) {
return false;
}
if ($this->hasher->CheckPassword($password, $result['user_pass'])) {
// Clear previous session
$this->session->regenerate();
// Write new data to session
$data = [
'id' => $result['user_id'],
'logged_' . $this->table => true
];
$this->session->set('user', $data);
return true;
}
return false;
} | [
"public",
"function",
"login",
"(",
"$",
"username",
",",
"$",
"password",
")",
"{",
"$",
"stmt",
"=",
"$",
"this",
"->",
"conn",
"->",
"prepare",
"(",
"sprintf",
"(",
"\"SELECT user_id, user_name, user_pass\n\t\t\tFROM %s WHERE user_name = :name LIMIT 1\"",
",",
"$... | Try to login user with passed parameters.
@param string $username
@param string $password
@return bool | [
"Try",
"to",
"login",
"user",
"with",
"passed",
"parameters",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Auth/Auth.php#L143-L168 | train |
Kajna/K-Core | Core/Auth/Auth.php | Auth.isLogged | public function isLogged()
{
$user = $this->session->get('user');
if (isset($user['logged_' . $this->table])
&& $user['logged_' . $this->table] === true
) {
return true;
}
return false;
} | php | public function isLogged()
{
$user = $this->session->get('user');
if (isset($user['logged_' . $this->table])
&& $user['logged_' . $this->table] === true
) {
return true;
}
return false;
} | [
"public",
"function",
"isLogged",
"(",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"session",
"->",
"get",
"(",
"'user'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"user",
"[",
"'logged_'",
".",
"$",
"this",
"->",
"table",
"]",
")",
"&&",
"$",
... | Check if there is logged user.
@return bool | [
"Check",
"if",
"there",
"is",
"logged",
"user",
"."
] | 6a354056cf95e471b9b1eb372c5626123fd77df2 | https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Auth/Auth.php#L213-L222 | train |
hail-framework/framework | src/I18n/Gettext/Translator.php | Translator.addTranslations | protected function addTranslations(array $translations)
{
$domain = $translations['domain'] ?? '';
//Set the first domain loaded as default domain
if ($this->domain === null) {
$this->domain = $domain;
}
if (isset($this->dictionary[$domain])) {
$this->dictionary[$domain] = \array_replace_recursive($this->dictionary[$domain], $translations['messages']);
return;
}
if (!empty($translations['plural-forms'])) {
[$count, $code] = \array_map('trim', \explode(';', $translations['plural-forms'], 2));
// extract just the expression turn 'n' into a php variable '$n'.
// Slap on a return keyword and semicolon at the end.
$this->plurals[$domain] = [
'count' => (int) \str_replace('nplurals=', '', $count),
'code' => \str_replace('plural=', 'return ', \str_replace('n', '$n', $code)).';',
];
}
$this->dictionary[$domain] = $translations['messages'];
} | php | protected function addTranslations(array $translations)
{
$domain = $translations['domain'] ?? '';
//Set the first domain loaded as default domain
if ($this->domain === null) {
$this->domain = $domain;
}
if (isset($this->dictionary[$domain])) {
$this->dictionary[$domain] = \array_replace_recursive($this->dictionary[$domain], $translations['messages']);
return;
}
if (!empty($translations['plural-forms'])) {
[$count, $code] = \array_map('trim', \explode(';', $translations['plural-forms'], 2));
// extract just the expression turn 'n' into a php variable '$n'.
// Slap on a return keyword and semicolon at the end.
$this->plurals[$domain] = [
'count' => (int) \str_replace('nplurals=', '', $count),
'code' => \str_replace('plural=', 'return ', \str_replace('n', '$n', $code)).';',
];
}
$this->dictionary[$domain] = $translations['messages'];
} | [
"protected",
"function",
"addTranslations",
"(",
"array",
"$",
"translations",
")",
"{",
"$",
"domain",
"=",
"$",
"translations",
"[",
"'domain'",
"]",
"??",
"''",
";",
"//Set the first domain loaded as default domain",
"if",
"(",
"$",
"this",
"->",
"domain",
"=... | Set new translations to the dictionary.
@param array $translations | [
"Set",
"new",
"translations",
"to",
"the",
"dictionary",
"."
] | d419e6c098d29ef9b62192b74050e51985b94f90 | https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Translator.php#L179-L206 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.