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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
thecodingmachine/mouf | src-dev/Mouf/Controllers/ConfigController.php | ConfigController.register | public function register($name = null, $defaultvalue = null, $value = null, $type = null, $comment = null, $fetchFromEnv = null, $selfedit = "false") {
$this->selfedit = $selfedit;
if ($selfedit == "true") {
$this->moufManager = MoufManager::getMoufManager();
} else {
$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
}
$this->configManager = $this->moufManager->getConfigManager();
$this->name = $name;
$this->defaultvalue = $defaultvalue;
$this->value = $value;
$this->type = $type;
$this->comment = $comment;
$this->fetchFromEnv = $fetchFromEnv;
if ($name != null) {
$def = $this->configManager->getConstantDefinition($name);
if ($def != null) {
if ($this->comment == null) {
$this->comment = $def['comment'];
}
if ($this->defaultvalue == null) {
$this->defaultvalue = $def['defaultValue'];
}
if ($this->type == null) {
$this->type = $def['type'];
}
if ($this->fetchFromEnv === null && isset($def['fetchFromEnv'])) {
$this->fetchFromEnv = $def['fetchFromEnv'];
}
}
if ($this->value == null) {
$constants = $this->configManager->getDefinedConstants();
if (isset($constants[$name])) {
$this->value = $constants[$name];
}
}
} else {
$this->fetchFromEnv = true;
}
// TODO: manage type!
//$this->type = $comment;
$this->contentBlock->addFile(ROOT_PATH."src-dev/views/constants/registerConstant.php", $this);
$this->template->toHtml();
} | php | public function register($name = null, $defaultvalue = null, $value = null, $type = null, $comment = null, $fetchFromEnv = null, $selfedit = "false") {
$this->selfedit = $selfedit;
if ($selfedit == "true") {
$this->moufManager = MoufManager::getMoufManager();
} else {
$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
}
$this->configManager = $this->moufManager->getConfigManager();
$this->name = $name;
$this->defaultvalue = $defaultvalue;
$this->value = $value;
$this->type = $type;
$this->comment = $comment;
$this->fetchFromEnv = $fetchFromEnv;
if ($name != null) {
$def = $this->configManager->getConstantDefinition($name);
if ($def != null) {
if ($this->comment == null) {
$this->comment = $def['comment'];
}
if ($this->defaultvalue == null) {
$this->defaultvalue = $def['defaultValue'];
}
if ($this->type == null) {
$this->type = $def['type'];
}
if ($this->fetchFromEnv === null && isset($def['fetchFromEnv'])) {
$this->fetchFromEnv = $def['fetchFromEnv'];
}
}
if ($this->value == null) {
$constants = $this->configManager->getDefinedConstants();
if (isset($constants[$name])) {
$this->value = $constants[$name];
}
}
} else {
$this->fetchFromEnv = true;
}
// TODO: manage type!
//$this->type = $comment;
$this->contentBlock->addFile(ROOT_PATH."src-dev/views/constants/registerConstant.php", $this);
$this->template->toHtml();
} | [
"public",
"function",
"register",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"defaultvalue",
"=",
"null",
",",
"$",
"value",
"=",
"null",
",",
"$",
"type",
"=",
"null",
",",
"$",
"comment",
"=",
"null",
",",
"$",
"fetchFromEnv",
"=",
"null",
",",
"$"... | Displays the screen to register a constant definition.
@Action
@Logged
@param string $name
@param string $selfedit | [
"Displays",
"the",
"screen",
"to",
"register",
"a",
"constant",
"definition",
"."
] | b6a11bfd4a93859c1014d5b3d54ee99314f5fc7b | https://github.com/thecodingmachine/mouf/blob/b6a11bfd4a93859c1014d5b3d54ee99314f5fc7b/src-dev/Mouf/Controllers/ConfigController.php#L135-L184 | train |
thecodingmachine/mouf | src-dev/Mouf/Controllers/ConfigController.php | ConfigController.registerConstant | public function registerConstant($name, $comment, $type, $defaultvalue = "", $value = "", $selfedit = "false", $fetchFromEnv = "false") {
$this->selfedit = $selfedit;
if ($selfedit == "true") {
$this->moufManager = MoufManager::getMoufManager();
} else {
$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
}
$this->configManager = $this->moufManager->getConfigManager();
if ($type == "int") {
$value = $value !== '' ? (int) $value : '';
$defaultvalue = $defaultvalue !== '' ? (int) $defaultvalue : '';
} else if ($type == "float") {
$value = (float) $value;
$defaultvalue = (float) $defaultvalue;
} else if ($type == "bool") {
if ($value == "true") {
$value = true;
} else {
$value = false;
}
if ($defaultvalue == "true") {
$defaultvalue = true;
} else {
$defaultvalue = false;
}
}
$this->configManager->registerConstant($name, $type, $defaultvalue, $comment, $fetchFromEnv === 'true');
$this->moufManager->rewriteMouf();
// Now, let's write the constant for our environment:
$this->constantsList = $this->configManager->getDefinedConstants();
$this->constantsList[$name] = $value;
$this->configManager->setDefinedConstants($this->constantsList);
header("Location: .?selfedit=".$selfedit);
} | php | public function registerConstant($name, $comment, $type, $defaultvalue = "", $value = "", $selfedit = "false", $fetchFromEnv = "false") {
$this->selfedit = $selfedit;
if ($selfedit == "true") {
$this->moufManager = MoufManager::getMoufManager();
} else {
$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
}
$this->configManager = $this->moufManager->getConfigManager();
if ($type == "int") {
$value = $value !== '' ? (int) $value : '';
$defaultvalue = $defaultvalue !== '' ? (int) $defaultvalue : '';
} else if ($type == "float") {
$value = (float) $value;
$defaultvalue = (float) $defaultvalue;
} else if ($type == "bool") {
if ($value == "true") {
$value = true;
} else {
$value = false;
}
if ($defaultvalue == "true") {
$defaultvalue = true;
} else {
$defaultvalue = false;
}
}
$this->configManager->registerConstant($name, $type, $defaultvalue, $comment, $fetchFromEnv === 'true');
$this->moufManager->rewriteMouf();
// Now, let's write the constant for our environment:
$this->constantsList = $this->configManager->getDefinedConstants();
$this->constantsList[$name] = $value;
$this->configManager->setDefinedConstants($this->constantsList);
header("Location: .?selfedit=".$selfedit);
} | [
"public",
"function",
"registerConstant",
"(",
"$",
"name",
",",
"$",
"comment",
",",
"$",
"type",
",",
"$",
"defaultvalue",
"=",
"\"\"",
",",
"$",
"value",
"=",
"\"\"",
",",
"$",
"selfedit",
"=",
"\"false\"",
",",
"$",
"fetchFromEnv",
"=",
"\"false\"",
... | Actually saves the new constant declared.
@Action
@Logged
@param string $name
@param string $defaultvalue
@param string $value
@param string $comment
@param string $type
@param string $selfedit | [
"Actually",
"saves",
"the",
"new",
"constant",
"declared",
"."
] | b6a11bfd4a93859c1014d5b3d54ee99314f5fc7b | https://github.com/thecodingmachine/mouf/blob/b6a11bfd4a93859c1014d5b3d54ee99314f5fc7b/src-dev/Mouf/Controllers/ConfigController.php#L198-L236 | train |
thecodingmachine/mouf | src-dev/Mouf/Controllers/ConfigController.php | ConfigController.deleteConstant | public function deleteConstant($name, $selfedit = "false") {
$this->selfedit = $selfedit;
if ($selfedit == "true") {
$this->moufManager = MoufManager::getMoufManager();
} else {
$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
}
$this->configManager = $this->moufManager->getConfigManager();
$this->configManager->unregisterConstant($name);
$this->moufManager->rewriteMouf();
// Now, let's write the constant for our environment:
$this->constantsList = $this->configManager->getDefinedConstants();
unset($this->constantsList[$name]);
$this->configManager->setDefinedConstants($this->constantsList);
header("Location: .?selfedit=".$selfedit);
} | php | public function deleteConstant($name, $selfedit = "false") {
$this->selfedit = $selfedit;
if ($selfedit == "true") {
$this->moufManager = MoufManager::getMoufManager();
} else {
$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
}
$this->configManager = $this->moufManager->getConfigManager();
$this->configManager->unregisterConstant($name);
$this->moufManager->rewriteMouf();
// Now, let's write the constant for our environment:
$this->constantsList = $this->configManager->getDefinedConstants();
unset($this->constantsList[$name]);
$this->configManager->setDefinedConstants($this->constantsList);
header("Location: .?selfedit=".$selfedit);
} | [
"public",
"function",
"deleteConstant",
"(",
"$",
"name",
",",
"$",
"selfedit",
"=",
"\"false\"",
")",
"{",
"$",
"this",
"->",
"selfedit",
"=",
"$",
"selfedit",
";",
"if",
"(",
"$",
"selfedit",
"==",
"\"true\"",
")",
"{",
"$",
"this",
"->",
"moufManage... | Deletes a constant.
@Action
@Logged
@param string $name | [
"Deletes",
"a",
"constant",
"."
] | b6a11bfd4a93859c1014d5b3d54ee99314f5fc7b | https://github.com/thecodingmachine/mouf/blob/b6a11bfd4a93859c1014d5b3d54ee99314f5fc7b/src-dev/Mouf/Controllers/ConfigController.php#L245-L266 | train |
PatrickLouys/http | src/HttpResponse.php | HttpResponse.getHeaders | public function getHeaders()
{
$headers = array_merge(
$this->getRequestLineHeaders(),
$this->getStandardHeaders(),
$this->getCookieHeaders()
);
return $headers;
} | php | public function getHeaders()
{
$headers = array_merge(
$this->getRequestLineHeaders(),
$this->getStandardHeaders(),
$this->getCookieHeaders()
);
return $headers;
} | [
"public",
"function",
"getHeaders",
"(",
")",
"{",
"$",
"headers",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"getRequestLineHeaders",
"(",
")",
",",
"$",
"this",
"->",
"getStandardHeaders",
"(",
")",
",",
"$",
"this",
"->",
"getCookieHeaders",
"(",
")",
... | Returns an array with the HTTP headers.
@return array | [
"Returns",
"an",
"array",
"with",
"the",
"HTTP",
"headers",
"."
] | 6321602a8be45c5159f1f0099c60a72c8efdb825 | https://github.com/PatrickLouys/http/blob/6321602a8be45c5159f1f0099c60a72c8efdb825/src/HttpResponse.php#L138-L147 | train |
PatrickLouys/http | src/HttpRequest.php | HttpRequest.getParameter | public function getParameter($key, $defaultValue = null)
{
if (array_key_exists($key, $this->postParameters)) {
return $this->postParameters[$key];
}
if (array_key_exists($key, $this->getParameters)) {
return $this->getParameters[$key];
}
return $defaultValue;
} | php | public function getParameter($key, $defaultValue = null)
{
if (array_key_exists($key, $this->postParameters)) {
return $this->postParameters[$key];
}
if (array_key_exists($key, $this->getParameters)) {
return $this->getParameters[$key];
}
return $defaultValue;
} | [
"public",
"function",
"getParameter",
"(",
"$",
"key",
",",
"$",
"defaultValue",
"=",
"null",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"postParameters",
")",
")",
"{",
"return",
"$",
"this",
"->",
"postParameters"... | Returns a parameter value or a default value if none is set.
@param string $key
@param string $defaultValue (optional)
@return string | [
"Returns",
"a",
"parameter",
"value",
"or",
"a",
"default",
"value",
"if",
"none",
"is",
"set",
"."
] | 6321602a8be45c5159f1f0099c60a72c8efdb825 | https://github.com/PatrickLouys/http/blob/6321602a8be45c5159f1f0099c60a72c8efdb825/src/HttpRequest.php#L36-L47 | train |
PatrickLouys/http | src/HttpRequest.php | HttpRequest.getQueryParameter | public function getQueryParameter($key, $defaultValue = null)
{
if (array_key_exists($key, $this->getParameters)) {
return $this->getParameters[$key];
}
return $defaultValue;
} | php | public function getQueryParameter($key, $defaultValue = null)
{
if (array_key_exists($key, $this->getParameters)) {
return $this->getParameters[$key];
}
return $defaultValue;
} | [
"public",
"function",
"getQueryParameter",
"(",
"$",
"key",
",",
"$",
"defaultValue",
"=",
"null",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"getParameters",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getParamete... | Returns a query parameter value or a default value if none is set.
@param string $key
@param string $defaultValue (optional)
@return string | [
"Returns",
"a",
"query",
"parameter",
"value",
"or",
"a",
"default",
"value",
"if",
"none",
"is",
"set",
"."
] | 6321602a8be45c5159f1f0099c60a72c8efdb825 | https://github.com/PatrickLouys/http/blob/6321602a8be45c5159f1f0099c60a72c8efdb825/src/HttpRequest.php#L56-L63 | train |
PatrickLouys/http | src/HttpRequest.php | HttpRequest.getBodyParameter | public function getBodyParameter($key, $defaultValue = null)
{
if (array_key_exists($key, $this->postParameters)) {
return $this->postParameters[$key];
}
return $defaultValue;
} | php | public function getBodyParameter($key, $defaultValue = null)
{
if (array_key_exists($key, $this->postParameters)) {
return $this->postParameters[$key];
}
return $defaultValue;
} | [
"public",
"function",
"getBodyParameter",
"(",
"$",
"key",
",",
"$",
"defaultValue",
"=",
"null",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"postParameters",
")",
")",
"{",
"return",
"$",
"this",
"->",
"postParamet... | Returns a body parameter value or a default value if none is set.
@param string $key
@param string $defaultValue (optional)
@return string | [
"Returns",
"a",
"body",
"parameter",
"value",
"or",
"a",
"default",
"value",
"if",
"none",
"is",
"set",
"."
] | 6321602a8be45c5159f1f0099c60a72c8efdb825 | https://github.com/PatrickLouys/http/blob/6321602a8be45c5159f1f0099c60a72c8efdb825/src/HttpRequest.php#L72-L79 | train |
PatrickLouys/http | src/HttpRequest.php | HttpRequest.getCookie | public function getCookie($key, $defaultValue = null)
{
if (array_key_exists($key, $this->cookies)) {
return $this->cookies[$key];
}
return $defaultValue;
} | php | public function getCookie($key, $defaultValue = null)
{
if (array_key_exists($key, $this->cookies)) {
return $this->cookies[$key];
}
return $defaultValue;
} | [
"public",
"function",
"getCookie",
"(",
"$",
"key",
",",
"$",
"defaultValue",
"=",
"null",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"cookies",
")",
")",
"{",
"return",
"$",
"this",
"->",
"cookies",
"[",
"$",
... | Returns a cookie value or a default value if none is set.
@param string $key
@param string $defaultValue (optional)
@return string | [
"Returns",
"a",
"cookie",
"value",
"or",
"a",
"default",
"value",
"if",
"none",
"is",
"set",
"."
] | 6321602a8be45c5159f1f0099c60a72c8efdb825 | https://github.com/PatrickLouys/http/blob/6321602a8be45c5159f1f0099c60a72c8efdb825/src/HttpRequest.php#L104-L111 | train |
PatrickLouys/http | src/HttpCookie.php | HttpCookie.getHeaderString | public function getHeaderString()
{
$parts = [
$this->name . '=' . rawurlencode($this->value),
$this->getMaxAgeString(),
$this->getExpiresString(),
$this->getDomainString(),
$this->getPathString(),
$this->getSecureString(),
$this->getHttpOnlyString(),
];
$filteredParts = array_filter($parts);
return implode('; ', $filteredParts);
} | php | public function getHeaderString()
{
$parts = [
$this->name . '=' . rawurlencode($this->value),
$this->getMaxAgeString(),
$this->getExpiresString(),
$this->getDomainString(),
$this->getPathString(),
$this->getSecureString(),
$this->getHttpOnlyString(),
];
$filteredParts = array_filter($parts);
return implode('; ', $filteredParts);
} | [
"public",
"function",
"getHeaderString",
"(",
")",
"{",
"$",
"parts",
"=",
"[",
"$",
"this",
"->",
"name",
".",
"'='",
".",
"rawurlencode",
"(",
"$",
"this",
"->",
"value",
")",
",",
"$",
"this",
"->",
"getMaxAgeString",
"(",
")",
",",
"$",
"this",
... | Returns the cookie HTTP header string.
@return string | [
"Returns",
"the",
"cookie",
"HTTP",
"header",
"string",
"."
] | 6321602a8be45c5159f1f0099c60a72c8efdb825 | https://github.com/PatrickLouys/http/blob/6321602a8be45c5159f1f0099c60a72c8efdb825/src/HttpCookie.php#L102-L117 | train |
zefy/php-simple-sso | docs/examples/Server.php | Server.redirect | protected function redirect(?string $url = null, array $parameters = [], int $httpResponseCode = 307)
{
if (!$url) {
$url = urldecode($_GET['return_url']);
}
$query = '';
// Making URL query string if parameters given.
if (!empty($parameters)) {
$query = '?';
if (parse_url($url, PHP_URL_QUERY)) {
$query = '&';
}
$query .= http_build_query($parameters);
}
header('Location: ' . $url . $query);
exit;
} | php | protected function redirect(?string $url = null, array $parameters = [], int $httpResponseCode = 307)
{
if (!$url) {
$url = urldecode($_GET['return_url']);
}
$query = '';
// Making URL query string if parameters given.
if (!empty($parameters)) {
$query = '?';
if (parse_url($url, PHP_URL_QUERY)) {
$query = '&';
}
$query .= http_build_query($parameters);
}
header('Location: ' . $url . $query);
exit;
} | [
"protected",
"function",
"redirect",
"(",
"?",
"string",
"$",
"url",
"=",
"null",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
",",
"int",
"$",
"httpResponseCode",
"=",
"307",
")",
"{",
"if",
"(",
"!",
"$",
"url",
")",
"{",
"$",
"url",
"=",
"u... | Redirect to provided URL with query string.
If $url is null, redirect to url which given in 'return_url'.
@param string|null $url URL to be redirected.
@param array $parameters HTTP query string.
@param int $httpResponseCode HTTP response code for redirection.
@return void | [
"Redirect",
"to",
"provided",
"URL",
"with",
"query",
"string",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Server.php#L40-L56 | train |
zefy/php-simple-sso | docs/examples/Server.php | Server.getBrokerInfo | protected function getBrokerInfo(string $brokerId)
{
if (!isset($this->brokers[$brokerId])) {
return null;
}
return $this->brokers[$brokerId];
} | php | protected function getBrokerInfo(string $brokerId)
{
if (!isset($this->brokers[$brokerId])) {
return null;
}
return $this->brokers[$brokerId];
} | [
"protected",
"function",
"getBrokerInfo",
"(",
"string",
"$",
"brokerId",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"brokers",
"[",
"$",
"brokerId",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"broker... | Get the secret key and other info of a broker
@param string $brokerId
@return null|array | [
"Get",
"the",
"secret",
"key",
"and",
"other",
"info",
"of",
"a",
"broker"
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Server.php#L96-L103 | train |
zefy/php-simple-sso | docs/examples/Server.php | Server.getUserInfo | protected function getUserInfo(string $username)
{
if (!isset($this->users[$username])) {
return null;
}
return $this->users[$username];
} | php | protected function getUserInfo(string $username)
{
if (!isset($this->users[$username])) {
return null;
}
return $this->users[$username];
} | [
"protected",
"function",
"getUserInfo",
"(",
"string",
"$",
"username",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"users",
"[",
"$",
"username",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"users",
... | Get the information about a user
@param string $username
@return array|object|null | [
"Get",
"the",
"information",
"about",
"a",
"user"
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Server.php#L112-L119 | train |
zefy/php-simple-sso | docs/examples/Server.php | Server.getBrokerSessionId | protected function getBrokerSessionId()
{
$headers = getallheaders();
if (isset($headers['Authorization']) && strpos($headers['Authorization'], 'Bearer') === 0) {
$headers['Authorization'] = substr($headers['Authorization'], 7);
return $headers['Authorization'];
}
return null;
} | php | protected function getBrokerSessionId()
{
$headers = getallheaders();
if (isset($headers['Authorization']) && strpos($headers['Authorization'], 'Bearer') === 0) {
$headers['Authorization'] = substr($headers['Authorization'], 7);
return $headers['Authorization'];
}
return null;
} | [
"protected",
"function",
"getBrokerSessionId",
"(",
")",
"{",
"$",
"headers",
"=",
"getallheaders",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"headers",
"[",
"'Authorization'",
"]",
")",
"&&",
"strpos",
"(",
"$",
"headers",
"[",
"'Authorization'",
"]",
... | Return session id sent from broker.
@return null|string | [
"Return",
"session",
"id",
"sent",
"from",
"broker",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Server.php#L139-L149 | train |
zefy/php-simple-sso | docs/examples/Server.php | Server.saveBrokerSessionData | protected function saveBrokerSessionData(string $brokerSessionId, string $sessionData)
{
/** This is basic example and you should do something better. */
$cacheFile = fopen('broker_session_' . $brokerSessionId, 'w');
fwrite($cacheFile, $sessionData);
fclose($cacheFile);
} | php | protected function saveBrokerSessionData(string $brokerSessionId, string $sessionData)
{
/** This is basic example and you should do something better. */
$cacheFile = fopen('broker_session_' . $brokerSessionId, 'w');
fwrite($cacheFile, $sessionData);
fclose($cacheFile);
} | [
"protected",
"function",
"saveBrokerSessionData",
"(",
"string",
"$",
"brokerSessionId",
",",
"string",
"$",
"sessionData",
")",
"{",
"/** This is basic example and you should do something better. */",
"$",
"cacheFile",
"=",
"fopen",
"(",
"'broker_session_'",
".",
"$",
"b... | Save broker session data to cache.
@param string $brokerSessionId
@param string $sessionData
@return void | [
"Save",
"broker",
"session",
"data",
"to",
"cache",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Server.php#L222-L229 | train |
zefy/php-simple-sso | docs/examples/Server.php | Server.getBrokerSessionData | protected function getBrokerSessionData(string $brokerSessionId)
{
/** This is basic example and you should do something better. */
$cacheFileName = 'broker_session_' . $brokerSessionId;
if (!file_exists($cacheFileName)) {
return null;
}
if (time() - 3600 > filemtime($cacheFileName)) {
unlink($cacheFileName);
return null;
}
echo file_get_contents($cacheFileName);
} | php | protected function getBrokerSessionData(string $brokerSessionId)
{
/** This is basic example and you should do something better. */
$cacheFileName = 'broker_session_' . $brokerSessionId;
if (!file_exists($cacheFileName)) {
return null;
}
if (time() - 3600 > filemtime($cacheFileName)) {
unlink($cacheFileName);
return null;
}
echo file_get_contents($cacheFileName);
} | [
"protected",
"function",
"getBrokerSessionData",
"(",
"string",
"$",
"brokerSessionId",
")",
"{",
"/** This is basic example and you should do something better. */",
"$",
"cacheFileName",
"=",
"'broker_session_'",
".",
"$",
"brokerSessionId",
";",
"if",
"(",
"!",
"file_exis... | Get broker session data from cache.
@param string $brokerSessionId
@return null|string | [
"Get",
"broker",
"session",
"data",
"from",
"cache",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Server.php#L238-L255 | train |
zefy/php-simple-sso | src/SSOServer.php | SSOServer.attach | public function attach(?string $broker, ?string $token, ?string $checksum)
{
try {
if (!$broker) {
$this->fail('No broker id specified.', true);
}
if (!$token) {
$this->fail('No token specified.', true);
}
if (!$checksum || $checksum != $this->generateAttachChecksum($broker, $token)) {
$this->fail('Invalid checksum.', true);
}
$this->startUserSession();
$sessionId = $this->generateSessionId($broker, $token);
$this->saveBrokerSessionData($sessionId, $this->getSessionData('id'));
} catch (SSOServerException $e) {
return $this->redirect(null, ['sso_error' => $e->getMessage()]);
}
$this->attachSuccess();
} | php | public function attach(?string $broker, ?string $token, ?string $checksum)
{
try {
if (!$broker) {
$this->fail('No broker id specified.', true);
}
if (!$token) {
$this->fail('No token specified.', true);
}
if (!$checksum || $checksum != $this->generateAttachChecksum($broker, $token)) {
$this->fail('Invalid checksum.', true);
}
$this->startUserSession();
$sessionId = $this->generateSessionId($broker, $token);
$this->saveBrokerSessionData($sessionId, $this->getSessionData('id'));
} catch (SSOServerException $e) {
return $this->redirect(null, ['sso_error' => $e->getMessage()]);
}
$this->attachSuccess();
} | [
"public",
"function",
"attach",
"(",
"?",
"string",
"$",
"broker",
",",
"?",
"string",
"$",
"token",
",",
"?",
"string",
"$",
"checksum",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"$",
"broker",
")",
"{",
"$",
"this",
"->",
"fail",
"(",
"'No broker id ... | Attach user's session to broker's session.
@param string|null $broker Broker's name/id.
@param string|null $token Token sent from broker.
@param string|null $checksum Calculated broker+token checksum.
@return string or redirect | [
"Attach",
"user",
"s",
"session",
"to",
"broker",
"s",
"session",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOServer.php#L30-L54 | train |
zefy/php-simple-sso | src/SSOServer.php | SSOServer.logout | public function logout()
{
try {
$this->startBrokerSession();
$this->setSessionData('sso_user', null);
} catch (SSOServerException $e) {
return $this->returnJson(['error' => $e->getMessage()]);
}
return $this->returnJson(['success' => 'User has been successfully logged out.']);
} | php | public function logout()
{
try {
$this->startBrokerSession();
$this->setSessionData('sso_user', null);
} catch (SSOServerException $e) {
return $this->returnJson(['error' => $e->getMessage()]);
}
return $this->returnJson(['success' => 'User has been successfully logged out.']);
} | [
"public",
"function",
"logout",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"startBrokerSession",
"(",
")",
";",
"$",
"this",
"->",
"setSessionData",
"(",
"'sso_user'",
",",
"null",
")",
";",
"}",
"catch",
"(",
"SSOServerException",
"$",
"e",
")",
"{... | Logging user out.
@return string | [
"Logging",
"user",
"out",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOServer.php#L88-L98 | train |
zefy/php-simple-sso | src/SSOServer.php | SSOServer.userInfo | public function userInfo()
{
try {
$this->startBrokerSession();
$username = $this->getSessionData('sso_user');
if (!$username) {
$this->fail('User not authenticated. Session ID: ' . $this->getSessionData('id'));
}
if (!$user = $this->getUserInfo($username)) {
$this->fail('User not found.');
}
} catch (SSOServerException $e) {
return $this->returnJson(['error' => $e->getMessage()]);
}
return $this->returnUserInfo($user);
} | php | public function userInfo()
{
try {
$this->startBrokerSession();
$username = $this->getSessionData('sso_user');
if (!$username) {
$this->fail('User not authenticated. Session ID: ' . $this->getSessionData('id'));
}
if (!$user = $this->getUserInfo($username)) {
$this->fail('User not found.');
}
} catch (SSOServerException $e) {
return $this->returnJson(['error' => $e->getMessage()]);
}
return $this->returnUserInfo($user);
} | [
"public",
"function",
"userInfo",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"startBrokerSession",
"(",
")",
";",
"$",
"username",
"=",
"$",
"this",
"->",
"getSessionData",
"(",
"'sso_user'",
")",
";",
"if",
"(",
"!",
"$",
"username",
")",
"{",
"$... | Returning user info for the broker.
@return string | [
"Returning",
"user",
"info",
"for",
"the",
"broker",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOServer.php#L105-L124 | train |
zefy/php-simple-sso | src/SSOServer.php | SSOServer.startBrokerSession | protected function startBrokerSession()
{
if (isset($this->brokerId)) {
return;
}
$sessionId = $this->getBrokerSessionId();
if (!$sessionId) {
$this->fail('Missing session key from broker.');
}
$savedSessionId = $this->getBrokerSessionData($sessionId);
if (!$savedSessionId) {
$this->fail('There is no saved session data associated with the broker session id.');
}
$this->startSession($savedSessionId);
$this->brokerId = $this->validateBrokerSessionId($sessionId);
} | php | protected function startBrokerSession()
{
if (isset($this->brokerId)) {
return;
}
$sessionId = $this->getBrokerSessionId();
if (!$sessionId) {
$this->fail('Missing session key from broker.');
}
$savedSessionId = $this->getBrokerSessionData($sessionId);
if (!$savedSessionId) {
$this->fail('There is no saved session data associated with the broker session id.');
}
$this->startSession($savedSessionId);
$this->brokerId = $this->validateBrokerSessionId($sessionId);
} | [
"protected",
"function",
"startBrokerSession",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"brokerId",
")",
")",
"{",
"return",
";",
"}",
"$",
"sessionId",
"=",
"$",
"this",
"->",
"getBrokerSessionId",
"(",
")",
";",
"if",
"(",
"!",
"$... | Resume broker session if saved session id exist.
@throws SSOServerException
@return void | [
"Resume",
"broker",
"session",
"if",
"saved",
"session",
"id",
"exist",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOServer.php#L133-L154 | train |
zefy/php-simple-sso | src/SSOServer.php | SSOServer.validateBrokerSessionId | protected function validateBrokerSessionId(string $sessionId)
{
$matches = null;
if (!preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $this->getBrokerSessionId(), $matches)) {
$this->fail('Invalid session id');
}
if ($this->generateSessionId($matches[1], $matches[2]) != $sessionId) {
$this->fail('Checksum failed: Client IP address may have changed');
}
return $matches[1];
} | php | protected function validateBrokerSessionId(string $sessionId)
{
$matches = null;
if (!preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $this->getBrokerSessionId(), $matches)) {
$this->fail('Invalid session id');
}
if ($this->generateSessionId($matches[1], $matches[2]) != $sessionId) {
$this->fail('Checksum failed: Client IP address may have changed');
}
return $matches[1];
} | [
"protected",
"function",
"validateBrokerSessionId",
"(",
"string",
"$",
"sessionId",
")",
"{",
"$",
"matches",
"=",
"null",
";",
"if",
"(",
"!",
"preg_match",
"(",
"'/^SSO-(\\w*+)-(\\w*+)-([a-z0-9]*+)$/'",
",",
"$",
"this",
"->",
"getBrokerSessionId",
"(",
")",
... | Check if broker session is valid.
@param string $sessionId Session id from the broker.
@throws SSOServerException
@return string | [
"Check",
"if",
"broker",
"session",
"is",
"valid",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOServer.php#L165-L178 | train |
zefy/php-simple-sso | src/SSOServer.php | SSOServer.fail | protected function fail(?string $message, bool $isRedirect = false, ?string $url = null)
{
if (!$isRedirect) {
throw new SSOServerException($message);
}
$this->redirect($url, ['sso_error' => $message]);
} | php | protected function fail(?string $message, bool $isRedirect = false, ?string $url = null)
{
if (!$isRedirect) {
throw new SSOServerException($message);
}
$this->redirect($url, ['sso_error' => $message]);
} | [
"protected",
"function",
"fail",
"(",
"?",
"string",
"$",
"message",
",",
"bool",
"$",
"isRedirect",
"=",
"false",
",",
"?",
"string",
"$",
"url",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"isRedirect",
")",
"{",
"throw",
"new",
"SSOServerException",... | If something failed, throw an Exception or redirect.
@param null|string $message
@param bool $isRedirect
@param null|string $url
@throws SSOServerException
@return void | [
"If",
"something",
"failed",
"throw",
"an",
"Exception",
"or",
"redirect",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOServer.php#L243-L250 | train |
zefy/php-simple-sso | src/SSOBroker.php | SSOBroker.attach | public function attach()
{
$parameters = [
'return_url' => $this->getCurrentUrl(),
'broker' => $this->brokerName,
'token' => $this->token,
'checksum' => hash('sha256', 'attach' . $this->token . $this->brokerSecret)
];
$attachUrl = $this->generateCommandUrl('attach', $parameters);
$this->redirect($attachUrl);
} | php | public function attach()
{
$parameters = [
'return_url' => $this->getCurrentUrl(),
'broker' => $this->brokerName,
'token' => $this->token,
'checksum' => hash('sha256', 'attach' . $this->token . $this->brokerSecret)
];
$attachUrl = $this->generateCommandUrl('attach', $parameters);
$this->redirect($attachUrl);
} | [
"public",
"function",
"attach",
"(",
")",
"{",
"$",
"parameters",
"=",
"[",
"'return_url'",
"=>",
"$",
"this",
"->",
"getCurrentUrl",
"(",
")",
",",
"'broker'",
"=>",
"$",
"this",
"->",
"brokerName",
",",
"'token'",
"=>",
"$",
"this",
"->",
"token",
",... | Attach client session to broker session in SSO server.
@return void | [
"Attach",
"client",
"session",
"to",
"broker",
"session",
"in",
"SSO",
"server",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOBroker.php#L63-L75 | train |
zefy/php-simple-sso | src/SSOBroker.php | SSOBroker.getUserInfo | public function getUserInfo()
{
if (!isset($this->userInfo) || empty($this->userInfo)) {
$this->userInfo = $this->makeRequest('GET', 'userInfo');
}
return $this->userInfo;
} | php | public function getUserInfo()
{
if (!isset($this->userInfo) || empty($this->userInfo)) {
$this->userInfo = $this->makeRequest('GET', 'userInfo');
}
return $this->userInfo;
} | [
"public",
"function",
"getUserInfo",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"userInfo",
")",
"||",
"empty",
"(",
"$",
"this",
"->",
"userInfo",
")",
")",
"{",
"$",
"this",
"->",
"userInfo",
"=",
"$",
"this",
"->",
"makeRequ... | Getting user info from SSO based on client session.
@return array | [
"Getting",
"user",
"info",
"from",
"SSO",
"based",
"on",
"client",
"session",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOBroker.php#L82-L89 | train |
zefy/php-simple-sso | src/SSOBroker.php | SSOBroker.login | public function login(string $username, string $password)
{
$this->userInfo = $this->makeRequest('POST', 'login', compact('username', 'password'));
if (!isset($this->userInfo['error']) && isset($this->userInfo['data']['id'])) {
return true;
}
return false;
} | php | public function login(string $username, string $password)
{
$this->userInfo = $this->makeRequest('POST', 'login', compact('username', 'password'));
if (!isset($this->userInfo['error']) && isset($this->userInfo['data']['id'])) {
return true;
}
return false;
} | [
"public",
"function",
"login",
"(",
"string",
"$",
"username",
",",
"string",
"$",
"password",
")",
"{",
"$",
"this",
"->",
"userInfo",
"=",
"$",
"this",
"->",
"makeRequest",
"(",
"'POST'",
",",
"'login'",
",",
"compact",
"(",
"'username'",
",",
"'passwo... | Login client to SSO server with user credentials.
@param string $username
@param string $password
@return bool | [
"Login",
"client",
"to",
"SSO",
"server",
"with",
"user",
"credentials",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOBroker.php#L99-L108 | train |
zefy/php-simple-sso | src/SSOBroker.php | SSOBroker.generateCommandUrl | protected function generateCommandUrl(string $command, array $parameters = [])
{
$query = '';
if (!empty($parameters)) {
$query = '?' . http_build_query($parameters);
}
return $this->ssoServerUrl . '/sso/' . $command . $query;
} | php | protected function generateCommandUrl(string $command, array $parameters = [])
{
$query = '';
if (!empty($parameters)) {
$query = '?' . http_build_query($parameters);
}
return $this->ssoServerUrl . '/sso/' . $command . $query;
} | [
"protected",
"function",
"generateCommandUrl",
"(",
"string",
"$",
"command",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"''",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"parameters",
")",
")",
"{",
"$",
"query",
"=",
... | Generate request url.
@param string $command
@param array $parameters
@return string | [
"Generate",
"request",
"url",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/src/SSOBroker.php#L128-L136 | train |
zefy/php-simple-sso | docs/examples/Broker.php | Broker.saveToken | protected function saveToken()
{
if (isset($this->token) && $this->token) {
return;
}
if ($this->token = $this->getCookie($this->getCookieName())) {
return;
}
// If cookie token doesn't exist, we need to create it with unique token...
$this->token = base_convert(md5(uniqid(rand(), true)), 16, 36);
setcookie($this->getCookieName(), $this->token, time() + 60 * 60 * 12, '/');
// ... and attach it to broker session in SSO server.
$this->attach();
} | php | protected function saveToken()
{
if (isset($this->token) && $this->token) {
return;
}
if ($this->token = $this->getCookie($this->getCookieName())) {
return;
}
// If cookie token doesn't exist, we need to create it with unique token...
$this->token = base_convert(md5(uniqid(rand(), true)), 16, 36);
setcookie($this->getCookieName(), $this->token, time() + 60 * 60 * 12, '/');
// ... and attach it to broker session in SSO server.
$this->attach();
} | [
"protected",
"function",
"saveToken",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"token",
")",
"&&",
"$",
"this",
"->",
"token",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"token",
"=",
"$",
"this",
"->",
"getCook... | Somehow save random token for client.
@return void | [
"Somehow",
"save",
"random",
"token",
"for",
"client",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Broker.php#L50-L66 | train |
zefy/php-simple-sso | docs/examples/Broker.php | Broker.makeRequest | protected function makeRequest(string $method, string $command, array $parameters = [])
{
$commandUrl = $this->generateCommandUrl($command);
$headers = [
'Accept' => 'application/json',
'Authorization' => 'Bearer '. $this->getSessionId(),
];
switch ($method) {
case 'POST':
$body = ['form_params' => $parameters];
break;
case 'GET':
$body = ['query' => $parameters];
break;
default:
$body = [];
break;
}
$client = new GuzzleHttp\Client;
$response = $client->request($method, $commandUrl, $body + ['headers' => $headers]);
return json_decode($response->getBody(), true);
} | php | protected function makeRequest(string $method, string $command, array $parameters = [])
{
$commandUrl = $this->generateCommandUrl($command);
$headers = [
'Accept' => 'application/json',
'Authorization' => 'Bearer '. $this->getSessionId(),
];
switch ($method) {
case 'POST':
$body = ['form_params' => $parameters];
break;
case 'GET':
$body = ['query' => $parameters];
break;
default:
$body = [];
break;
}
$client = new GuzzleHttp\Client;
$response = $client->request($method, $commandUrl, $body + ['headers' => $headers]);
return json_decode($response->getBody(), true);
} | [
"protected",
"function",
"makeRequest",
"(",
"string",
"$",
"method",
",",
"string",
"$",
"command",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"commandUrl",
"=",
"$",
"this",
"->",
"generateCommandUrl",
"(",
"$",
"command",
")",
";",... | Make request to SSO server.
@param string $method Request method 'post' or 'get'.
@param string $command Request command name.
@param array $parameters Parameters for URL query string if GET request and form parameters if it's POST request.
@return array | [
"Make",
"request",
"to",
"SSO",
"server",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Broker.php#L88-L109 | train |
zefy/php-simple-sso | docs/examples/Broker.php | Broker.redirect | protected function redirect(string $url, array $parameters = [], int $httpResponseCode = 307)
{
$query = '';
// Making URL query string if parameters given.
if (!empty($parameters)) {
$query = '?';
if (parse_url($url, PHP_URL_QUERY)) {
$query = '&';
}
$query .= http_build_query($parameters);
}
header('Location: ' . $url . $query, true, $httpResponseCode);
exit;
} | php | protected function redirect(string $url, array $parameters = [], int $httpResponseCode = 307)
{
$query = '';
// Making URL query string if parameters given.
if (!empty($parameters)) {
$query = '?';
if (parse_url($url, PHP_URL_QUERY)) {
$query = '&';
}
$query .= http_build_query($parameters);
}
header('Location: ' . $url . $query, true, $httpResponseCode);
exit;
} | [
"protected",
"function",
"redirect",
"(",
"string",
"$",
"url",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
",",
"int",
"$",
"httpResponseCode",
"=",
"307",
")",
"{",
"$",
"query",
"=",
"''",
";",
"// Making URL query string if parameters given.",
"if",
... | Redirect client to specified url.
@param string $url URL to be redirected.
@param array $parameters HTTP query string.
@param int $httpResponseCode HTTP response code for redirection.
@return void | [
"Redirect",
"client",
"to",
"specified",
"url",
"."
] | f2eb2ef567615429966534af5f88cff7cdb00cca | https://github.com/zefy/php-simple-sso/blob/f2eb2ef567615429966534af5f88cff7cdb00cca/docs/examples/Broker.php#L120-L134 | train |
wasinger/jsonrpc-bundle | Controller/JsonRpcController.php | JsonRpcController.addMethod | public function addMethod($alias, $service, $method, $overwrite = false)
{
if (!isset($this->functions)) $this->functions = array();
if (isset($this->functions[$alias]) && !$overwrite) {
throw new \InvalidArgumentException('JsonRpcController: The function "' . $alias . '" already exists.');
}
$this->functions[$alias] = array(
'service' => $service,
'method' => $method
);
} | php | public function addMethod($alias, $service, $method, $overwrite = false)
{
if (!isset($this->functions)) $this->functions = array();
if (isset($this->functions[$alias]) && !$overwrite) {
throw new \InvalidArgumentException('JsonRpcController: The function "' . $alias . '" already exists.');
}
$this->functions[$alias] = array(
'service' => $service,
'method' => $method
);
} | [
"public",
"function",
"addMethod",
"(",
"$",
"alias",
",",
"$",
"service",
",",
"$",
"method",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"functions",
")",
")",
"$",
"this",
"->",
"functions",
"=... | Add a new function that can be called by RPC
@param string $alias The function name used in the RPC call
@param string $service The service name of the method to call
@param string $method The method of $service
@param bool $overwrite Whether to overwrite an existing function
@throws \InvalidArgumentException | [
"Add",
"a",
"new",
"function",
"that",
"can",
"be",
"called",
"by",
"RPC"
] | 8c8ff13244a3c9c8f956de2ee074d615392ed354 | https://github.com/wasinger/jsonrpc-bundle/blob/8c8ff13244a3c9c8f956de2ee074d615392ed354/Controller/JsonRpcController.php#L204-L214 | train |
wasinger/jsonrpc-bundle | Controller/JsonRpcController.php | JsonRpcController.getSerializationContext | protected function getSerializationContext(array $functionConfig)
{
if (isset($functionConfig['jms_serialization_context'])) {
$serializationContext = \JMS\Serializer\SerializationContext::create();
if (isset($functionConfig['jms_serialization_context']['groups'])) {
$serializationContext->setGroups($functionConfig['jms_serialization_context']['groups']);
}
if (isset($functionConfig['jms_serialization_context']['version'])) {
$serializationContext->setVersion($functionConfig['jms_serialization_context']['version']);
}
if (isset($functionConfig['jms_serialization_context']['max_depth_checks'])) {
$serializationContext->enableMaxDepthChecks($functionConfig['jms_serialization_context']['max_depth_checks']);
}
} else {
$serializationContext = $this->serializationContext;
}
return $serializationContext;
} | php | protected function getSerializationContext(array $functionConfig)
{
if (isset($functionConfig['jms_serialization_context'])) {
$serializationContext = \JMS\Serializer\SerializationContext::create();
if (isset($functionConfig['jms_serialization_context']['groups'])) {
$serializationContext->setGroups($functionConfig['jms_serialization_context']['groups']);
}
if (isset($functionConfig['jms_serialization_context']['version'])) {
$serializationContext->setVersion($functionConfig['jms_serialization_context']['version']);
}
if (isset($functionConfig['jms_serialization_context']['max_depth_checks'])) {
$serializationContext->enableMaxDepthChecks($functionConfig['jms_serialization_context']['max_depth_checks']);
}
} else {
$serializationContext = $this->serializationContext;
}
return $serializationContext;
} | [
"protected",
"function",
"getSerializationContext",
"(",
"array",
"$",
"functionConfig",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"functionConfig",
"[",
"'jms_serialization_context'",
"]",
")",
")",
"{",
"$",
"serializationContext",
"=",
"\\",
"JMS",
"\\",
"Seria... | Get SerializationContext or creates one if jms_serialization_context option is set
@param array $functionConfig
@return \JMS\Serializer\SerializationContext | [
"Get",
"SerializationContext",
"or",
"creates",
"one",
"if",
"jms_serialization_context",
"option",
"is",
"set"
] | 8c8ff13244a3c9c8f956de2ee074d615392ed354 | https://github.com/wasinger/jsonrpc-bundle/blob/8c8ff13244a3c9c8f956de2ee074d615392ed354/Controller/JsonRpcController.php#L297-L318 | train |
kasp3r/link-preview | src/LinkPreview/LinkPreview.php | LinkPreview.getParsed | public function getParsed()
{
$parsed = [];
$parsers = $this->getParsers();
if (0 === count($parsers)) {
$this->addDefaultParsers();
}
foreach ($this->getParsers() as $name => $parser) {
$parser->getLink()->setUrl($this->getUrl());
if ($parser->isValidParser()) {
$parsed[$name] = $parser->parseLink();
if (!$this->getPropagation()) {
break;
}
}
}
return $parsed;
} | php | public function getParsed()
{
$parsed = [];
$parsers = $this->getParsers();
if (0 === count($parsers)) {
$this->addDefaultParsers();
}
foreach ($this->getParsers() as $name => $parser) {
$parser->getLink()->setUrl($this->getUrl());
if ($parser->isValidParser()) {
$parsed[$name] = $parser->parseLink();
if (!$this->getPropagation()) {
break;
}
}
}
return $parsed;
} | [
"public",
"function",
"getParsed",
"(",
")",
"{",
"$",
"parsed",
"=",
"[",
"]",
";",
"$",
"parsers",
"=",
"$",
"this",
"->",
"getParsers",
"(",
")",
";",
"if",
"(",
"0",
"===",
"count",
"(",
"$",
"parsers",
")",
")",
"{",
"$",
"this",
"->",
"ad... | Get parsed model array with parser name as a key
@return LinkInterface[] | [
"Get",
"parsed",
"model",
"array",
"with",
"parser",
"name",
"as",
"a",
"key"
] | 468c0209f1640f270e62a13e5a41da1272e6098c | https://github.com/kasp3r/link-preview/blob/468c0209f1640f270e62a13e5a41da1272e6098c/src/LinkPreview/LinkPreview.php#L54-L76 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.getLogTime | private function getLogTime()
{
$diff = $this->microtime_diff($this->init);
$format = gmdate("H:i:s",(int)$diff);
$diff = sprintf("%01.5f", $diff);
$format .= substr($diff,strpos((string)$diff,'.'));
return $format;
} | php | private function getLogTime()
{
$diff = $this->microtime_diff($this->init);
$format = gmdate("H:i:s",(int)$diff);
$diff = sprintf("%01.5f", $diff);
$format .= substr($diff,strpos((string)$diff,'.'));
return $format;
} | [
"private",
"function",
"getLogTime",
"(",
")",
"{",
"$",
"diff",
"=",
"$",
"this",
"->",
"microtime_diff",
"(",
"$",
"this",
"->",
"init",
")",
";",
"$",
"format",
"=",
"gmdate",
"(",
"\"H:i:s\"",
",",
"(",
"int",
")",
"$",
"diff",
")",
";",
"$",
... | Devuelve la diferencia de tiempo formateada
@return string | [
"Devuelve",
"la",
"diferencia",
"de",
"tiempo",
"formateada"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L128-L135 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.microtime_diff | private function microtime_diff($start, $end = null)
{
if (!$end) {
$end = microtime();
}
list($start_usec, $start_sec) = explode(" ", $start);
list($end_usec, $end_sec) = explode(" ", $end);
$diff_sec = intval($end_sec) - intval($start_sec);
$diff_usec = floatval($end_usec) - floatval($start_usec);
return floatval($diff_sec) + $diff_usec;
} | php | private function microtime_diff($start, $end = null)
{
if (!$end) {
$end = microtime();
}
list($start_usec, $start_sec) = explode(" ", $start);
list($end_usec, $end_sec) = explode(" ", $end);
$diff_sec = intval($end_sec) - intval($start_sec);
$diff_usec = floatval($end_usec) - floatval($start_usec);
return floatval($diff_sec) + $diff_usec;
} | [
"private",
"function",
"microtime_diff",
"(",
"$",
"start",
",",
"$",
"end",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"end",
")",
"{",
"$",
"end",
"=",
"microtime",
"(",
")",
";",
"}",
"list",
"(",
"$",
"start_usec",
",",
"$",
"start_sec",
")"... | Diferencia de microtime
@param string $start inicio
@param microtime $end fin
@return float | [
"Diferencia",
"de",
"microtime"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L143-L153 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.validNameFile | public function validNameFile($filename,$ext=true){
$filename = trim($filename);
if($filename!="." && $filename!=".." && $filename!=" " && preg_match_all("#^[a-zA-Z0-9-_.\s]+$#",$filename) > 0){
if($ext) return $this->validExt($filename);
else return true;
}else{
return false;
}
} | php | public function validNameFile($filename,$ext=true){
$filename = trim($filename);
if($filename!="." && $filename!=".." && $filename!=" " && preg_match_all("#^[a-zA-Z0-9-_.\s]+$#",$filename) > 0){
if($ext) return $this->validExt($filename);
else return true;
}else{
return false;
}
} | [
"public",
"function",
"validNameFile",
"(",
"$",
"filename",
",",
"$",
"ext",
"=",
"true",
")",
"{",
"$",
"filename",
"=",
"trim",
"(",
"$",
"filename",
")",
";",
"if",
"(",
"$",
"filename",
"!=",
"\".\"",
"&&",
"$",
"filename",
"!=",
"\"..\"",
"&&",... | Valida nombre de archivo
@param string $filename
@return boolean | [
"Valida",
"nombre",
"de",
"archivo"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L194-L202 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.validExt | public function validExt($filename){
$exts = $this->config['ext'];
$ext = $this->getExtension($filename);
if(array_search($ext,$exts)===false){
return false;
}else{
return true;
}
} | php | public function validExt($filename){
$exts = $this->config['ext'];
$ext = $this->getExtension($filename);
if(array_search($ext,$exts)===false){
return false;
}else{
return true;
}
} | [
"public",
"function",
"validExt",
"(",
"$",
"filename",
")",
"{",
"$",
"exts",
"=",
"$",
"this",
"->",
"config",
"[",
"'ext'",
"]",
";",
"$",
"ext",
"=",
"$",
"this",
"->",
"getExtension",
"(",
"$",
"filename",
")",
";",
"if",
"(",
"array_search",
... | Valida extension de archivos
@param string $filename
@return boolean | [
"Valida",
"extension",
"de",
"archivos"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L209-L219 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.setInfo | public function setInfo($data=array()) {
if(isset($data['data'])) $this->info['data'] = $data['data'];
if(isset($data['status'])) $this->info['status'] = $data['status'];
if(isset($data['msg'])) $this->info['msg'] = $data['msg'];
} | php | public function setInfo($data=array()) {
if(isset($data['data'])) $this->info['data'] = $data['data'];
if(isset($data['status'])) $this->info['status'] = $data['status'];
if(isset($data['msg'])) $this->info['msg'] = $data['msg'];
} | [
"public",
"function",
"setInfo",
"(",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'data'",
"]",
")",
")",
"$",
"this",
"->",
"info",
"[",
"'data'",
"]",
"=",
"$",
"data",
"[",
"'data'",
"]",
";",
... | Agrega mensaje a cada peticion si se produce un error
@param array $data
@return void | [
"Agrega",
"mensaje",
"a",
"cada",
"peticion",
"si",
"se",
"produce",
"un",
"error"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L226-L231 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager._log | public function _log($string,$type='info') {
if($this->config['debug']){
$string = $this->getLogTime().": ".$string;
}
if($type=='info')
$this->log->addInfo($string);
elseif($type=='warning')
$this->log->addWarning($string);
elseif($type=='error')
$this->log->addError($string);
} | php | public function _log($string,$type='info') {
if($this->config['debug']){
$string = $this->getLogTime().": ".$string;
}
if($type=='info')
$this->log->addInfo($string);
elseif($type=='warning')
$this->log->addWarning($string);
elseif($type=='error')
$this->log->addError($string);
} | [
"public",
"function",
"_log",
"(",
"$",
"string",
",",
"$",
"type",
"=",
"'info'",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"'debug'",
"]",
")",
"{",
"$",
"string",
"=",
"$",
"this",
"->",
"getLogTime",
"(",
")",
".",
"\": \"",
".",... | Si debug active permite logear informacion
@param string $string Texto a mostrar
@param string $type Tipo de mensaje
@return void | [
"Si",
"debug",
"active",
"permite",
"logear",
"informacion"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L239-L249 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.sanitizeNameFolder | private function sanitizeNameFolder($var,$strict=false) {
$sanitized = strip_tags($var);
$sanitized = str_replace('.', '', $sanitized);
$sanitized = preg_replace('@(\/)+@', '/', $sanitized);
if($strict){
if(substr($sanitized,-1)=='/') $sanitized = substr($sanitized,0,-1);
}
return $sanitized;
} | php | private function sanitizeNameFolder($var,$strict=false) {
$sanitized = strip_tags($var);
$sanitized = str_replace('.', '', $sanitized);
$sanitized = preg_replace('@(\/)+@', '/', $sanitized);
if($strict){
if(substr($sanitized,-1)=='/') $sanitized = substr($sanitized,0,-1);
}
return $sanitized;
} | [
"private",
"function",
"sanitizeNameFolder",
"(",
"$",
"var",
",",
"$",
"strict",
"=",
"false",
")",
"{",
"$",
"sanitized",
"=",
"strip_tags",
"(",
"$",
"var",
")",
";",
"$",
"sanitized",
"=",
"str_replace",
"(",
"'.'",
",",
"''",
",",
"$",
"sanitized"... | Clear name folder
@param string $var
@return string | [
"Clear",
"name",
"folder"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L270-L278 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.fileInfo | public function fileInfo($file,$path){
if($file->isReadable()){
$item = $this->fileDetails;
$item["filename"] = $file->getFilename();
$item["filetype"] = $file->getExtension();
$item["lastmodified"] = $file->getMTime();
$item["size"] = $file->getSize();
if ($this->isImage($file)) {
$thumb = $this->firstThumb($file,$path);
if($thumb){
$item['preview'] = $this->config['url'].$this->config['source'].'/'.$this->config['folder_thumb'].$path.$thumb;
}
}
$item['previewfull'] = $this->config['url'].$this->config['source'].$path.$item["filename"];
return $item;
}else{
return ;
}
} | php | public function fileInfo($file,$path){
if($file->isReadable()){
$item = $this->fileDetails;
$item["filename"] = $file->getFilename();
$item["filetype"] = $file->getExtension();
$item["lastmodified"] = $file->getMTime();
$item["size"] = $file->getSize();
if ($this->isImage($file)) {
$thumb = $this->firstThumb($file,$path);
if($thumb){
$item['preview'] = $this->config['url'].$this->config['source'].'/'.$this->config['folder_thumb'].$path.$thumb;
}
}
$item['previewfull'] = $this->config['url'].$this->config['source'].$path.$item["filename"];
return $item;
}else{
return ;
}
} | [
"public",
"function",
"fileInfo",
"(",
"$",
"file",
",",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"file",
"->",
"isReadable",
"(",
")",
")",
"{",
"$",
"item",
"=",
"$",
"this",
"->",
"fileDetails",
";",
"$",
"item",
"[",
"\"filename\"",
"]",
"=",
"... | Todas las propiedades de un archivo o directorio
@param SplFileInfo $file Object of SplFileInfo
@param string $path Ruta de la carpeta o archivo
@return array|null Lista de propiedades o null si no es leible | [
"Todas",
"las",
"propiedades",
"de",
"un",
"archivo",
"o",
"directorio"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L338-L356 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.dirInfo | public function dirInfo($file,$path){
if($file->isReadable()){
$item = $this->fileDetails;
$item["filename"] = $file->getFilename();
$item["filetype"] = $file->getExtension();
$item["lastmodified"] = $file->getMTime();
$item["size"] = $file->getSize();
$item["filetype"] = '';
$item["isdir"] = true;
$item["urlfolder"] = $path.$item["filename"].'/';
$item['preview'] = '';
return $item;
}else{
return ;
}
} | php | public function dirInfo($file,$path){
if($file->isReadable()){
$item = $this->fileDetails;
$item["filename"] = $file->getFilename();
$item["filetype"] = $file->getExtension();
$item["lastmodified"] = $file->getMTime();
$item["size"] = $file->getSize();
$item["filetype"] = '';
$item["isdir"] = true;
$item["urlfolder"] = $path.$item["filename"].'/';
$item['preview'] = '';
return $item;
}else{
return ;
}
} | [
"public",
"function",
"dirInfo",
"(",
"$",
"file",
",",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"file",
"->",
"isReadable",
"(",
")",
")",
"{",
"$",
"item",
"=",
"$",
"this",
"->",
"fileDetails",
";",
"$",
"item",
"[",
"\"filename\"",
"]",
"=",
"$... | Informacion del directorio
@param UploadedFile $file
@param string $path ruta relativa
@return array | [
"Informacion",
"del",
"directorio"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L364-L379 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.firstThumb | public function firstThumb($file,$path){
$fullpath = $this->getFullPath().$path;
$fullpaththumb = $this->getFullPath().'/'.$this->config['folder_thumb'].$path;
$filename = $file->getFilename();
$filename_new_first = '';
foreach ($this->config['images']['resize'] as $key => $value) {
$image_info = $this->imageSizeName($path,$filename,$value);
if(file_exists($fullpaththumb.$image_info['name']) === false){
$this->resizeImage($fullpath.$filename,$fullpaththumb.$image_info['name'],$image_info,$value);
}
$filename_new_first = $image_info['name'];
break;
}
return $filename_new_first;
} | php | public function firstThumb($file,$path){
$fullpath = $this->getFullPath().$path;
$fullpaththumb = $this->getFullPath().'/'.$this->config['folder_thumb'].$path;
$filename = $file->getFilename();
$filename_new_first = '';
foreach ($this->config['images']['resize'] as $key => $value) {
$image_info = $this->imageSizeName($path,$filename,$value);
if(file_exists($fullpaththumb.$image_info['name']) === false){
$this->resizeImage($fullpath.$filename,$fullpaththumb.$image_info['name'],$image_info,$value);
}
$filename_new_first = $image_info['name'];
break;
}
return $filename_new_first;
} | [
"public",
"function",
"firstThumb",
"(",
"$",
"file",
",",
"$",
"path",
")",
"{",
"$",
"fullpath",
"=",
"$",
"this",
"->",
"getFullPath",
"(",
")",
".",
"$",
"path",
";",
"$",
"fullpaththumb",
"=",
"$",
"this",
"->",
"getFullPath",
"(",
")",
".",
"... | Informacion de la primera miniatura
@param UploadedFile $file
@param string $path ruta relativa
@return string | [
"Informacion",
"de",
"la",
"primera",
"miniatura"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L387-L401 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.createThumb | public function createThumb($file,$path){
$ext = $file->getExtension();
$search = $this->config["images"]["images_ext"];
if(array_search($ext, $search) !== false){
$fullpath = $this->getFullPath().$path;
$fullpaththumb = $this->getFullPath().'/'.$this->config['folder_thumb'].$path;
$filename = $file->getFilename();
$filename_new_first = '';
$i=0;
foreach ($this->config['images']['resize'] as $key => $value) {
$i++;
$image_info = $this->imageSizeName($path,$filename,$value);
if(file_exists($fullpaththumb.$image_info['name']) === false){
$this->resizeImage($fullpath.$filename,$fullpaththumb.$image_info['name'],$image_info,$value);
}
if($i==1) $filename_new_first = $image_info['name'];
}
return $filename_new_first;
}else{
if( $this->config['debug'] ) $this->_log(__METHOD__." - $ext");
}
} | php | public function createThumb($file,$path){
$ext = $file->getExtension();
$search = $this->config["images"]["images_ext"];
if(array_search($ext, $search) !== false){
$fullpath = $this->getFullPath().$path;
$fullpaththumb = $this->getFullPath().'/'.$this->config['folder_thumb'].$path;
$filename = $file->getFilename();
$filename_new_first = '';
$i=0;
foreach ($this->config['images']['resize'] as $key => $value) {
$i++;
$image_info = $this->imageSizeName($path,$filename,$value);
if(file_exists($fullpaththumb.$image_info['name']) === false){
$this->resizeImage($fullpath.$filename,$fullpaththumb.$image_info['name'],$image_info,$value);
}
if($i==1) $filename_new_first = $image_info['name'];
}
return $filename_new_first;
}else{
if( $this->config['debug'] ) $this->_log(__METHOD__." - $ext");
}
} | [
"public",
"function",
"createThumb",
"(",
"$",
"file",
",",
"$",
"path",
")",
"{",
"$",
"ext",
"=",
"$",
"file",
"->",
"getExtension",
"(",
")",
";",
"$",
"search",
"=",
"$",
"this",
"->",
"config",
"[",
"\"images\"",
"]",
"[",
"\"images_ext\"",
"]",... | Crea la miniatura de imagenes
@param UploadedFile $file
@param string $path
@return string Nombre del nuevo archivo | [
"Crea",
"la",
"miniatura",
"de",
"imagenes"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L422-L443 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.resizeImage | public function resizeImage($path_imagen,$path_imagen_new,$image_info=array(),$image_config=array())
{
$imagen_ext = $this->getExtension($path_imagen);
if ($image_config[2]===true && $image_config[3]===true) {
Imagen::open($path_imagen)->zoomCrop($image_info['width'],$image_info['height'])->save($path_imagen_new,$imagen_ext,$this->config['images']['quality']);
return true;
}elseif ( $image_config[2]===true && $image_config[3]===null ) {
Imagen::open($path_imagen)->scaleResize($image_info['width'],null)->save($path_imagen_new,$imagen_ext,$this->config['images']['quality']);
return true;
}elseif ( $image_config[2]===null && $image_config[3]===true ) {
Imagen::open($path_imagen)->scaleResize(null,$image_info['height'])->save($path_imagen_new,$imagen_ext,$this->config['images']['quality']);
return true;
}else{
return false;
}
} | php | public function resizeImage($path_imagen,$path_imagen_new,$image_info=array(),$image_config=array())
{
$imagen_ext = $this->getExtension($path_imagen);
if ($image_config[2]===true && $image_config[3]===true) {
Imagen::open($path_imagen)->zoomCrop($image_info['width'],$image_info['height'])->save($path_imagen_new,$imagen_ext,$this->config['images']['quality']);
return true;
}elseif ( $image_config[2]===true && $image_config[3]===null ) {
Imagen::open($path_imagen)->scaleResize($image_info['width'],null)->save($path_imagen_new,$imagen_ext,$this->config['images']['quality']);
return true;
}elseif ( $image_config[2]===null && $image_config[3]===true ) {
Imagen::open($path_imagen)->scaleResize(null,$image_info['height'])->save($path_imagen_new,$imagen_ext,$this->config['images']['quality']);
return true;
}else{
return false;
}
} | [
"public",
"function",
"resizeImage",
"(",
"$",
"path_imagen",
",",
"$",
"path_imagen_new",
",",
"$",
"image_info",
"=",
"array",
"(",
")",
",",
"$",
"image_config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"imagen_ext",
"=",
"$",
"this",
"->",
"getExtensio... | redimensiona una imagen
@param string $path_imagen ruta de imagen origen
@param string $path_imagen_new ruta de imagen nueva
@param array $image_info info de imagen
@param array $image_config dimensiones de imagenes
@return boolean | [
"redimensiona",
"una",
"imagen"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L453-L468 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.imageSizeName | public function imageSizeName($path,$imagen,$image_config)
{
$result = array("name"=>'',"width"=>0,"height"=>0);
$imagen_ext = $this->getExtension($imagen);
$imagen_name = $this->removeExtension($imagen);
if ($image_config[2]===true && $image_config[3]===true) {
$fullpath_new = $imagen_name.'-'.$image_config[0].'x'.$image_config[1].'.'.$imagen_ext;
$result['name'] = $fullpath_new;
$result['width'] = $image_config[0];
$result['height'] = $image_config[1];
}elseif ( $image_config[2]===true && $image_config[3]===null ) {
$imagesize = getimagesize($this->getFullPath().$path.$imagen);
$imagesize_new = $this->getImageCalSize(array($imagesize[0],$imagesize[1]),$image_config);
$fullpath_new = $imagen_name.'-'.$imagesize_new[0].'x'.$imagesize_new[1].'.'.$imagen_ext;
$result['name'] = $fullpath_new;
$result['width'] = $imagesize_new[0];
$result['height'] = $imagesize_new[1];
}elseif ( $image_config[2]===null && $image_config[3]===true ) {
$imagesize = getimagesize($this->getFullPath().$path.$imagen);
$imagesize_new = $this->getImageCalSize(array($imagesize[0],$imagesize[1]),$image_config);
$fullpath_new = $imagen_name.'-'.$imagesize_new[0].'x'.$imagesize_new[1].'.'.$imagen_ext;
$result['name'] = $fullpath_new;
$result['width'] = $imagesize_new[0];
$result['height'] = $imagesize_new[1];
}
return $result;
} | php | public function imageSizeName($path,$imagen,$image_config)
{
$result = array("name"=>'',"width"=>0,"height"=>0);
$imagen_ext = $this->getExtension($imagen);
$imagen_name = $this->removeExtension($imagen);
if ($image_config[2]===true && $image_config[3]===true) {
$fullpath_new = $imagen_name.'-'.$image_config[0].'x'.$image_config[1].'.'.$imagen_ext;
$result['name'] = $fullpath_new;
$result['width'] = $image_config[0];
$result['height'] = $image_config[1];
}elseif ( $image_config[2]===true && $image_config[3]===null ) {
$imagesize = getimagesize($this->getFullPath().$path.$imagen);
$imagesize_new = $this->getImageCalSize(array($imagesize[0],$imagesize[1]),$image_config);
$fullpath_new = $imagen_name.'-'.$imagesize_new[0].'x'.$imagesize_new[1].'.'.$imagen_ext;
$result['name'] = $fullpath_new;
$result['width'] = $imagesize_new[0];
$result['height'] = $imagesize_new[1];
}elseif ( $image_config[2]===null && $image_config[3]===true ) {
$imagesize = getimagesize($this->getFullPath().$path.$imagen);
$imagesize_new = $this->getImageCalSize(array($imagesize[0],$imagesize[1]),$image_config);
$fullpath_new = $imagen_name.'-'.$imagesize_new[0].'x'.$imagesize_new[1].'.'.$imagen_ext;
$result['name'] = $fullpath_new;
$result['width'] = $imagesize_new[0];
$result['height'] = $imagesize_new[1];
}
return $result;
} | [
"public",
"function",
"imageSizeName",
"(",
"$",
"path",
",",
"$",
"imagen",
",",
"$",
"image_config",
")",
"{",
"$",
"result",
"=",
"array",
"(",
"\"name\"",
"=>",
"''",
",",
"\"width\"",
"=>",
"0",
",",
"\"height\"",
"=>",
"0",
")",
";",
"$",
"imag... | Devuelva el nuevo nombre y dimesion de imagen
@param string $path ruta relativa
@param string $imagen nombre de imagen
@param array $image_config dimensiones de imagenes
@return array | [
"Devuelva",
"el",
"nuevo",
"nombre",
"y",
"dimesion",
"de",
"imagen"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L477-L503 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.getImageCalSize | public function getImageCalSize($imagesize=array(),$image_config=array())
{
$r = array();
if(count($imagesize)>0 && isset($imagesize[0],$imagesize[1]) && count($image_config)>0){
if ($image_config[2]===true && $image_config[3]===null) {
$por = $image_config[0] / $imagesize[0];
$height = round($imagesize[1] * $por);
$r[0] = $image_config[0];
$r[1] = $height;
}elseif ($image_config[2]===null && $image_config[3]===true) {
$por = $image_config[1] / $imagesize[1];
$width = round($imagesize[0] * $por);
$r[0] = $width;
$r[1] = $image_config[1];
}else{
$r[0] = $image_config[0];
$r[1] = $image_config[1];
}
}
return $r;
} | php | public function getImageCalSize($imagesize=array(),$image_config=array())
{
$r = array();
if(count($imagesize)>0 && isset($imagesize[0],$imagesize[1]) && count($image_config)>0){
if ($image_config[2]===true && $image_config[3]===null) {
$por = $image_config[0] / $imagesize[0];
$height = round($imagesize[1] * $por);
$r[0] = $image_config[0];
$r[1] = $height;
}elseif ($image_config[2]===null && $image_config[3]===true) {
$por = $image_config[1] / $imagesize[1];
$width = round($imagesize[0] * $por);
$r[0] = $width;
$r[1] = $image_config[1];
}else{
$r[0] = $image_config[0];
$r[1] = $image_config[1];
}
}
return $r;
} | [
"public",
"function",
"getImageCalSize",
"(",
"$",
"imagesize",
"=",
"array",
"(",
")",
",",
"$",
"image_config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"r",
"=",
"array",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"imagesize",
")",
">",
"0",
"... | Calcula las dimensiones de la imagen
@param array $imagesize dimension de la imagen
@param array $image_config dimensiones de la imagen
@return array dimension de la nueva imagen | [
"Calcula",
"las",
"dimensiones",
"de",
"la",
"imagen"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L511-L531 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.upload | public function upload($file,$path){
if( $this->validExt($file->getClientOriginalName())){
if($file->getClientSize() > ($this->getMaxUploadFileSize() * 1024 * 1024) ){
$result = array("query"=>"BE_UPLOAD_FILE_SIZE_NOT_SERVER","params"=>array($file->getClientSize()));
$this->setInfo(array("msg"=>$result));
if( $this->config['debug'] ) $this->_log(__METHOD__." - file size no permitido server: ".$file->getClientSize());
return ;
}elseif($file->getClientSize() > ($this->config['upload']['size_max'] * 1024 * 1024) ){
$result = array("query"=>"BE_UPLOAD_FILE_SIZE_NOT_PERMITIDO","params"=>array($file->getClientSize()));
$this->setInfo(array("msg"=>$result));
if( $this->config['debug'] ) $this->_log(__METHOD__." - file size no permitido: ".$file->getClientSize());
return ;
}else{
if($file->isValid()){
$dir = $this->getFullPath().$path;
$namefile = $file->getClientOriginalName();
$namefile = $this->clearNameFile($namefile);
$nametemp = $namefile;
if( $this->config["upload"]["overwrite"] ==false){
$ext = $this->getExtension($namefile);
$i=0;
while(true){
$pathnametemp = $dir.$nametemp;
if(file_exists($pathnametemp)){
$i++;
$nametemp = $this->removeExtension( $namefile ) . '_' . $i . '.' . $ext ;
}else{
break;
}
}
}
$file->move($dir,$nametemp);
$file = new \SplFileInfo($dir.$nametemp);
return $file;
}
}
}else{
if( $this->config['debug'] ) $this->_log(__METHOD__." - file extension no permitido: ".$file->getExtension());
}
} | php | public function upload($file,$path){
if( $this->validExt($file->getClientOriginalName())){
if($file->getClientSize() > ($this->getMaxUploadFileSize() * 1024 * 1024) ){
$result = array("query"=>"BE_UPLOAD_FILE_SIZE_NOT_SERVER","params"=>array($file->getClientSize()));
$this->setInfo(array("msg"=>$result));
if( $this->config['debug'] ) $this->_log(__METHOD__." - file size no permitido server: ".$file->getClientSize());
return ;
}elseif($file->getClientSize() > ($this->config['upload']['size_max'] * 1024 * 1024) ){
$result = array("query"=>"BE_UPLOAD_FILE_SIZE_NOT_PERMITIDO","params"=>array($file->getClientSize()));
$this->setInfo(array("msg"=>$result));
if( $this->config['debug'] ) $this->_log(__METHOD__." - file size no permitido: ".$file->getClientSize());
return ;
}else{
if($file->isValid()){
$dir = $this->getFullPath().$path;
$namefile = $file->getClientOriginalName();
$namefile = $this->clearNameFile($namefile);
$nametemp = $namefile;
if( $this->config["upload"]["overwrite"] ==false){
$ext = $this->getExtension($namefile);
$i=0;
while(true){
$pathnametemp = $dir.$nametemp;
if(file_exists($pathnametemp)){
$i++;
$nametemp = $this->removeExtension( $namefile ) . '_' . $i . '.' . $ext ;
}else{
break;
}
}
}
$file->move($dir,$nametemp);
$file = new \SplFileInfo($dir.$nametemp);
return $file;
}
}
}else{
if( $this->config['debug'] ) $this->_log(__METHOD__." - file extension no permitido: ".$file->getExtension());
}
} | [
"public",
"function",
"upload",
"(",
"$",
"file",
",",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"validExt",
"(",
"$",
"file",
"->",
"getClientOriginalName",
"(",
")",
")",
")",
"{",
"if",
"(",
"$",
"file",
"->",
"getClientSize",
"(",
")... | Mueve un arcivo subido
@param UploadedFile $file
@param string $path
@return SplFileInfo|null | [
"Mueve",
"un",
"arcivo",
"subido"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L600-L643 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.uploadAll | public function uploadAll($files,$path){
if( is_array($files) && count($files) > 0 ){
$n = count($files);
if( $n <= $this->config['upload']['number'] ){
$res = array();
$notresult = array();
foreach ($files as $key => $value) {
$file = $this->upload($value,$path);
if( $file ){
$this->createThumb($file,$path);
$res[] = $file->getFilename();
}else{
$notresult[] = $value->getClientOriginalName();
}
}
$r = '';
$n2 = count($res);
$result = array("query"=>"BE_UPLOADALL_UPLOADS %s / %s","params"=>array($n2,$n));
if(count($notresult)>0){
$result['query'] = $result['query'].' | BE_UPLOADALL_NOT_UPLOADS ';
$i=0;
$n = count($notresult);
foreach ($notresult as $value) {
$result['query'] = $result['query'] . ' %s';
if( $n - 1 > $i ){
$result['query'] = $result['query'] . ',';
$value = $value.',';
}
$result['params'][] = $value;
$i++;
}
$this->setInfo(array("status"=>0));
}
$this->setInfo(array("msg"=>$result));
return $res;
}else{
$result = array("query"=>"BE_UPLOAD_MAX_UPLOAD %s","params"=>array($this->config['upload']['number']));
$this->setInfo(array("msg"=>$result,"status"=>0));
}
}else{
return ;
}
} | php | public function uploadAll($files,$path){
if( is_array($files) && count($files) > 0 ){
$n = count($files);
if( $n <= $this->config['upload']['number'] ){
$res = array();
$notresult = array();
foreach ($files as $key => $value) {
$file = $this->upload($value,$path);
if( $file ){
$this->createThumb($file,$path);
$res[] = $file->getFilename();
}else{
$notresult[] = $value->getClientOriginalName();
}
}
$r = '';
$n2 = count($res);
$result = array("query"=>"BE_UPLOADALL_UPLOADS %s / %s","params"=>array($n2,$n));
if(count($notresult)>0){
$result['query'] = $result['query'].' | BE_UPLOADALL_NOT_UPLOADS ';
$i=0;
$n = count($notresult);
foreach ($notresult as $value) {
$result['query'] = $result['query'] . ' %s';
if( $n - 1 > $i ){
$result['query'] = $result['query'] . ',';
$value = $value.',';
}
$result['params'][] = $value;
$i++;
}
$this->setInfo(array("status"=>0));
}
$this->setInfo(array("msg"=>$result));
return $res;
}else{
$result = array("query"=>"BE_UPLOAD_MAX_UPLOAD %s","params"=>array($this->config['upload']['number']));
$this->setInfo(array("msg"=>$result,"status"=>0));
}
}else{
return ;
}
} | [
"public",
"function",
"uploadAll",
"(",
"$",
"files",
",",
"$",
"path",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"files",
")",
"&&",
"count",
"(",
"$",
"files",
")",
">",
"0",
")",
"{",
"$",
"n",
"=",
"count",
"(",
"$",
"files",
")",
";",
"... | Upload all files
@param array $files
@param string $path
@return array|null | [
"Upload",
"all",
"files"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L651-L694 | train |
guillermomartinez/filemanager-php | src/GuillermoMartinez/Filemanager/Filemanager.php | Filemanager.newFolder | public function newFolder($namefile,$path){
$fullpath = $this->getFullPath().$path;
$namefile = $this->clearNameFile($namefile);
$namefile = $this->sanitizeNameFolder($namefile);
$dir = new Filesystem;
if($dir->exists($fullpath.$namefile)){
$result = array("query"=>"BE_NEW_FOLDER_EXISTED %s","params"=>array($path.$namefile));
$this->setInfo(array("msg"=>$result,"status"=>0));
if( $this->config['debug'] ) $this->_log(__METHOD__." - Ya existe: ".$path.$namefile);
return false;
}else{
$dir->mkdir($fullpath.$namefile);
$result = array("query"=>"BE_NEW_FOLDER_CREATED %s","params"=>array($path.$namefile));
$this->setInfo(array("msg"=>$result,"data"=>array( "path" => $path, "namefile" => $namefile )));
return true;
}
} | php | public function newFolder($namefile,$path){
$fullpath = $this->getFullPath().$path;
$namefile = $this->clearNameFile($namefile);
$namefile = $this->sanitizeNameFolder($namefile);
$dir = new Filesystem;
if($dir->exists($fullpath.$namefile)){
$result = array("query"=>"BE_NEW_FOLDER_EXISTED %s","params"=>array($path.$namefile));
$this->setInfo(array("msg"=>$result,"status"=>0));
if( $this->config['debug'] ) $this->_log(__METHOD__." - Ya existe: ".$path.$namefile);
return false;
}else{
$dir->mkdir($fullpath.$namefile);
$result = array("query"=>"BE_NEW_FOLDER_CREATED %s","params"=>array($path.$namefile));
$this->setInfo(array("msg"=>$result,"data"=>array( "path" => $path, "namefile" => $namefile )));
return true;
}
} | [
"public",
"function",
"newFolder",
"(",
"$",
"namefile",
",",
"$",
"path",
")",
"{",
"$",
"fullpath",
"=",
"$",
"this",
"->",
"getFullPath",
"(",
")",
".",
"$",
"path",
";",
"$",
"namefile",
"=",
"$",
"this",
"->",
"clearNameFile",
"(",
"$",
"namefil... | Renombra una carpeta
@param string $namefile
@param string $path
@return boolean | [
"Renombra",
"una",
"carpeta"
] | 5a0d1a68d17fe0dca0206958632a17d153f6389f | https://github.com/guillermomartinez/filemanager-php/blob/5a0d1a68d17fe0dca0206958632a17d153f6389f/src/GuillermoMartinez/Filemanager/Filemanager.php#L702-L718 | train |
findbrok/php-watson-api-bridge | src/WatsonBridgeServiceProvider.php | WatsonBridgeServiceProvider.registerDefaultBridge | protected function registerDefaultBridge()
{
$this->app->bind(Bridge::class, function (Application $app) {
/** @var Carpenter $carpenter */
$carpenter = $app->make(Carpenter::class);
/** @var Repository $config */
$config = $app->make(Repository::class);
return $carpenter->constructBridge(
$config->get('watson-bridge.default_credentials'),
null,
$config->get('watson-bridge.default_auth_method')
);
});
} | php | protected function registerDefaultBridge()
{
$this->app->bind(Bridge::class, function (Application $app) {
/** @var Carpenter $carpenter */
$carpenter = $app->make(Carpenter::class);
/** @var Repository $config */
$config = $app->make(Repository::class);
return $carpenter->constructBridge(
$config->get('watson-bridge.default_credentials'),
null,
$config->get('watson-bridge.default_auth_method')
);
});
} | [
"protected",
"function",
"registerDefaultBridge",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"Bridge",
"::",
"class",
",",
"function",
"(",
"Application",
"$",
"app",
")",
"{",
"/** @var Carpenter $carpenter */",
"$",
"carpenter",
"=",
"$",
... | Registers the Default Bridge. | [
"Registers",
"the",
"Default",
"Bridge",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/WatsonBridgeServiceProvider.php#L53-L67 | train |
findbrok/php-watson-api-bridge | src/Support/Carpenter.php | Carpenter.constructBridge | public function constructBridge($credential, $service = null, $authMethod = 'credentials')
{
// Get credentials array.
$credentials = $this->getCredentials($credential);
// Make sure credentials information is available.
if (! isset($credentials['username']) || ! isset($credentials['password']) || ! isset($credentials['gateway'])) {
throw new WatsonBridgeException('Could not construct Bridge, missing some information in credentials.',
500);
}
// Make bridge.
$bridge = $this->makeRawBridge()
->setUsername($credentials['username'])
->setPassword($credentials['password'])
->setEndPoint($credentials['gateway'])
->setClient($credentials['gateway'])
->appendHeaders(['X-Watson-Learning-Opt-Out' => config('watson-bridge.x_watson_learning_opt_out')]);
// Add service.
$bridge = $this->addServiceToBridge($bridge, $service);
// Choose an auth method.
$bridge = $this->chooseAuthMethodForBridge($bridge, $authMethod);
return $bridge;
} | php | public function constructBridge($credential, $service = null, $authMethod = 'credentials')
{
// Get credentials array.
$credentials = $this->getCredentials($credential);
// Make sure credentials information is available.
if (! isset($credentials['username']) || ! isset($credentials['password']) || ! isset($credentials['gateway'])) {
throw new WatsonBridgeException('Could not construct Bridge, missing some information in credentials.',
500);
}
// Make bridge.
$bridge = $this->makeRawBridge()
->setUsername($credentials['username'])
->setPassword($credentials['password'])
->setEndPoint($credentials['gateway'])
->setClient($credentials['gateway'])
->appendHeaders(['X-Watson-Learning-Opt-Out' => config('watson-bridge.x_watson_learning_opt_out')]);
// Add service.
$bridge = $this->addServiceToBridge($bridge, $service);
// Choose an auth method.
$bridge = $this->chooseAuthMethodForBridge($bridge, $authMethod);
return $bridge;
} | [
"public",
"function",
"constructBridge",
"(",
"$",
"credential",
",",
"$",
"service",
"=",
"null",
",",
"$",
"authMethod",
"=",
"'credentials'",
")",
"{",
"// Get credentials array.",
"$",
"credentials",
"=",
"$",
"this",
"->",
"getCredentials",
"(",
"$",
"cre... | Constructs a new Bridge.
@param string $credential
@param string $service
@param string $authMethod
@throws WatsonBridgeException
@return Bridge | [
"Constructs",
"a",
"new",
"Bridge",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Support/Carpenter.php#L20-L46 | train |
findbrok/php-watson-api-bridge | src/Support/Carpenter.php | Carpenter.addServiceToBridge | protected function addServiceToBridge(Bridge $bridge, $service = null)
{
// Add a service if necessary.
if (! is_null($service)) {
$bridge->usingService($service);
}
return $bridge;
} | php | protected function addServiceToBridge(Bridge $bridge, $service = null)
{
// Add a service if necessary.
if (! is_null($service)) {
$bridge->usingService($service);
}
return $bridge;
} | [
"protected",
"function",
"addServiceToBridge",
"(",
"Bridge",
"$",
"bridge",
",",
"$",
"service",
"=",
"null",
")",
"{",
"// Add a service if necessary.",
"if",
"(",
"!",
"is_null",
"(",
"$",
"service",
")",
")",
"{",
"$",
"bridge",
"->",
"usingService",
"("... | Adds a Service to the Bridge.
@param Bridge $bridge
@param string $service
@return Bridge | [
"Adds",
"a",
"Service",
"to",
"the",
"Bridge",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Support/Carpenter.php#L66-L74 | train |
findbrok/php-watson-api-bridge | src/Support/Carpenter.php | Carpenter.chooseAuthMethodForBridge | protected function chooseAuthMethodForBridge(Bridge $bridge, $username, $authMethod = null)
{
// Check if an auth method is passed explicitly.
if (! is_null($authMethod) && collect(config('watson-bridge.auth_methods'))->contains($authMethod)) {
$bridge->useAuthMethodAs($authMethod);
// Auth method is token so we need to set Token.
if ($authMethod == 'token') {
$bridge->setToken($username);
}
}
return $bridge;
} | php | protected function chooseAuthMethodForBridge(Bridge $bridge, $username, $authMethod = null)
{
// Check if an auth method is passed explicitly.
if (! is_null($authMethod) && collect(config('watson-bridge.auth_methods'))->contains($authMethod)) {
$bridge->useAuthMethodAs($authMethod);
// Auth method is token so we need to set Token.
if ($authMethod == 'token') {
$bridge->setToken($username);
}
}
return $bridge;
} | [
"protected",
"function",
"chooseAuthMethodForBridge",
"(",
"Bridge",
"$",
"bridge",
",",
"$",
"username",
",",
"$",
"authMethod",
"=",
"null",
")",
"{",
"// Check if an auth method is passed explicitly.",
"if",
"(",
"!",
"is_null",
"(",
"$",
"authMethod",
")",
"&&... | Choose an Auth Method for the Bridge.
@param Bridge $bridge
@param string $username
@param string $authMethod
@return Bridge | [
"Choose",
"an",
"Auth",
"Method",
"for",
"the",
"Bridge",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Support/Carpenter.php#L85-L98 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.setToken | public function setToken($username = null)
{
// Only set Token if Username is supplied.
if (! is_null($username)) {
$this->token = new Token($username);
}
return $this;
} | php | public function setToken($username = null)
{
// Only set Token if Username is supplied.
if (! is_null($username)) {
$this->token = new Token($username);
}
return $this;
} | [
"public",
"function",
"setToken",
"(",
"$",
"username",
"=",
"null",
")",
"{",
"// Only set Token if Username is supplied.",
"if",
"(",
"!",
"is_null",
"(",
"$",
"username",
")",
")",
"{",
"$",
"this",
"->",
"token",
"=",
"new",
"Token",
"(",
"$",
"usernam... | Sets the Token.
@param string $username
@return $this | [
"Sets",
"the",
"Token",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L142-L150 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.cleanOptions | public function cleanOptions($options = [])
{
// If item is null or empty we will remove them.
return collect($options)->reject(function ($item) {
return empty($item) || is_null($item);
})->all();
} | php | public function cleanOptions($options = [])
{
// If item is null or empty we will remove them.
return collect($options)->reject(function ($item) {
return empty($item) || is_null($item);
})->all();
} | [
"public",
"function",
"cleanOptions",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// If item is null or empty we will remove them.",
"return",
"collect",
"(",
"$",
"options",
")",
"->",
"reject",
"(",
"function",
"(",
"$",
"item",
")",
"{",
"return",
"empty... | Clean options by removing empty items.
@param array $options
@return array | [
"Clean",
"options",
"by",
"removing",
"empty",
"items",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L178-L184 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.failedRequest | public function failedRequest(Response $response)
{
// Decode Response.
$decodedResponse = json_decode($response->getBody()->getContents(), true);
// Get error message.
$errorMessage = (isset($decodedResponse['error_message']) && ! is_null($decodedResponse['error_message'])) ? $decodedResponse['error_message'] : $response->getReasonPhrase();
// ClientException.
throw new WatsonBridgeException($errorMessage, $response->getStatusCode());
} | php | public function failedRequest(Response $response)
{
// Decode Response.
$decodedResponse = json_decode($response->getBody()->getContents(), true);
// Get error message.
$errorMessage = (isset($decodedResponse['error_message']) && ! is_null($decodedResponse['error_message'])) ? $decodedResponse['error_message'] : $response->getReasonPhrase();
// ClientException.
throw new WatsonBridgeException($errorMessage, $response->getStatusCode());
} | [
"public",
"function",
"failedRequest",
"(",
"Response",
"$",
"response",
")",
"{",
"// Decode Response.",
"$",
"decodedResponse",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
",",
"true",
")",
";",
"// G... | Failed Request to Watson.
@param Response $response
@throws WatsonBridgeException | [
"Failed",
"Request",
"to",
"Watson",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L218-L226 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.fetchToken | public function fetchToken($incrementThrottle = false)
{
// Increment throttle if needed.
if ($incrementThrottle) {
$this->incrementThrottle();
}
// Reset Client.
$this->setClient($this->getAuthorizationEndpoint());
// Get the token response.
$response = $this->get('v1/token', [
'url' => $this->endpoint,
]);
// Extract.
$token = json_decode($response->getBody()->getContents(), true);
// Reset client.
$this->setClient($this->endpoint);
// Update token.
$this->token->updateToken($token['token']);
} | php | public function fetchToken($incrementThrottle = false)
{
// Increment throttle if needed.
if ($incrementThrottle) {
$this->incrementThrottle();
}
// Reset Client.
$this->setClient($this->getAuthorizationEndpoint());
// Get the token response.
$response = $this->get('v1/token', [
'url' => $this->endpoint,
]);
// Extract.
$token = json_decode($response->getBody()->getContents(), true);
// Reset client.
$this->setClient($this->endpoint);
// Update token.
$this->token->updateToken($token['token']);
} | [
"public",
"function",
"fetchToken",
"(",
"$",
"incrementThrottle",
"=",
"false",
")",
"{",
"// Increment throttle if needed.",
"if",
"(",
"$",
"incrementThrottle",
")",
"{",
"$",
"this",
"->",
"incrementThrottle",
"(",
")",
";",
"}",
"// Reset Client.",
"$",
"th... | Fetch token from Watson and Save it locally.
@param bool $incrementThrottle
@return void | [
"Fetch",
"token",
"from",
"Watson",
"and",
"Save",
"it",
"locally",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L235-L253 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.getAuthorizationEndpoint | public function getAuthorizationEndpoint()
{
// Parse the endpoint.
$parsedEndpoint = collect(parse_url($this->endpoint));
// Return auth url.
return $parsedEndpoint->get('scheme').'://'.$parsedEndpoint->get('host').'/authorization/api/';
} | php | public function getAuthorizationEndpoint()
{
// Parse the endpoint.
$parsedEndpoint = collect(parse_url($this->endpoint));
// Return auth url.
return $parsedEndpoint->get('scheme').'://'.$parsedEndpoint->get('host').'/authorization/api/';
} | [
"public",
"function",
"getAuthorizationEndpoint",
"(",
")",
"{",
"// Parse the endpoint.",
"$",
"parsedEndpoint",
"=",
"collect",
"(",
"parse_url",
"(",
"$",
"this",
"->",
"endpoint",
")",
")",
";",
"// Return auth url.",
"return",
"$",
"parsedEndpoint",
"->",
"ge... | Get the authorization endpoint for getting tokens.
@return string | [
"Get",
"the",
"authorization",
"endpoint",
"for",
"getting",
"tokens",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L285-L292 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.setClient | public function setClient($endpoint = null)
{
// Create client using API endpoint.
$this->client = new Client([
'base_uri' => ! is_null($endpoint) ? $endpoint : $this->endpoint,
]);
return $this;
} | php | public function setClient($endpoint = null)
{
// Create client using API endpoint.
$this->client = new Client([
'base_uri' => ! is_null($endpoint) ? $endpoint : $this->endpoint,
]);
return $this;
} | [
"public",
"function",
"setClient",
"(",
"$",
"endpoint",
"=",
"null",
")",
"{",
"// Create client using API endpoint.",
"$",
"this",
"->",
"client",
"=",
"new",
"Client",
"(",
"[",
"'base_uri'",
"=>",
"!",
"is_null",
"(",
"$",
"endpoint",
")",
"?",
"$",
"e... | Creates the http client.
@param string $endpoint
@return $this | [
"Creates",
"the",
"http",
"client",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L301-L309 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.usingService | public function usingService($serviceName)
{
// Check if service exists first.
if (! config()->has('watson-bridge.services.'.$serviceName)) {
throw new WatsonBridgeException('Unknown service "'.$serviceName.'" try adding it to the list of services in watson-bridge config.');
}
// Get service endpoint.
$serviceUrl = config('watson-bridge.services.'.$serviceName);
// Reset Client.
$this->setClient(rtrim($this->endpoint, '/').'/'.ltrim($serviceUrl, '/'));
return $this;
} | php | public function usingService($serviceName)
{
// Check if service exists first.
if (! config()->has('watson-bridge.services.'.$serviceName)) {
throw new WatsonBridgeException('Unknown service "'.$serviceName.'" try adding it to the list of services in watson-bridge config.');
}
// Get service endpoint.
$serviceUrl = config('watson-bridge.services.'.$serviceName);
// Reset Client.
$this->setClient(rtrim($this->endpoint, '/').'/'.ltrim($serviceUrl, '/'));
return $this;
} | [
"public",
"function",
"usingService",
"(",
"$",
"serviceName",
")",
"{",
"// Check if service exists first.",
"if",
"(",
"!",
"config",
"(",
")",
"->",
"has",
"(",
"'watson-bridge.services.'",
".",
"$",
"serviceName",
")",
")",
"{",
"throw",
"new",
"WatsonBridge... | Set Watson service being used.
@param string $serviceName
@return $this | [
"Set",
"Watson",
"service",
"being",
"used",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L329-L343 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.getRequestOptions | public function getRequestOptions($initial = [])
{
// Define options.
$options = collect($initial);
// Define an auth option.
if ($this->authMethod == 'credentials') {
$options = $options->merge(['auth' => $this->getAuth()]);
} elseif ($this->authMethod == 'token') {
$this->appendHeaders(['X-Watson-Authorization-Token' => $this->getToken()]);
}
// Put Headers in options.
$options = $options->merge(['headers' => $this->getHeaders()]);
// Clean and return.
return $this->cleanOptions($options->all());
} | php | public function getRequestOptions($initial = [])
{
// Define options.
$options = collect($initial);
// Define an auth option.
if ($this->authMethod == 'credentials') {
$options = $options->merge(['auth' => $this->getAuth()]);
} elseif ($this->authMethod == 'token') {
$this->appendHeaders(['X-Watson-Authorization-Token' => $this->getToken()]);
}
// Put Headers in options.
$options = $options->merge(['headers' => $this->getHeaders()]);
// Clean and return.
return $this->cleanOptions($options->all());
} | [
"public",
"function",
"getRequestOptions",
"(",
"$",
"initial",
"=",
"[",
"]",
")",
"{",
"// Define options.",
"$",
"options",
"=",
"collect",
"(",
"$",
"initial",
")",
";",
"// Define an auth option.",
"if",
"(",
"$",
"this",
"->",
"authMethod",
"==",
"'cre... | Get Request options to pass along.
@param array $initial
@return array | [
"Get",
"Request",
"options",
"to",
"pass",
"along",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L363-L380 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.request | public function request($method = 'GET', $uri = '', $options = [])
{
try {
// Make the request.
return $this->getClient()->request($method, $uri, $this->getRequestOptions($options));
} catch (ClientException $e) {
// We are using token auth and probably token expired.
if ($this->authMethod == 'token' && $e->getCode() == 401 && ! $this->isThrottledReached()) {
// Try refresh token.
$this->fetchToken(true);
// Try requesting again.
return $this->request($method, $uri, $options);
}
// Clear throttle for this request.
$this->clearThrottle();
// Call Failed Request.
$this->failedRequest($e->getResponse());
}
} | php | public function request($method = 'GET', $uri = '', $options = [])
{
try {
// Make the request.
return $this->getClient()->request($method, $uri, $this->getRequestOptions($options));
} catch (ClientException $e) {
// We are using token auth and probably token expired.
if ($this->authMethod == 'token' && $e->getCode() == 401 && ! $this->isThrottledReached()) {
// Try refresh token.
$this->fetchToken(true);
// Try requesting again.
return $this->request($method, $uri, $options);
}
// Clear throttle for this request.
$this->clearThrottle();
// Call Failed Request.
$this->failedRequest($e->getResponse());
}
} | [
"public",
"function",
"request",
"(",
"$",
"method",
"=",
"'GET'",
",",
"$",
"uri",
"=",
"''",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"try",
"{",
"// Make the request.",
"return",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"request",
"(",... | Make a Request to Watson with credentials Auth.
@param string $method
@param string $uri
@param array $options
@return \GuzzleHttp\Psr7\Response | [
"Make",
"a",
"Request",
"to",
"Watson",
"with",
"credentials",
"Auth",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L473-L492 | train |
findbrok/php-watson-api-bridge | src/Bridge.php | Bridge.send | private function send($method, $uri, $data, $type = 'json')
{
// Make the Request to Watson.
$response = $this->request($method, $uri, [$type => $data]);
// Request Failed.
if ($response->getStatusCode() != 200) {
// Throw Watson Bridge Exception.
$this->failedRequest($response);
}
// We return response.
return $response;
} | php | private function send($method, $uri, $data, $type = 'json')
{
// Make the Request to Watson.
$response = $this->request($method, $uri, [$type => $data]);
// Request Failed.
if ($response->getStatusCode() != 200) {
// Throw Watson Bridge Exception.
$this->failedRequest($response);
}
// We return response.
return $response;
} | [
"private",
"function",
"send",
"(",
"$",
"method",
",",
"$",
"uri",
",",
"$",
"data",
",",
"$",
"type",
"=",
"'json'",
")",
"{",
"// Make the Request to Watson.",
"$",
"response",
"=",
"$",
"this",
"->",
"request",
"(",
"$",
"method",
",",
"$",
"uri",
... | Send a Request to Watson.
@param string $method
@param string $uri
@param mixed $data
@param string $type
@return \GuzzleHttp\Psr7\Response | [
"Send",
"a",
"Request",
"to",
"Watson",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Bridge.php#L504-L516 | train |
findbrok/php-watson-api-bridge | src/Token.php | Token.isExpired | public function isExpired()
{
return $this->hasPayLoad() && ($this->payLoad['created'] + $this->payLoad['expires_in']) < Carbon::now()
->format('U');
} | php | public function isExpired()
{
return $this->hasPayLoad() && ($this->payLoad['created'] + $this->payLoad['expires_in']) < Carbon::now()
->format('U');
} | [
"public",
"function",
"isExpired",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"hasPayLoad",
"(",
")",
"&&",
"(",
"$",
"this",
"->",
"payLoad",
"[",
"'created'",
"]",
"+",
"$",
"this",
"->",
"payLoad",
"[",
"'expires_in'",
"]",
")",
"<",
"Carbon",
":... | Check that token is expired.
@return bool | [
"Check",
"that",
"token",
"is",
"expired",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Token.php#L67-L71 | train |
findbrok/php-watson-api-bridge | src/Token.php | Token.save | public function save()
{
// No payload to save.
if (! $this->hasPayLoad()) {
return false;
}
// Save the token.
return (bool) file_put_contents($this->getFilePath(), collect($this->payLoad)->toJson(), LOCK_EX);
} | php | public function save()
{
// No payload to save.
if (! $this->hasPayLoad()) {
return false;
}
// Save the token.
return (bool) file_put_contents($this->getFilePath(), collect($this->payLoad)->toJson(), LOCK_EX);
} | [
"public",
"function",
"save",
"(",
")",
"{",
"// No payload to save.",
"if",
"(",
"!",
"$",
"this",
"->",
"hasPayLoad",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Save the token.",
"return",
"(",
"bool",
")",
"file_put_contents",
"(",
"$",
"this"... | Saves a token.
@return bool | [
"Saves",
"a",
"token",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Token.php#L98-L107 | train |
findbrok/php-watson-api-bridge | src/Token.php | Token.updateToken | public function updateToken($token)
{
// Update Payload.
$this->payLoad = [
'token' => $token,
'expires_in' => 3600,
'created' => Carbon::now()->format('U'),
];
// Save token.
return $this->save();
} | php | public function updateToken($token)
{
// Update Payload.
$this->payLoad = [
'token' => $token,
'expires_in' => 3600,
'created' => Carbon::now()->format('U'),
];
// Save token.
return $this->save();
} | [
"public",
"function",
"updateToken",
"(",
"$",
"token",
")",
"{",
"// Update Payload.",
"$",
"this",
"->",
"payLoad",
"=",
"[",
"'token'",
"=>",
"$",
"token",
",",
"'expires_in'",
"=>",
"3600",
",",
"'created'",
"=>",
"Carbon",
"::",
"now",
"(",
")",
"->... | Update the token.
@param string $token
@return bool | [
"Update",
"the",
"token",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Token.php#L163-L174 | train |
findbrok/php-watson-api-bridge | src/Support/BridgeStack.php | BridgeStack.mountBridge | public function mountBridge($name, $credential, $service = null, $authMethod = 'credentials')
{
// Creates the Bridge.
$bridge = $this->carpenter->constructBridge($credential, $service, $authMethod);
// Save it under a name.
$this->put($name, $bridge);
return $this;
} | php | public function mountBridge($name, $credential, $service = null, $authMethod = 'credentials')
{
// Creates the Bridge.
$bridge = $this->carpenter->constructBridge($credential, $service, $authMethod);
// Save it under a name.
$this->put($name, $bridge);
return $this;
} | [
"public",
"function",
"mountBridge",
"(",
"$",
"name",
",",
"$",
"credential",
",",
"$",
"service",
"=",
"null",
",",
"$",
"authMethod",
"=",
"'credentials'",
")",
"{",
"// Creates the Bridge.",
"$",
"bridge",
"=",
"$",
"this",
"->",
"carpenter",
"->",
"co... | Mounts a Bridge on the stack.
@param string $name
@param string $credential
@param string $service
@param string $authMethod
@return $this | [
"Mounts",
"a",
"Bridge",
"on",
"the",
"stack",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Support/BridgeStack.php#L41-L50 | train |
findbrok/php-watson-api-bridge | src/Support/BridgeStack.php | BridgeStack.conjure | public function conjure($name)
{
// We must check if the Bridge does
// exists.
if (! $this->has($name)) {
throw new WatsonBridgeException('The Bridge with name "'.$name.'" does not exist.');
}
return $this->get($name);
} | php | public function conjure($name)
{
// We must check if the Bridge does
// exists.
if (! $this->has($name)) {
throw new WatsonBridgeException('The Bridge with name "'.$name.'" does not exist.');
}
return $this->get($name);
} | [
"public",
"function",
"conjure",
"(",
"$",
"name",
")",
"{",
"// We must check if the Bridge does",
"// exists.",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"WatsonBridgeException",
"(",
"'The Bridge with name \"'"... | Conjures a specific Bridge to use.
@param string $name
@throws WatsonBridgeException
@return Bridge | [
"Conjures",
"a",
"specific",
"Bridge",
"to",
"use",
"."
] | 468da14e6b9fd4fef4f58cd32dd6533b7013f5ba | https://github.com/findbrok/php-watson-api-bridge/blob/468da14e6b9fd4fef4f58cd32dd6533b7013f5ba/src/Support/BridgeStack.php#L60-L69 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/Deleter/RecursiveDirectoryDeleter.php | RecursiveDirectoryDeleter.deleteFiles | private function deleteFiles(Directory $path)
{
foreach ($this->manager->findFiles($path) as $file) {
$this->wrapper->delete($file->getRealpath());
}
} | php | private function deleteFiles(Directory $path)
{
foreach ($this->manager->findFiles($path) as $file) {
$this->wrapper->delete($file->getRealpath());
}
} | [
"private",
"function",
"deleteFiles",
"(",
"Directory",
"$",
"path",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"manager",
"->",
"findFiles",
"(",
"$",
"path",
")",
"as",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"wrapper",
"->",
"delete",
"(",
"$"... | Deletes files in a directory
@param string $path /remote/path/ | [
"Deletes",
"files",
"in",
"a",
"directory"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/Deleter/RecursiveDirectoryDeleter.php#L96-L101 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/Deleter/RecursiveDirectoryDeleter.php | RecursiveDirectoryDeleter.deleteDirectories | private function deleteDirectories(Directory $path, array $options = array())
{
foreach ($this->manager->findDirectories($path) as $dir) {
$this->delete($dir, $options);
}
} | php | private function deleteDirectories(Directory $path, array $options = array())
{
foreach ($this->manager->findDirectories($path) as $dir) {
$this->delete($dir, $options);
}
} | [
"private",
"function",
"deleteDirectories",
"(",
"Directory",
"$",
"path",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"manager",
"->",
"findDirectories",
"(",
"$",
"path",
")",
"as",
"$",
"dir",
"... | Deletes directories in a directory
@param Directory $path /remote/path/
@param array $options Deleter options | [
"Deletes",
"directories",
"in",
"a",
"directory"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/Deleter/RecursiveDirectoryDeleter.php#L109-L114 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/DeleterVoter.php | DeleterVoter.addVotable | public function addVotable(DeleterVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | php | public function addVotable(DeleterVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | [
"public",
"function",
"addVotable",
"(",
"DeleterVotableInterface",
"$",
"votable",
",",
"$",
"prepend",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"prepend",
")",
"{",
"array_unshift",
"(",
"$",
"this",
"->",
"votables",
",",
"$",
"votable",
")",
";",
"}",... | Adds a votable Deleter
@param DeleterVotableInterface $votable A votable Deleter
@param boolean $prepend Whether to prepend the votable | [
"Adds",
"a",
"votable",
"Deleter"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/DeleterVoter.php#L39-L46 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/DeleterVoter.php | DeleterVoter.addDefaultFTPDeleters | public function addDefaultFTPDeleters(FTPWrapper $wrapper, FTPFilesystemManager $manager)
{
$this->addVotable(new FTPDeleter\RecursiveDirectoryDeleter($wrapper, $manager));
$this->addVotable(new FTPDeleter\FileDeleter($wrapper, $manager));
} | php | public function addDefaultFTPDeleters(FTPWrapper $wrapper, FTPFilesystemManager $manager)
{
$this->addVotable(new FTPDeleter\RecursiveDirectoryDeleter($wrapper, $manager));
$this->addVotable(new FTPDeleter\FileDeleter($wrapper, $manager));
} | [
"public",
"function",
"addDefaultFTPDeleters",
"(",
"FTPWrapper",
"$",
"wrapper",
",",
"FTPFilesystemManager",
"$",
"manager",
")",
"{",
"$",
"this",
"->",
"addVotable",
"(",
"new",
"FTPDeleter",
"\\",
"RecursiveDirectoryDeleter",
"(",
"$",
"wrapper",
",",
"$",
... | Adds the default deleters
@param FTPWrapper $wrapper The FTPWrapper instance
@param FTPFilesystemManager $manager The Filesystem manager | [
"Adds",
"the",
"default",
"deleters"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/DeleterVoter.php#L54-L58 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/Connection/Connection.php | Connection.open | public function open()
{
if ($this->isConnected()) {
throw new ConnectionEstablishedException;
}
$stream = $this->doConnect();
if (false === $stream) {
throw new ConnectionException(sprintf("Could not connect to server %s:%s", $this->getHost(), $this->getPort()));
}
if (!@ftp_login($stream, $this->getUsername(), $this->getPassword())) {
throw new ConnectionException(sprintf(
"Could not login using combination of username (%s) and password (%s)",
$this->getUsername(),
preg_replace("/./", "*", $this->getPassword())
));
}
if (true === $this->passive) {
if (false === ftp_pasv($stream, true)) {
throw new ConnectionException("Cold not turn on passive mode");
}
}
$this->connected = true;
$this->stream = $stream;
return true;
} | php | public function open()
{
if ($this->isConnected()) {
throw new ConnectionEstablishedException;
}
$stream = $this->doConnect();
if (false === $stream) {
throw new ConnectionException(sprintf("Could not connect to server %s:%s", $this->getHost(), $this->getPort()));
}
if (!@ftp_login($stream, $this->getUsername(), $this->getPassword())) {
throw new ConnectionException(sprintf(
"Could not login using combination of username (%s) and password (%s)",
$this->getUsername(),
preg_replace("/./", "*", $this->getPassword())
));
}
if (true === $this->passive) {
if (false === ftp_pasv($stream, true)) {
throw new ConnectionException("Cold not turn on passive mode");
}
}
$this->connected = true;
$this->stream = $stream;
return true;
} | [
"public",
"function",
"open",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"throw",
"new",
"ConnectionEstablishedException",
";",
"}",
"$",
"stream",
"=",
"$",
"this",
"->",
"doConnect",
"(",
")",
";",
"if",
"(",
"f... | Opens the connection
@return boolean TRUE when connection suceeded
@throws ConnectionEstablishedException When connection is already running
@throws ConnectionException When connection to server failed
@throws ConnectionException When loging-in to server failed | [
"Opens",
"the",
"connection"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/Connection/Connection.php#L105-L135 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/UploaderVoter.php | UploaderVoter.addVotable | public function addVotable(UploaderVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | php | public function addVotable(UploaderVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | [
"public",
"function",
"addVotable",
"(",
"UploaderVotableInterface",
"$",
"votable",
",",
"$",
"prepend",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"prepend",
")",
"{",
"array_unshift",
"(",
"$",
"this",
"->",
"votables",
",",
"$",
"votable",
")",
";",
"}"... | Adds a votable uploader
@param UploaderVotableInterface $votable A votable uploader
@param boolean $prepend Whether to prepend the votable | [
"Adds",
"a",
"votable",
"uploader"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/UploaderVoter.php#L38-L45 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/UploaderVoter.php | UploaderVoter.addDefaultFTPUploaders | public function addDefaultFTPUploaders(FTPWrapper $wrapper)
{
$this->addVotable(new FTPUploader\FileUploader($wrapper));
$this->addVotable(new FTPUploader\ResourceUploader($wrapper));
$this->addVotable(new FTPUploader\NbFileUploader($wrapper));
$this->addVotable(new FTPUploader\NbResourceUploader($wrapper));
} | php | public function addDefaultFTPUploaders(FTPWrapper $wrapper)
{
$this->addVotable(new FTPUploader\FileUploader($wrapper));
$this->addVotable(new FTPUploader\ResourceUploader($wrapper));
$this->addVotable(new FTPUploader\NbFileUploader($wrapper));
$this->addVotable(new FTPUploader\NbResourceUploader($wrapper));
} | [
"public",
"function",
"addDefaultFTPUploaders",
"(",
"FTPWrapper",
"$",
"wrapper",
")",
"{",
"$",
"this",
"->",
"addVotable",
"(",
"new",
"FTPUploader",
"\\",
"FileUploader",
"(",
"$",
"wrapper",
")",
")",
";",
"$",
"this",
"->",
"addVotable",
"(",
"new",
... | Adds the default uploaders
@param FTPWrapper $wrapper An FTP Wrapper | [
"Adds",
"the",
"default",
"uploaders"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/UploaderVoter.php#L52-L58 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/DownloaderVoter.php | DownloaderVoter.addVotable | public function addVotable(DownloaderVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | php | public function addVotable(DownloaderVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | [
"public",
"function",
"addVotable",
"(",
"DownloaderVotableInterface",
"$",
"votable",
",",
"$",
"prepend",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"prepend",
")",
"{",
"array_unshift",
"(",
"$",
"this",
"->",
"votables",
",",
"$",
"votable",
")",
";",
"... | Adds a votable downloader
@param DownloaderVotableInterface $votable A votable downloader
@param boolean $prepend Whether to prepend the votable | [
"Adds",
"a",
"votable",
"downloader"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/DownloaderVoter.php#L38-L45 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/DownloaderVoter.php | DownloaderVoter.addDefaultFTPDownloaders | public function addDefaultFTPDownloaders(FTPWrapper $wrapper)
{
$this->addVotable(new FTPDownloader\FileDownloader($wrapper));
$this->addVotable(new FTPDownloader\ResourceDownloader($wrapper));
$this->addVotable(new FTPDownloader\NbFileDownloader($wrapper));
$this->addVotable(new FTPDownloader\NbResourceDownloader($wrapper));
} | php | public function addDefaultFTPDownloaders(FTPWrapper $wrapper)
{
$this->addVotable(new FTPDownloader\FileDownloader($wrapper));
$this->addVotable(new FTPDownloader\ResourceDownloader($wrapper));
$this->addVotable(new FTPDownloader\NbFileDownloader($wrapper));
$this->addVotable(new FTPDownloader\NbResourceDownloader($wrapper));
} | [
"public",
"function",
"addDefaultFTPDownloaders",
"(",
"FTPWrapper",
"$",
"wrapper",
")",
"{",
"$",
"this",
"->",
"addVotable",
"(",
"new",
"FTPDownloader",
"\\",
"FileDownloader",
"(",
"$",
"wrapper",
")",
")",
";",
"$",
"this",
"->",
"addVotable",
"(",
"ne... | Adds the default downloaders
@param FTPWrapper $wrapper An FTP Wrapper | [
"Adds",
"the",
"default",
"downloaders"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/DownloaderVoter.php#L52-L58 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/Manager/FTPFilesystemManager.php | FTPFilesystemManager.findFilesystemByName | public function findFilesystemByName($name, Directory $inDirectory = null)
{
$name = '/'.ltrim($name, '/');
$directory = dirname($name);
$directory = str_replace('\\', '/', $directory); // Issue #7
if ($inDirectory) {
$name = sprintf("/%s", ltrim($inDirectory->getRealpath().$name, '/'));
$directory = $inDirectory;
}
return $this->findOneBy($directory, function ($item) use ($name) {
return $name == $item->getRealpath();
});
} | php | public function findFilesystemByName($name, Directory $inDirectory = null)
{
$name = '/'.ltrim($name, '/');
$directory = dirname($name);
$directory = str_replace('\\', '/', $directory); // Issue #7
if ($inDirectory) {
$name = sprintf("/%s", ltrim($inDirectory->getRealpath().$name, '/'));
$directory = $inDirectory;
}
return $this->findOneBy($directory, function ($item) use ($name) {
return $name == $item->getRealpath();
});
} | [
"public",
"function",
"findFilesystemByName",
"(",
"$",
"name",
",",
"Directory",
"$",
"inDirectory",
"=",
"null",
")",
"{",
"$",
"name",
"=",
"'/'",
".",
"ltrim",
"(",
"$",
"name",
",",
"'/'",
")",
";",
"$",
"directory",
"=",
"dirname",
"(",
"$",
"n... | Finds a filesystem by its name
@param string $name Filesystem name
@param Directory|null $inDirectory Directory to fetch in
@return Filesystem | [
"Finds",
"a",
"filesystem",
"by",
"its",
"name"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/Manager/FTPFilesystemManager.php#L183-L197 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/Manager/FTPFilesystemManager.php | FTPFilesystemManager.getCwd | public function getCwd()
{
$path = $this->wrapper->pwd();
if ('/' === $path) {
return new Directory('/');
}
return $this->findDirectoryByName($path);
} | php | public function getCwd()
{
$path = $this->wrapper->pwd();
if ('/' === $path) {
return new Directory('/');
}
return $this->findDirectoryByName($path);
} | [
"public",
"function",
"getCwd",
"(",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"wrapper",
"->",
"pwd",
"(",
")",
";",
"if",
"(",
"'/'",
"===",
"$",
"path",
")",
"{",
"return",
"new",
"Directory",
"(",
"'/'",
")",
";",
"}",
"return",
"$",
"... | Returns the current working directory
@return Directory Current directory | [
"Returns",
"the",
"current",
"working",
"directory"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/Manager/FTPFilesystemManager.php#L281-L290 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/PermissionsFactory.php | PermissionsFactory.build | public function build($input)
{
if (strlen($input) != 3) {
throw new \InvalidArgumentException(sprintf("%s is not a valid permission input", $input));
}
$perms = 0;
if ('r' === substr($input, 0, 1)) {
$perms |= Permissions::READABLE;
}
if ('w' === substr($input, 1, 1)) {
$perms |= Permissions::WRITABLE;
}
if ('x' === substr($input, 2, 1)) {
$perms |= Permissions::EXECUTABLE;
}
$permissions = new Permissions;
$permissions->setFlags($perms);
return $permissions;
} | php | public function build($input)
{
if (strlen($input) != 3) {
throw new \InvalidArgumentException(sprintf("%s is not a valid permission input", $input));
}
$perms = 0;
if ('r' === substr($input, 0, 1)) {
$perms |= Permissions::READABLE;
}
if ('w' === substr($input, 1, 1)) {
$perms |= Permissions::WRITABLE;
}
if ('x' === substr($input, 2, 1)) {
$perms |= Permissions::EXECUTABLE;
}
$permissions = new Permissions;
$permissions->setFlags($perms);
return $permissions;
} | [
"public",
"function",
"build",
"(",
"$",
"input",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"input",
")",
"!=",
"3",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"%s is not a valid permission input\"",
",",
"$",
"input",
... | Builds a Permissions object
@param string $input Permissions string
@return Permissions | [
"Builds",
"a",
"Permissions",
"object"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/PermissionsFactory.php#L34-L58 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/CreatorVoter.php | CreatorVoter.addVotable | public function addVotable(CreatorVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | php | public function addVotable(CreatorVotableInterface $votable, $prepend = false)
{
if ($prepend) {
array_unshift($this->votables, $votable);
} else {
$this->votables[] = $votable;
}
} | [
"public",
"function",
"addVotable",
"(",
"CreatorVotableInterface",
"$",
"votable",
",",
"$",
"prepend",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"prepend",
")",
"{",
"array_unshift",
"(",
"$",
"this",
"->",
"votables",
",",
"$",
"votable",
")",
";",
"}",... | Adds a votable Creator
@param CreatorVotableInterface $votable A votable Creator
@param boolean $prepend Whether to prepend the votable | [
"Adds",
"a",
"votable",
"Creator"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/CreatorVoter.php#L39-L46 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/CreatorVoter.php | CreatorVoter.addDefaultFTPCreators | public function addDefaultFTPCreators(FTPWrapper $wrapper, FTPFilesystemManager $manager)
{
$this->addVotable(new FTPCreator\RecursiveDirectoryCreator($wrapper, $manager));
} | php | public function addDefaultFTPCreators(FTPWrapper $wrapper, FTPFilesystemManager $manager)
{
$this->addVotable(new FTPCreator\RecursiveDirectoryCreator($wrapper, $manager));
} | [
"public",
"function",
"addDefaultFTPCreators",
"(",
"FTPWrapper",
"$",
"wrapper",
",",
"FTPFilesystemManager",
"$",
"manager",
")",
"{",
"$",
"this",
"->",
"addVotable",
"(",
"new",
"FTPCreator",
"\\",
"RecursiveDirectoryCreator",
"(",
"$",
"wrapper",
",",
"$",
... | Adds the default creators
@param FTPWrapper $wrapper The FTPWrapper instance
@param FTPFilesystemManager $manager The Filesystem manager | [
"Adds",
"the",
"default",
"creators"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/CreatorVoter.php#L54-L57 | train |
touki653/php-ftp-wrapper | lib/Touki/FTP/FTPFactory.php | FTPFactory.build | public function build(ConnectionInterface $connection)
{
if (!$connection->isConnected()) {
$connection->open();
}
if (null === $this->wrapper) {
$this->wrapper = new FTPWrapper($connection);
}
if (null === $this->manager) {
if (null === $this->fsFactory) {
$this->fsFactory = new FilesystemFactory(new PermissionsFactory);
}
$this->manager = new FTPFilesystemManager($this->wrapper, $this->fsFactory);
}
if (null === $this->dlVoter) {
$this->dlVoter = new DownloaderVoter;
$this->dlVoter->addDefaultFTPDownloaders($this->wrapper);
}
if (null === $this->ulVoter) {
$this->ulVoter = new UploaderVoter;
$this->ulVoter->addDefaultFTPUploaders($this->wrapper);
}
if (null === $this->crVoter) {
$this->crVoter = new CreatorVoter;
$this->crVoter->addDefaultFTPCreators($this->wrapper, $this->manager);
}
if (null === $this->deVoter) {
$this->deVoter = new DeleterVoter;
$this->deVoter->addDefaultFTPDeleters($this->wrapper, $this->manager);
}
return new FTP($this->manager, $this->dlVoter, $this->ulVoter, $this->crVoter, $this->deVoter);
} | php | public function build(ConnectionInterface $connection)
{
if (!$connection->isConnected()) {
$connection->open();
}
if (null === $this->wrapper) {
$this->wrapper = new FTPWrapper($connection);
}
if (null === $this->manager) {
if (null === $this->fsFactory) {
$this->fsFactory = new FilesystemFactory(new PermissionsFactory);
}
$this->manager = new FTPFilesystemManager($this->wrapper, $this->fsFactory);
}
if (null === $this->dlVoter) {
$this->dlVoter = new DownloaderVoter;
$this->dlVoter->addDefaultFTPDownloaders($this->wrapper);
}
if (null === $this->ulVoter) {
$this->ulVoter = new UploaderVoter;
$this->ulVoter->addDefaultFTPUploaders($this->wrapper);
}
if (null === $this->crVoter) {
$this->crVoter = new CreatorVoter;
$this->crVoter->addDefaultFTPCreators($this->wrapper, $this->manager);
}
if (null === $this->deVoter) {
$this->deVoter = new DeleterVoter;
$this->deVoter->addDefaultFTPDeleters($this->wrapper, $this->manager);
}
return new FTP($this->manager, $this->dlVoter, $this->ulVoter, $this->crVoter, $this->deVoter);
} | [
"public",
"function",
"build",
"(",
"ConnectionInterface",
"$",
"connection",
")",
"{",
"if",
"(",
"!",
"$",
"connection",
"->",
"isConnected",
"(",
")",
")",
"{",
"$",
"connection",
"->",
"open",
"(",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"t... | Creates an FTP instance
@return FTP An FTP instance | [
"Creates",
"an",
"FTP",
"instance"
] | 318595fb8b1bff215b4af092c3faae83a532b822 | https://github.com/touki653/php-ftp-wrapper/blob/318595fb8b1bff215b4af092c3faae83a532b822/lib/Touki/FTP/FTPFactory.php#L168-L207 | train |
borodulin/yii2-oauth2-server | src/request/AccessTokenExtractor.php | AccessTokenExtractor.extract | public function extract()
{
$headerToken = null;
foreach ($this->_request->getHeaders()->get('Authorization', [], false) as $authHeader) {
if (preg_match('/^Bearer\\s+(.*?)$/', $authHeader, $matches)) {
$headerToken = $matches[1];
break;
}
}
$postToken = $this->_request->post('access_token');
$getToken = $this->_request->get('access_token');
// Check that exactly one method was used
$methodsCount = isset($headerToken) + isset($postToken) + isset($getToken);
if ($methodsCount > 1) {
throw new Exception(Yii::t('conquer/oauth2', 'Only one method may be used to authenticate at a time (Auth header, POST or GET).'));
} elseif ($methodsCount === 0) {
throw new Exception(Yii::t('conquer/oauth2', 'The access token was not found.'));
}
// HEADER: Get the access token from the header
if ($headerToken) {
return $headerToken;
}
// POST: Get the token from POST data
if ($postToken) {
if (!$this->_request->isPost) {
throw new Exception(Yii::t('conquer/oauth2', 'When putting the token in the body, the method must be POST.'));
}
// IETF specifies content-type. NB: Not all webservers populate this _SERVER variable
if (strpos($this->_request->contentType, 'application/x-www-form-urlencoded') !== 0) {
throw new Exception(Yii::t('conquer/oauth2', 'The content type for POST requests must be "application/x-www-form-urlencoded".'));
}
return $postToken;
}
return $getToken;
} | php | public function extract()
{
$headerToken = null;
foreach ($this->_request->getHeaders()->get('Authorization', [], false) as $authHeader) {
if (preg_match('/^Bearer\\s+(.*?)$/', $authHeader, $matches)) {
$headerToken = $matches[1];
break;
}
}
$postToken = $this->_request->post('access_token');
$getToken = $this->_request->get('access_token');
// Check that exactly one method was used
$methodsCount = isset($headerToken) + isset($postToken) + isset($getToken);
if ($methodsCount > 1) {
throw new Exception(Yii::t('conquer/oauth2', 'Only one method may be used to authenticate at a time (Auth header, POST or GET).'));
} elseif ($methodsCount === 0) {
throw new Exception(Yii::t('conquer/oauth2', 'The access token was not found.'));
}
// HEADER: Get the access token from the header
if ($headerToken) {
return $headerToken;
}
// POST: Get the token from POST data
if ($postToken) {
if (!$this->_request->isPost) {
throw new Exception(Yii::t('conquer/oauth2', 'When putting the token in the body, the method must be POST.'));
}
// IETF specifies content-type. NB: Not all webservers populate this _SERVER variable
if (strpos($this->_request->contentType, 'application/x-www-form-urlencoded') !== 0) {
throw new Exception(Yii::t('conquer/oauth2', 'The content type for POST requests must be "application/x-www-form-urlencoded".'));
}
return $postToken;
}
return $getToken;
} | [
"public",
"function",
"extract",
"(",
")",
"{",
"$",
"headerToken",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"_request",
"->",
"getHeaders",
"(",
")",
"->",
"get",
"(",
"'Authorization'",
",",
"[",
"]",
",",
"false",
")",
"as",
"$",
"auth... | Extracts access_token from web request
@return string
@throws Exception | [
"Extracts",
"access_token",
"from",
"web",
"request"
] | 6fab7c342677934bc0a85341979b95717480ae91 | https://github.com/borodulin/yii2-oauth2-server/blob/6fab7c342677934bc0a85341979b95717480ae91/src/request/AccessTokenExtractor.php#L34-L72 | train |
borodulin/yii2-oauth2-server | src/AuthorizeFilter.php | AuthorizeFilter.finishAuthorization | public function finishAuthorization()
{
/** @var Authorization $responseType */
$responseType = $this->getResponseType();
if (Yii::$app->user->isGuest) {
$responseType->errorRedirect(Yii::t('conquer/oauth2', 'The User denied access to your application.'), Exception::ACCESS_DENIED);
}
$parts = $responseType->getResponseData();
$redirectUri = http_build_url($responseType->redirect_uri, $parts, HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT);
if (isset($parts['fragment'])) {
$redirectUri .= '#' . $parts['fragment'];
}
Yii::$app->response->redirect($redirectUri);
} | php | public function finishAuthorization()
{
/** @var Authorization $responseType */
$responseType = $this->getResponseType();
if (Yii::$app->user->isGuest) {
$responseType->errorRedirect(Yii::t('conquer/oauth2', 'The User denied access to your application.'), Exception::ACCESS_DENIED);
}
$parts = $responseType->getResponseData();
$redirectUri = http_build_url($responseType->redirect_uri, $parts, HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT);
if (isset($parts['fragment'])) {
$redirectUri .= '#' . $parts['fragment'];
}
Yii::$app->response->redirect($redirectUri);
} | [
"public",
"function",
"finishAuthorization",
"(",
")",
"{",
"/** @var Authorization $responseType */",
"$",
"responseType",
"=",
"$",
"this",
"->",
"getResponseType",
"(",
")",
";",
"if",
"(",
"Yii",
"::",
"$",
"app",
"->",
"user",
"->",
"isGuest",
")",
"{",
... | Finish oauth authorization.
Builds redirect uri and performs redirect.
If user is not logged on, redirect contains the Access Denied Error | [
"Finish",
"oauth",
"authorization",
".",
"Builds",
"redirect",
"uri",
"and",
"performs",
"redirect",
".",
"If",
"user",
"is",
"not",
"logged",
"on",
"redirect",
"contains",
"the",
"Access",
"Denied",
"Error"
] | 6fab7c342677934bc0a85341979b95717480ae91 | https://github.com/borodulin/yii2-oauth2-server/blob/6fab7c342677934bc0a85341979b95717480ae91/src/AuthorizeFilter.php#L110-L126 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/PermissionsController.php | PermissionsController.index | public function index()
{
$permissions = $this->permissions->all();
return View::make(Config::get('cpanel::views.permissions_index'))
->with('permissions', $permissions);
} | php | public function index()
{
$permissions = $this->permissions->all();
return View::make(Config::get('cpanel::views.permissions_index'))
->with('permissions', $permissions);
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"permissions",
"=",
"$",
"this",
"->",
"permissions",
"->",
"all",
"(",
")",
";",
"return",
"View",
"::",
"make",
"(",
"Config",
"::",
"get",
"(",
"'cpanel::views.permissions_index'",
")",
")",
"->",
"wi... | Display all the permissions
@author Steve Montambeault
@link http://stevemo.ca
@return \Illuminate\View\View | [
"Display",
"all",
"the",
"permissions"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/PermissionsController.php#L38-L44 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/PermissionsController.php | PermissionsController.edit | public function edit($id)
{
$permission = $this->permissions->find($id);
if ( $permission )
{
return View::make( Config::get('cpanel::views.permissions_edit') )
->with('permission', $permission);
}
else
{
return Redirect::route('cpanel.permissions.index')
->with('error', Lang::get('cpanel::permissions.model_not_found'));
}
} | php | public function edit($id)
{
$permission = $this->permissions->find($id);
if ( $permission )
{
return View::make( Config::get('cpanel::views.permissions_edit') )
->with('permission', $permission);
}
else
{
return Redirect::route('cpanel.permissions.index')
->with('error', Lang::get('cpanel::permissions.model_not_found'));
}
} | [
"public",
"function",
"edit",
"(",
"$",
"id",
")",
"{",
"$",
"permission",
"=",
"$",
"this",
"->",
"permissions",
"->",
"find",
"(",
"$",
"id",
")",
";",
"if",
"(",
"$",
"permission",
")",
"{",
"return",
"View",
"::",
"make",
"(",
"Config",
"::",
... | Display the edit permission form
@author Steve Montambeault
@link http://stevemo.ca
@param $id
@return \Illuminate\Http\RedirectResponse|\Illuminate\View\View | [
"Display",
"the",
"edit",
"permission",
"form"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/PermissionsController.php#L69-L83 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/PermissionsController.php | PermissionsController.store | public function store()
{
$inputs = Input::all();
if ( $this->form->create($inputs) )
{
return Redirect::route('cpanel.permissions.index')
->with('success', Lang::get('cpanel::permissions.create_success'));
}
return Redirect::back()
->withInput()
->withErrors($this->form->getErrors());
} | php | public function store()
{
$inputs = Input::all();
if ( $this->form->create($inputs) )
{
return Redirect::route('cpanel.permissions.index')
->with('success', Lang::get('cpanel::permissions.create_success'));
}
return Redirect::back()
->withInput()
->withErrors($this->form->getErrors());
} | [
"public",
"function",
"store",
"(",
")",
"{",
"$",
"inputs",
"=",
"Input",
"::",
"all",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"form",
"->",
"create",
"(",
"$",
"inputs",
")",
")",
"{",
"return",
"Redirect",
"::",
"route",
"(",
"'cpanel.permi... | Save new permissions into the database
@author Steve Montambeault
@link http://stevemo.ca
@return \Illuminate\Http\RedirectResponse | [
"Save",
"new",
"permissions",
"into",
"the",
"database"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/PermissionsController.php#L94-L107 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/PermissionsController.php | PermissionsController.update | public function update($id)
{
$inputs = Input::all();
$inputs['id'] = $id;
try
{
if ( $this->form->update($inputs) )
{
return Redirect::route('cpanel.permissions.index')
->with('success', Lang::get('cpanel::permissions.update_success'));
}
return Redirect::back()
->withInput()
->withErrors($this->form->getErrors());
}
catch ( PermissionNotFoundException $e )
{
return Redirect::route('cpanel.permissions.index')
->with('error', Lang::get('cpanel::permissions.model_not_found'));
}
} | php | public function update($id)
{
$inputs = Input::all();
$inputs['id'] = $id;
try
{
if ( $this->form->update($inputs) )
{
return Redirect::route('cpanel.permissions.index')
->with('success', Lang::get('cpanel::permissions.update_success'));
}
return Redirect::back()
->withInput()
->withErrors($this->form->getErrors());
}
catch ( PermissionNotFoundException $e )
{
return Redirect::route('cpanel.permissions.index')
->with('error', Lang::get('cpanel::permissions.model_not_found'));
}
} | [
"public",
"function",
"update",
"(",
"$",
"id",
")",
"{",
"$",
"inputs",
"=",
"Input",
"::",
"all",
"(",
")",
";",
"$",
"inputs",
"[",
"'id'",
"]",
"=",
"$",
"id",
";",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"form",
"->",
"update",
"(",
"$... | Process the edit form
@author Steve Montambeault
@link http://stevemo.ca
@param $id
@return \Illuminate\Http\RedirectResponse | [
"Process",
"the",
"edit",
"form"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/PermissionsController.php#L119-L141 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/PermissionsController.php | PermissionsController.destroy | public function destroy($id)
{
if ( $this->permissions->delete($id) )
{
return Redirect::route('cpanel.permissions.index')
->with('success', Lang::get('cpanel::permissions.delete_success'));
}
else
{
return Redirect::route('cpanel.permissions.index')
->with('error', Lang::get('cpanel::permissions.model_not_found'));
}
} | php | public function destroy($id)
{
if ( $this->permissions->delete($id) )
{
return Redirect::route('cpanel.permissions.index')
->with('success', Lang::get('cpanel::permissions.delete_success'));
}
else
{
return Redirect::route('cpanel.permissions.index')
->with('error', Lang::get('cpanel::permissions.model_not_found'));
}
} | [
"public",
"function",
"destroy",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"permissions",
"->",
"delete",
"(",
"$",
"id",
")",
")",
"{",
"return",
"Redirect",
"::",
"route",
"(",
"'cpanel.permissions.index'",
")",
"->",
"with",
"(",
"'suc... | Delete a permission module
@author Steve Montambeault
@link http://stevemo.ca
@param $id
@return \Illuminate\Http\RedirectResponse | [
"Delete",
"a",
"permission",
"module"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/PermissionsController.php#L153-L165 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Services/Validation/AbstractValidator.php | AbstractValidator.passes | public function passes()
{
$validator = $this->validator->make($this->data, $this->rules, $this->messages);
if( $validator->fails() )
{
$this->errors = $validator->messages();
return false;
}
return true;
} | php | public function passes()
{
$validator = $this->validator->make($this->data, $this->rules, $this->messages);
if( $validator->fails() )
{
$this->errors = $validator->messages();
return false;
}
return true;
} | [
"public",
"function",
"passes",
"(",
")",
"{",
"$",
"validator",
"=",
"$",
"this",
"->",
"validator",
"->",
"make",
"(",
"$",
"this",
"->",
"data",
",",
"$",
"this",
"->",
"rules",
",",
"$",
"this",
"->",
"messages",
")",
";",
"if",
"(",
"$",
"va... | Test if validation passes
@author Steve Montambeault
@link http://stevemo.ca
@return bool | [
"Test",
"if",
"validation",
"passes"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Services/Validation/AbstractValidator.php#L80-L91 | train |
nwtn/php-respimg | src/Respimg.php | Respimg.optimize | public static function optimize($path, $svgo = 0, $image_optim = 0, $picopt = 0, $imageOptim = 0) {
// make sure the path is real
if (!file_exists($path)) {
return false;
}
$is_dir = is_dir($path);
if (!$is_dir) {
$dir = escapeshellarg(substr($path, 0, strrpos($path, '/')));
$file = escapeshellarg(substr($path, strrpos($path, '/') + 1));
}
$path = escapeshellarg($path);
// make sure we got some ints up in here
$svgo = (int) $svgo;
$image_optim = (int) $image_optim;
$picopt = (int) $picopt;
$imageOptim = (int) $imageOptim;
// create some vars to store output
$output = array();
$return_var = 0;
// if we’re using image_optim, we need to create the YAML config file
if ($image_optim > 0) {
$yml = tempnam('/tmp', 'yml');
file_put_contents($yml, "verbose: true\njpegtran:\n progressive: false\noptipng:\n level: 7\n interlace: false\npngcrush:\n fix: true\n brute: true\npngquant:\n speed: 11\n");
}
// do the svgo optimizations
for ($i = 0; $i < $svgo; $i++) {
if ($is_dir) {
$command = escapeshellcmd('svgo -f ' . $path . ' --disable removeUnknownsAndDefaults');
} else {
$command = escapeshellcmd('svgo -i ' . $path . ' --disable removeUnknownsAndDefaults');
}
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
// do the image_optim optimizations
for ($i = 0; $i < $image_optim; $i++) {
$command = escapeshellcmd('image_optim -r ' . $path . ' --config-paths ' . $yml);
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
// do the picopt optimizations
for ($i = 0; $i < $picopt; $i++) {
$command = escapeshellcmd('picopt -r ' . $path);
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
// do the ImageOptim optimizations
// ImageOptim can’t handle the path with single quotes, so we have to strip them
// ImageOptim-CLI has an issue where it only works with a directory, not a single file
for ($i = 0; $i < $imageOptim; $i++) {
if ($is_dir) {
$command = escapeshellcmd('imageoptim -d ' . $path . ' -q');
} else {
$command = escapeshellcmd('find ' . $dir . ' -name ' . $file) . ' | imageoptim';
}
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
return $output;
} | php | public static function optimize($path, $svgo = 0, $image_optim = 0, $picopt = 0, $imageOptim = 0) {
// make sure the path is real
if (!file_exists($path)) {
return false;
}
$is_dir = is_dir($path);
if (!$is_dir) {
$dir = escapeshellarg(substr($path, 0, strrpos($path, '/')));
$file = escapeshellarg(substr($path, strrpos($path, '/') + 1));
}
$path = escapeshellarg($path);
// make sure we got some ints up in here
$svgo = (int) $svgo;
$image_optim = (int) $image_optim;
$picopt = (int) $picopt;
$imageOptim = (int) $imageOptim;
// create some vars to store output
$output = array();
$return_var = 0;
// if we’re using image_optim, we need to create the YAML config file
if ($image_optim > 0) {
$yml = tempnam('/tmp', 'yml');
file_put_contents($yml, "verbose: true\njpegtran:\n progressive: false\noptipng:\n level: 7\n interlace: false\npngcrush:\n fix: true\n brute: true\npngquant:\n speed: 11\n");
}
// do the svgo optimizations
for ($i = 0; $i < $svgo; $i++) {
if ($is_dir) {
$command = escapeshellcmd('svgo -f ' . $path . ' --disable removeUnknownsAndDefaults');
} else {
$command = escapeshellcmd('svgo -i ' . $path . ' --disable removeUnknownsAndDefaults');
}
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
// do the image_optim optimizations
for ($i = 0; $i < $image_optim; $i++) {
$command = escapeshellcmd('image_optim -r ' . $path . ' --config-paths ' . $yml);
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
// do the picopt optimizations
for ($i = 0; $i < $picopt; $i++) {
$command = escapeshellcmd('picopt -r ' . $path);
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
// do the ImageOptim optimizations
// ImageOptim can’t handle the path with single quotes, so we have to strip them
// ImageOptim-CLI has an issue where it only works with a directory, not a single file
for ($i = 0; $i < $imageOptim; $i++) {
if ($is_dir) {
$command = escapeshellcmd('imageoptim -d ' . $path . ' -q');
} else {
$command = escapeshellcmd('find ' . $dir . ' -name ' . $file) . ' | imageoptim';
}
exec($command, $output, $return_var);
if ($return_var != 0) {
return false;
}
}
return $output;
} | [
"public",
"static",
"function",
"optimize",
"(",
"$",
"path",
",",
"$",
"svgo",
"=",
"0",
",",
"$",
"image_optim",
"=",
"0",
",",
"$",
"picopt",
"=",
"0",
",",
"$",
"imageOptim",
"=",
"0",
")",
"{",
"// make sure the path is real",
"if",
"(",
"!",
"f... | Optimizes the image without reducing quality.
This function calls up to four external programs, which must be installed and available in the $PATH:
* SVGO
* image_optim
* picopt
* ImageOptim
Note that these are executed using PHP’s `exec` command, so there may be security implications.
@access public
@param string $path The path to the file or directory that should be optimized.
@param integer $svgo The number of times to optimize using SVGO.
@param integer $image_optim The number of times to optimize using image_optim.
@param integer $picopt The number of times to optimize using picopt.
@param integer $imageOptim The number of times to optimize using ImageOptim. | [
"Optimizes",
"the",
"image",
"without",
"reducing",
"quality",
"."
] | 9bb067726b479ff362202529f4c98b53a53a04c1 | https://github.com/nwtn/php-respimg/blob/9bb067726b479ff362202529f4c98b53a53a04c1/src/Respimg.php#L62-L143 | train |
nwtn/php-respimg | src/Respimg.php | Respimg.rasterize | public static function rasterize($file, $dest, $columns, $rows) {
// check the input
if (!file_exists($file)) {
return false;
}
if (!file_exists($dest) || !is_dir($dest)) {
return false;
}
// figure out the output width and height
$svgTmp = new Respimg($file);
$width = (double) $svgTmp->getImageWidth();
$height = (double) $svgTmp->getImageHeight();
$new_width = $columns;
$new_height = $rows;
$x_factor = $columns / $width;
$y_factor = $rows / $height;
if ($rows < 1) {
$new_height = round($x_factor * $height);
} elseif ($columns < 1) {
$new_width = round($y_factor * $width);
}
// get the svg data
$svgdata = file_get_contents($file);
// figure out some path stuff
$dest = rtrim($dest, '/');
$filename = substr($file, strrpos($file, '/') + 1);
$filename_base = substr($filename, 0, strrpos($filename, '.'));
// setup the request
$client = Client::getInstance();
$serviceContainer = ServiceContainer::getInstance();
$procedureLoaderFactory = $serviceContainer->get('procedure_loader_factory');
$procedureLoader = $procedureLoaderFactory->createProcedureLoader(__DIR__);
$client->getProcedureLoader()->addLoader($procedureLoader);
$request = new RespimgCaptureRequest();
$request->setType('svg2png');
$request->setMethod('GET');
$request->setSVG(base64_encode($svgdata));
$request->setViewportSize($new_width, $new_height);
$request->setRasterFile($dest . '/' . $filename_base . '-w' . $new_width . '.png');
$request->setWidth($new_width);
$request->setHeight($new_height);
$response = $client->getMessageFactory()->createResponse();
// send + return
$client->send($request, $response);
return true;
} | php | public static function rasterize($file, $dest, $columns, $rows) {
// check the input
if (!file_exists($file)) {
return false;
}
if (!file_exists($dest) || !is_dir($dest)) {
return false;
}
// figure out the output width and height
$svgTmp = new Respimg($file);
$width = (double) $svgTmp->getImageWidth();
$height = (double) $svgTmp->getImageHeight();
$new_width = $columns;
$new_height = $rows;
$x_factor = $columns / $width;
$y_factor = $rows / $height;
if ($rows < 1) {
$new_height = round($x_factor * $height);
} elseif ($columns < 1) {
$new_width = round($y_factor * $width);
}
// get the svg data
$svgdata = file_get_contents($file);
// figure out some path stuff
$dest = rtrim($dest, '/');
$filename = substr($file, strrpos($file, '/') + 1);
$filename_base = substr($filename, 0, strrpos($filename, '.'));
// setup the request
$client = Client::getInstance();
$serviceContainer = ServiceContainer::getInstance();
$procedureLoaderFactory = $serviceContainer->get('procedure_loader_factory');
$procedureLoader = $procedureLoaderFactory->createProcedureLoader(__DIR__);
$client->getProcedureLoader()->addLoader($procedureLoader);
$request = new RespimgCaptureRequest();
$request->setType('svg2png');
$request->setMethod('GET');
$request->setSVG(base64_encode($svgdata));
$request->setViewportSize($new_width, $new_height);
$request->setRasterFile($dest . '/' . $filename_base . '-w' . $new_width . '.png');
$request->setWidth($new_width);
$request->setHeight($new_height);
$response = $client->getMessageFactory()->createResponse();
// send + return
$client->send($request, $response);
return true;
} | [
"public",
"static",
"function",
"rasterize",
"(",
"$",
"file",
",",
"$",
"dest",
",",
"$",
"columns",
",",
"$",
"rows",
")",
"{",
"// check the input",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",... | Rasterizes an SVG image to a PNG.
Uses phantomjs to save the SVG as a PNG image at the specified size.
@access public
@param string $file The path to the file that should be rasterized.
@param string $dest The path to the directory where the output PNG should be saved.
@param integer $columns The number of columns in the output image. 0 = maintain aspect ratio based on $rows.
@param integer $rows The number of rows in the output image. 0 = maintain aspect ratio based on $columns. | [
"Rasterizes",
"an",
"SVG",
"image",
"to",
"a",
"PNG",
"."
] | 9bb067726b479ff362202529f4c98b53a53a04c1 | https://github.com/nwtn/php-respimg/blob/9bb067726b479ff362202529f4c98b53a53a04c1/src/Respimg.php#L159-L216 | train |
nwtn/php-respimg | src/Respimg.php | Respimg.smartResize | public function smartResize($columns, $rows, $optim = false) {
$this->setOption('filter:support', '2.0');
$this->thumbnailImage($columns, $rows, false, false, \Imagick::FILTER_TRIANGLE);
if ($optim) {
$this->unsharpMaskImage(0.25, 0.08, 8.3, 0.045);
} else {
$this->unsharpMaskImage(0.25, 0.25, 8, 0.065);
}
$this->posterizeImage(136, false);
$this->setImageCompressionQuality(82);
$this->setOption('jpeg:fancy-upsampling', 'off');
$this->setOption('png:compression-filter', '5');
$this->setOption('png:compression-level', '9');
$this->setOption('png:compression-strategy', '1');
$this->setOption('png:exclude-chunk', 'all');
$this->setInterlaceScheme(\Imagick::INTERLACE_NO);
$this->setColorspace(\Imagick::COLORSPACE_SRGB);
if (!$optim) {
$this->stripImage();
}
} | php | public function smartResize($columns, $rows, $optim = false) {
$this->setOption('filter:support', '2.0');
$this->thumbnailImage($columns, $rows, false, false, \Imagick::FILTER_TRIANGLE);
if ($optim) {
$this->unsharpMaskImage(0.25, 0.08, 8.3, 0.045);
} else {
$this->unsharpMaskImage(0.25, 0.25, 8, 0.065);
}
$this->posterizeImage(136, false);
$this->setImageCompressionQuality(82);
$this->setOption('jpeg:fancy-upsampling', 'off');
$this->setOption('png:compression-filter', '5');
$this->setOption('png:compression-level', '9');
$this->setOption('png:compression-strategy', '1');
$this->setOption('png:exclude-chunk', 'all');
$this->setInterlaceScheme(\Imagick::INTERLACE_NO);
$this->setColorspace(\Imagick::COLORSPACE_SRGB);
if (!$optim) {
$this->stripImage();
}
} | [
"public",
"function",
"smartResize",
"(",
"$",
"columns",
",",
"$",
"rows",
",",
"$",
"optim",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"setOption",
"(",
"'filter:support'",
",",
"'2.0'",
")",
";",
"$",
"this",
"->",
"thumbnailImage",
"(",
"$",
"colu... | Resizes the image using smart defaults for high quality and low file size.
This function is basically equivalent to:
$optim == true: `mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2.0 -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB INPUT_PATH`
$optim == false: `mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2.0 -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.25+8+0.065 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB -strip INPUT_PATH`
@access public
@param integer $columns The number of columns in the output image. 0 = maintain aspect ratio based on $rows.
@param integer $rows The number of rows in the output image. 0 = maintain aspect ratio based on $columns.
@param bool $optim Whether you intend to perform optimization on the resulting image. Note that setting this to `true` doesn’t actually perform any optimization. | [
"Resizes",
"the",
"image",
"using",
"smart",
"defaults",
"for",
"high",
"quality",
"and",
"low",
"file",
"size",
"."
] | 9bb067726b479ff362202529f4c98b53a53a04c1 | https://github.com/nwtn/php-respimg/blob/9bb067726b479ff362202529f4c98b53a53a04c1/src/Respimg.php#L235-L257 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Permission/Repo/PermissionRepository.php | PermissionRepository.create | public function create(array $data)
{
$perm = $this->model->create(array(
'name' => $data['name'],
'permissions' => $data['permissions']
));
if ( ! $perm )
{
return false;
}
else
{
$this->event->fire('permissions.create', array($perm));
return $perm;
}
} | php | public function create(array $data)
{
$perm = $this->model->create(array(
'name' => $data['name'],
'permissions' => $data['permissions']
));
if ( ! $perm )
{
return false;
}
else
{
$this->event->fire('permissions.create', array($perm));
return $perm;
}
} | [
"public",
"function",
"create",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"perm",
"=",
"$",
"this",
"->",
"model",
"->",
"create",
"(",
"array",
"(",
"'name'",
"=>",
"$",
"data",
"[",
"'name'",
"]",
",",
"'permissions'",
"=>",
"$",
"data",
"[",
"'p... | Put into storage a new permission
@author Steve Montambeault
@link http://stevemo.ca
@param array $data
@return bool|\Illuminate\Database\Eloquent\Model|\StdClass|static | [
"Put",
"into",
"storage",
"a",
"new",
"permission"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Permission/Repo/PermissionRepository.php#L61-L77 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Permission/Repo/PermissionRepository.php | PermissionRepository.delete | public function delete($id)
{
try
{
$perm = $this->model->findOrFail($id);
$oldData = $perm;
$perm->delete();
$this->event->fire('permissions.delete', array($oldData));
return true;
}
catch ( ModelNotFoundException $e)
{
return false;
}
} | php | public function delete($id)
{
try
{
$perm = $this->model->findOrFail($id);
$oldData = $perm;
$perm->delete();
$this->event->fire('permissions.delete', array($oldData));
return true;
}
catch ( ModelNotFoundException $e)
{
return false;
}
} | [
"public",
"function",
"delete",
"(",
"$",
"id",
")",
"{",
"try",
"{",
"$",
"perm",
"=",
"$",
"this",
"->",
"model",
"->",
"findOrFail",
"(",
"$",
"id",
")",
";",
"$",
"oldData",
"=",
"$",
"perm",
";",
"$",
"perm",
"->",
"delete",
"(",
")",
";",... | Delete a permission from storage
@author Steve Montambeault
@link http://stevemo.ca
@param $id
@return bool | [
"Delete",
"a",
"permission",
"from",
"storage"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Permission/Repo/PermissionRepository.php#L89-L104 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Permission/Repo/PermissionRepository.php | PermissionRepository.update | public function update(array $data)
{
$perm = $this->findOrFail($data['id']);
$perm->name = $data['name'];
$perm->permissions = $data['permissions'];
$perm->save();
$this->event->fire('permissions.update',array($perm));
return true;
} | php | public function update(array $data)
{
$perm = $this->findOrFail($data['id']);
$perm->name = $data['name'];
$perm->permissions = $data['permissions'];
$perm->save();
$this->event->fire('permissions.update',array($perm));
return true;
} | [
"public",
"function",
"update",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"perm",
"=",
"$",
"this",
"->",
"findOrFail",
"(",
"$",
"data",
"[",
"'id'",
"]",
")",
";",
"$",
"perm",
"->",
"name",
"=",
"$",
"data",
"[",
"'name'",
"]",
";",
"$",
"pe... | Update a permission into storage
@author Steve Montambeault
@link http://stevemo.ca
@param array $data
@return bool | [
"Update",
"a",
"permission",
"into",
"storage"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Permission/Repo/PermissionRepository.php#L184-L195 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/UsersPermissionsController.php | UsersPermissionsController.index | public function index($userId)
{
try
{
$user = $this->users->findById($userId);
$userPermissions = $user->getPermissions();
$genericPermissions = $this->permissions->generic();
$modulePermissions = $this->permissions->module();
return View::make(Config::get('cpanel::views.users_permission'))
->with('user',$user)
->with('userPermissions',$userPermissions)
->with('genericPermissions',$genericPermissions)
->with('modulePermissions',$modulePermissions);
}
catch ( UserNotFoundException $e)
{
return Redirect::route('cpanel.users.index')
->with('error', $e->getMessage());
}
} | php | public function index($userId)
{
try
{
$user = $this->users->findById($userId);
$userPermissions = $user->getPermissions();
$genericPermissions = $this->permissions->generic();
$modulePermissions = $this->permissions->module();
return View::make(Config::get('cpanel::views.users_permission'))
->with('user',$user)
->with('userPermissions',$userPermissions)
->with('genericPermissions',$genericPermissions)
->with('modulePermissions',$modulePermissions);
}
catch ( UserNotFoundException $e)
{
return Redirect::route('cpanel.users.index')
->with('error', $e->getMessage());
}
} | [
"public",
"function",
"index",
"(",
"$",
"userId",
")",
"{",
"try",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"users",
"->",
"findById",
"(",
"$",
"userId",
")",
";",
"$",
"userPermissions",
"=",
"$",
"user",
"->",
"getPermissions",
"(",
")",
";",
... | Display the user permissins
@author Steve Montambeault
@link http://stevemo.ca
@param int $userId
@return Response | [
"Display",
"the",
"user",
"permissins"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersPermissionsController.php#L40-L60 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/UsersPermissionsController.php | UsersPermissionsController.update | public function update($userId)
{
try
{
$permissions = Input::get('permissions', array());
$this->users->updatePermissions($userId,$permissions);
return Redirect::route('cpanel.users.index')
->with('success', Lang::get('cpanel::users.permissions_update_success'));
}
catch ( UserNotFoundException $e)
{
return Redirect::route('cpanel.users.permissions')
->with('error', $e->getMessage());
}
} | php | public function update($userId)
{
try
{
$permissions = Input::get('permissions', array());
$this->users->updatePermissions($userId,$permissions);
return Redirect::route('cpanel.users.index')
->with('success', Lang::get('cpanel::users.permissions_update_success'));
}
catch ( UserNotFoundException $e)
{
return Redirect::route('cpanel.users.permissions')
->with('error', $e->getMessage());
}
} | [
"public",
"function",
"update",
"(",
"$",
"userId",
")",
"{",
"try",
"{",
"$",
"permissions",
"=",
"Input",
"::",
"get",
"(",
"'permissions'",
",",
"array",
"(",
")",
")",
";",
"$",
"this",
"->",
"users",
"->",
"updatePermissions",
"(",
"$",
"userId",
... | Update user permissions
@author Steve Montambeault
@link http://stevemo.ca
@param int $userId
@return Response | [
"Update",
"user",
"permissions"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersPermissionsController.php#L71-L87 | train |
jkoudys/immutable.php | src/Iterator/ConcatIterator.php | ConcatIterator.getIteratorByIndex | protected function getIteratorByIndex($index = 0)
{
$runningCount = 0;
foreach ($this->getArrayIterator() as $innerIt) {
$count = count($innerIt);
if ($index < $runningCount + $count) {
return [$innerIt, $index - $runningCount];
}
$runningCount += $count;
}
return null;
} | php | protected function getIteratorByIndex($index = 0)
{
$runningCount = 0;
foreach ($this->getArrayIterator() as $innerIt) {
$count = count($innerIt);
if ($index < $runningCount + $count) {
return [$innerIt, $index - $runningCount];
}
$runningCount += $count;
}
return null;
} | [
"protected",
"function",
"getIteratorByIndex",
"(",
"$",
"index",
"=",
"0",
")",
"{",
"$",
"runningCount",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"getArrayIterator",
"(",
")",
"as",
"$",
"innerIt",
")",
"{",
"$",
"count",
"=",
"count",
"(",
... | Find which of the inner iterators an index corresponds to
@param int $index
@return [ArrayAccess, int] The iterator and interior index | [
"Find",
"which",
"of",
"the",
"inner",
"iterators",
"an",
"index",
"corresponds",
"to"
] | 5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e | https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Iterator/ConcatIterator.php#L114-L126 | train |
stevemo/cpanel | src/Stevemo/Cpanel/Controllers/PasswordController.php | PasswordController.postForgot | public function postForgot()
{
try
{
$email = Input::get('email');
$this->passForm->forgot($email);
return View::make(Config::get('cpanel::views.password_send'))
->with('email', $email);
}
catch (UserNotFoundException $e)
{
return Redirect::back()
->with('password_error', $e->getMessage());
}
} | php | public function postForgot()
{
try
{
$email = Input::get('email');
$this->passForm->forgot($email);
return View::make(Config::get('cpanel::views.password_send'))
->with('email', $email);
}
catch (UserNotFoundException $e)
{
return Redirect::back()
->with('password_error', $e->getMessage());
}
} | [
"public",
"function",
"postForgot",
"(",
")",
"{",
"try",
"{",
"$",
"email",
"=",
"Input",
"::",
"get",
"(",
"'email'",
")",
";",
"$",
"this",
"->",
"passForm",
"->",
"forgot",
"(",
"$",
"email",
")",
";",
"return",
"View",
"::",
"make",
"(",
"Conf... | Find the user and send a email with the reset code
@author Steve Montambeault
@link http://stevemo.ca
@return \Illuminate\Http\RedirectResponse|\Illuminate\View\View | [
"Find",
"the",
"user",
"and",
"send",
"a",
"email",
"with",
"the",
"reset",
"code"
] | f6435f64af5a3aa3d74c5d14f8d7e765303acb8b | https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/PasswordController.php#L51-L65 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.