repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
CharlotteDunois/Yasmin | src/HTTP/APIRequest.php | APIRequest.handleAPIError | protected function handleAPIError(\Psr\Http\Message\ResponseInterface $response, $body, ?\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $ratelimit = null) {
$status = $response->getStatusCode();
if($status >= 500) {
$this->retries++;
$maxRetries = (int) $this->api->client->getOption('http.requestMaxRetries', 0);
if($maxRetries > 0 && $this->retries > $maxRetries) {
$this->api->client->emit('debug', 'Giving up on item "'.$this->endpoint.'" after '.$maxRetries.' retries due to HTTP '.$status);
return (new \RuntimeException('Maximum retry of '.$maxRetries.' reached - giving up'));
}
$this->api->client->emit('debug', 'Delaying unshifting item "'.$this->endpoint.'" due to HTTP '.$status);
$delay = (int) $this->api->client->getOption('http.requestErrorDelay', 30);
if($this->retries > 2) {
$delay *= 2;
}
$this->api->client->addTimer($delay, function () use (&$ratelimit) {
if($ratelimit !== null) {
$this->api->unshiftQueue($ratelimit->unshift($this));
} else {
$this->api->unshiftQueue($this);
}
});
return null;
} elseif($status === 429) {
$this->api->client->emit('debug', 'Unshifting item "'.$this->endpoint.'" due to HTTP 429');
if($ratelimit !== null) {
$this->api->unshiftQueue($ratelimit->unshift($this));
} else {
$this->api->unshiftQueue($this);
}
return null;
}
if($status >= 400 && $status < 500) {
$error = new \CharlotteDunois\Yasmin\HTTP\DiscordAPIException($this->endpoint, $body);
} else {
$error = new \RuntimeException($response->getReasonPhrase());
}
return $error;
} | php | protected function handleAPIError(\Psr\Http\Message\ResponseInterface $response, $body, ?\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $ratelimit = null) {
$status = $response->getStatusCode();
if($status >= 500) {
$this->retries++;
$maxRetries = (int) $this->api->client->getOption('http.requestMaxRetries', 0);
if($maxRetries > 0 && $this->retries > $maxRetries) {
$this->api->client->emit('debug', 'Giving up on item "'.$this->endpoint.'" after '.$maxRetries.' retries due to HTTP '.$status);
return (new \RuntimeException('Maximum retry of '.$maxRetries.' reached - giving up'));
}
$this->api->client->emit('debug', 'Delaying unshifting item "'.$this->endpoint.'" due to HTTP '.$status);
$delay = (int) $this->api->client->getOption('http.requestErrorDelay', 30);
if($this->retries > 2) {
$delay *= 2;
}
$this->api->client->addTimer($delay, function () use (&$ratelimit) {
if($ratelimit !== null) {
$this->api->unshiftQueue($ratelimit->unshift($this));
} else {
$this->api->unshiftQueue($this);
}
});
return null;
} elseif($status === 429) {
$this->api->client->emit('debug', 'Unshifting item "'.$this->endpoint.'" due to HTTP 429');
if($ratelimit !== null) {
$this->api->unshiftQueue($ratelimit->unshift($this));
} else {
$this->api->unshiftQueue($this);
}
return null;
}
if($status >= 400 && $status < 500) {
$error = new \CharlotteDunois\Yasmin\HTTP\DiscordAPIException($this->endpoint, $body);
} else {
$error = new \RuntimeException($response->getReasonPhrase());
}
return $error;
} | [
"protected",
"function",
"handleAPIError",
"(",
"\\",
"Psr",
"\\",
"Http",
"\\",
"Message",
"\\",
"ResponseInterface",
"$",
"response",
",",
"$",
"body",
",",
"?",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Interfaces",
"\\",
"RatelimitBucketInterface",
"$"... | Handles an API error.
@param \Psr\Http\Message\ResponseInterface $response
@param mixed $body
@param \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface|null $ratelimit
@return \CharlotteDunois\Yasmin\HTTP\DiscordAPIException|\RuntimeException|null | [
"Handles",
"an",
"API",
"error",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIRequest.php#L238-L286 |
CharlotteDunois/Yasmin | src/Utils/URLHelpers.php | URLHelpers.setLoop | static function setLoop(\React\EventLoop\LoopInterface $loop) {
static::$loop = $loop;
if(static::$http === null) {
static::internalSetClient();
}
} | php | static function setLoop(\React\EventLoop\LoopInterface $loop) {
static::$loop = $loop;
if(static::$http === null) {
static::internalSetClient();
}
} | [
"static",
"function",
"setLoop",
"(",
"\\",
"React",
"\\",
"EventLoop",
"\\",
"LoopInterface",
"$",
"loop",
")",
"{",
"static",
"::",
"$",
"loop",
"=",
"$",
"loop",
";",
"if",
"(",
"static",
"::",
"$",
"http",
"===",
"null",
")",
"{",
"static",
"::",... | Sets the Event Loop.
@param \React\EventLoop\LoopInterface $loop
@return void
@internal | [
"Sets",
"the",
"Event",
"Loop",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/URLHelpers.php#L39-L45 |
CharlotteDunois/Yasmin | src/Utils/URLHelpers.php | URLHelpers.setHTTPClient | static function setHTTPClient(\Clue\React\Buzz\Browser $client) {
if(static::$http !== null) {
throw new \LogicException('Client has already been set');
}
static::$http = $client;
} | php | static function setHTTPClient(\Clue\React\Buzz\Browser $client) {
if(static::$http !== null) {
throw new \LogicException('Client has already been set');
}
static::$http = $client;
} | [
"static",
"function",
"setHTTPClient",
"(",
"\\",
"Clue",
"\\",
"React",
"\\",
"Buzz",
"\\",
"Browser",
"$",
"client",
")",
"{",
"if",
"(",
"static",
"::",
"$",
"http",
"!==",
"null",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Client has al... | Set the HTTP client used in Yasmin (and in this utility).
Be aware that this method can be changed at any time.
If you want to set the HTTP client, then you need to set it
before the utilities get initialized by the Client!
The HTTP client is after setting **immutable**.
@return void
@throws \LogicException | [
"Set",
"the",
"HTTP",
"client",
"used",
"in",
"Yasmin",
"(",
"and",
"in",
"this",
"utility",
")",
".",
"Be",
"aware",
"that",
"this",
"method",
"can",
"be",
"changed",
"at",
"any",
"time",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/URLHelpers.php#L58-L64 |
CharlotteDunois/Yasmin | src/Utils/URLHelpers.php | URLHelpers.makeRequest | static function makeRequest(\Psr\Http\Message\RequestInterface $request, ?array $requestOptions = null) {
$client = static::getHTTPClient();
if(!empty($requestOptions)) {
if(isset($requestOptions['http_errors'])) {
$client = $client->withOptions(array(
'obeySuccessCode' => !empty($requestOptions['http_errors'])
));
}
if(isset($requestOptions['timeout'])) {
$client = $client->withOptions(array(
'timeout' => ((float) $requestOptions['timeout'])
));
}
try {
$request = static::applyRequestOptions($request, $requestOptions);
} catch (\RuntimeException $e) {
return \React\Promise\reject($e);
}
}
return $client->send($request);
} | php | static function makeRequest(\Psr\Http\Message\RequestInterface $request, ?array $requestOptions = null) {
$client = static::getHTTPClient();
if(!empty($requestOptions)) {
if(isset($requestOptions['http_errors'])) {
$client = $client->withOptions(array(
'obeySuccessCode' => !empty($requestOptions['http_errors'])
));
}
if(isset($requestOptions['timeout'])) {
$client = $client->withOptions(array(
'timeout' => ((float) $requestOptions['timeout'])
));
}
try {
$request = static::applyRequestOptions($request, $requestOptions);
} catch (\RuntimeException $e) {
return \React\Promise\reject($e);
}
}
return $client->send($request);
} | [
"static",
"function",
"makeRequest",
"(",
"\\",
"Psr",
"\\",
"Http",
"\\",
"Message",
"\\",
"RequestInterface",
"$",
"request",
",",
"?",
"array",
"$",
"requestOptions",
"=",
"null",
")",
"{",
"$",
"client",
"=",
"static",
"::",
"getHTTPClient",
"(",
")",
... | Makes an asynchronous request. Resolves with an instance of ResponseInterface.
The following request options are supported:
```
array(
'http_errors' => bool, (whether the HTTP client should obey the HTTP success code)
'multipart' => array, (multipart form data, an array of `[ 'name' => string, 'contents' => string|resource, 'filename' => string ]`)
'json' => mixed, (any JSON serializable type to send with the request as body payload)
'query' => string, (the URL query string to set to)
'headers' => string[], (HTTP headers to set)
'timeout' => float, (after how many seconds the request times out)
)
```
@param \Psr\Http\Message\RequestInterface $request
@param array|null $requestOptions
@return \React\Promise\ExtendedPromiseInterface
@see \Psr\Http\Message\ResponseInterface | [
"Makes",
"an",
"asynchronous",
"request",
".",
"Resolves",
"with",
"an",
"instance",
"of",
"ResponseInterface",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/URLHelpers.php#L106-L130 |
CharlotteDunois/Yasmin | src/Utils/URLHelpers.php | URLHelpers.resolveURLToData | static function resolveURLToData(string $url, ?array $requestHeaders = null) {
if($requestHeaders === null) {
$requestHeaders = array();
}
foreach($requestHeaders as $key => $val) {
unset($requestHeaders[$key]);
$nkey = \ucwords($key, '-');
$requestHeaders[$nkey] = $val;
}
if(empty($requestHeaders['User-Agent'])) {
$requestHeaders['User-Agent'] = static::DEFAULT_USER_AGENT;
}
$request = new \RingCentral\Psr7\Request('GET', $url, $requestHeaders);
return static::makeRequest($request)->then(function ($response) {
$body = (string) $response->getBody();
return $body;
});
} | php | static function resolveURLToData(string $url, ?array $requestHeaders = null) {
if($requestHeaders === null) {
$requestHeaders = array();
}
foreach($requestHeaders as $key => $val) {
unset($requestHeaders[$key]);
$nkey = \ucwords($key, '-');
$requestHeaders[$nkey] = $val;
}
if(empty($requestHeaders['User-Agent'])) {
$requestHeaders['User-Agent'] = static::DEFAULT_USER_AGENT;
}
$request = new \RingCentral\Psr7\Request('GET', $url, $requestHeaders);
return static::makeRequest($request)->then(function ($response) {
$body = (string) $response->getBody();
return $body;
});
} | [
"static",
"function",
"resolveURLToData",
"(",
"string",
"$",
"url",
",",
"?",
"array",
"$",
"requestHeaders",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"requestHeaders",
"===",
"null",
")",
"{",
"$",
"requestHeaders",
"=",
"array",
"(",
")",
";",
"}",
"f... | Asynchronously resolves a given URL to the response body. Resolves with a string.
@param string $url
@param array|null $requestHeaders
@return \React\Promise\ExtendedPromiseInterface | [
"Asynchronously",
"resolves",
"a",
"given",
"URL",
"to",
"the",
"response",
"body",
".",
"Resolves",
"with",
"a",
"string",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/URLHelpers.php#L138-L159 |
CharlotteDunois/Yasmin | src/Utils/URLHelpers.php | URLHelpers.applyRequestOptions | static function applyRequestOptions(\Psr\Http\Message\RequestInterface $request, array $requestOptions) {
if(isset($requestOptions['multipart'])) {
$multipart = new \RingCentral\Psr7\MultipartStream($requestOptions['multipart']);
$request = $request->withBody($multipart)
->withHeader('Content-Type', 'multipart/form-data; boundary="'.$multipart->getBoundary().'"');
}
if(isset($requestOptions['json'])) {
$resource = \fopen('php://temp', 'r+');
if($resource === false) {
throw new \RuntimeException('Unable to create stream for JSON data');
}
$json = \json_encode($requestOptions['json']);
if($json === false) {
throw new \RuntimeException('Unable to encode json. Error: '.\json_last_error_msg());
}
\fwrite($resource, $json);
\fseek($resource, 0);
$stream = new \RingCentral\Psr7\Stream($resource, array('size' => \strlen($json)));
$request = $request->withBody($stream);
$request = $request->withHeader('Content-Type', 'application/json')
->withHeader('Content-Length', \strlen($json));
}
if(isset($requestOptions['query'])) {
$uri = $request->getUri()->withQuery($requestOptions['query']);
$request = $request->withUri($uri);
}
if(isset($requestOptions['headers'])) {
foreach($requestOptions['headers'] as $key => $val) {
$request = $request->withHeader($key, $val);
}
}
return $request;
} | php | static function applyRequestOptions(\Psr\Http\Message\RequestInterface $request, array $requestOptions) {
if(isset($requestOptions['multipart'])) {
$multipart = new \RingCentral\Psr7\MultipartStream($requestOptions['multipart']);
$request = $request->withBody($multipart)
->withHeader('Content-Type', 'multipart/form-data; boundary="'.$multipart->getBoundary().'"');
}
if(isset($requestOptions['json'])) {
$resource = \fopen('php://temp', 'r+');
if($resource === false) {
throw new \RuntimeException('Unable to create stream for JSON data');
}
$json = \json_encode($requestOptions['json']);
if($json === false) {
throw new \RuntimeException('Unable to encode json. Error: '.\json_last_error_msg());
}
\fwrite($resource, $json);
\fseek($resource, 0);
$stream = new \RingCentral\Psr7\Stream($resource, array('size' => \strlen($json)));
$request = $request->withBody($stream);
$request = $request->withHeader('Content-Type', 'application/json')
->withHeader('Content-Length', \strlen($json));
}
if(isset($requestOptions['query'])) {
$uri = $request->getUri()->withQuery($requestOptions['query']);
$request = $request->withUri($uri);
}
if(isset($requestOptions['headers'])) {
foreach($requestOptions['headers'] as $key => $val) {
$request = $request->withHeader($key, $val);
}
}
return $request;
} | [
"static",
"function",
"applyRequestOptions",
"(",
"\\",
"Psr",
"\\",
"Http",
"\\",
"Message",
"\\",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"requestOptions",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"requestOptions",
"[",
"'multipart'",
"]",
")... | Applies request options to the request.
The following request options are supported:
```
array(
'multipart' => array, (multipart form data, an array of `[ 'name' => string, 'contents' => string|resource, 'filename' => string ]`)
'json' => mixed, (any JSON serializable type to send with the request as body payload)
'query' => string, (the URL query string to set to)
'headers' => string[], (HTTP headers to set)
)
```
@param \Psr\Http\Message\RequestInterface $request
@param array $requestOptions
@return \Psr\Http\Message\RequestInterface
@throws \RuntimeException | [
"Applies",
"request",
"options",
"to",
"the",
"request",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/URLHelpers.php#L179-L220 |
CharlotteDunois/Yasmin | src/HTTP/DiscordAPIException.php | DiscordAPIException.flattenErrors | static function flattenErrors($obj, $key = '') {
$messages = array();
foreach($obj as $k => $val) {
if($k === 'message') {
continue;
}
$newKey = $k;
if($key) {
if(\is_numeric($k)) {
$newKey = $key.'.'.$k;
} else {
$newKey = $key.'['.$k.']';
}
}
if(isset($val['_errors'])) {
$messages[] = $newKey.': '.\implode(' ', \array_map(function ($element) {
return $element['message'];
}, $val['_errors']));
} else if(isset($val['code']) || isset($val['message'])) {
$messages[] = \trim(($val['code'] ?? '').': '.($val['message'] ?? ''));
} else if(\is_array($val)) {
$messages = \array_merge($messages, self::flattenErrors($val, $newKey));
} else {
$messages[] = $val;
}
}
return $messages;
} | php | static function flattenErrors($obj, $key = '') {
$messages = array();
foreach($obj as $k => $val) {
if($k === 'message') {
continue;
}
$newKey = $k;
if($key) {
if(\is_numeric($k)) {
$newKey = $key.'.'.$k;
} else {
$newKey = $key.'['.$k.']';
}
}
if(isset($val['_errors'])) {
$messages[] = $newKey.': '.\implode(' ', \array_map(function ($element) {
return $element['message'];
}, $val['_errors']));
} else if(isset($val['code']) || isset($val['message'])) {
$messages[] = \trim(($val['code'] ?? '').': '.($val['message'] ?? ''));
} else if(\is_array($val)) {
$messages = \array_merge($messages, self::flattenErrors($val, $newKey));
} else {
$messages[] = $val;
}
}
return $messages;
} | [
"static",
"function",
"flattenErrors",
"(",
"$",
"obj",
",",
"$",
"key",
"=",
"''",
")",
"{",
"$",
"messages",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"obj",
"as",
"$",
"k",
"=>",
"$",
"val",
")",
"{",
"if",
"(",
"$",
"k",
"===",
"'... | Flattens an errors object returned from the API into an array.
@param array $obj Discord error object
@param string $key Used internally to determine key names of nested fields
@return string[]
@internal | [
"Flattens",
"an",
"errors",
"object",
"returned",
"from",
"the",
"API",
"into",
"an",
"array",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/DiscordAPIException.php#L41-L72 |
CharlotteDunois/Yasmin | src/Utils/MessageHelpers.php | MessageHelpers.cleanContent | static function cleanContent(\CharlotteDunois\Yasmin\Models\Message $message, string $text) {
/** @var \CharlotteDunois\Yasmin\Interfaces\ChannelInterface $channel */
foreach($message->mentions->channels as $channel) {
$text = \str_replace('<#'.$channel->getId().'>', '#'.$channel->name, $text);
}
/** @var \CharlotteDunois\Yasmin\Models\Role $role */
foreach($message->mentions->roles as $role) {
$text = \str_replace($role->__toString(), $role->name, $text);
}
/** @var \CharlotteDunois\Yasmin\Models\User $user */
foreach($message->mentions->users as $user) {
$guildCheck = ($message->channel instanceof \CharlotteDunois\Yasmin\Interfaces\GuildChannelInterface && $message->channel->getGuild()->members->has($user->id));
$text = \preg_replace('/<@!?'.$user->id.'>/', ($guildCheck ? $message->channel->getGuild()->members->get($user->id)->displayName : $user->username), $text);
}
return $text;
} | php | static function cleanContent(\CharlotteDunois\Yasmin\Models\Message $message, string $text) {
/** @var \CharlotteDunois\Yasmin\Interfaces\ChannelInterface $channel */
foreach($message->mentions->channels as $channel) {
$text = \str_replace('<#'.$channel->getId().'>', '#'.$channel->name, $text);
}
/** @var \CharlotteDunois\Yasmin\Models\Role $role */
foreach($message->mentions->roles as $role) {
$text = \str_replace($role->__toString(), $role->name, $text);
}
/** @var \CharlotteDunois\Yasmin\Models\User $user */
foreach($message->mentions->users as $user) {
$guildCheck = ($message->channel instanceof \CharlotteDunois\Yasmin\Interfaces\GuildChannelInterface && $message->channel->getGuild()->members->has($user->id));
$text = \preg_replace('/<@!?'.$user->id.'>/', ($guildCheck ? $message->channel->getGuild()->members->get($user->id)->displayName : $user->username), $text);
}
return $text;
} | [
"static",
"function",
"cleanContent",
"(",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"Message",
"$",
"message",
",",
"string",
"$",
"text",
")",
"{",
"/** @var \\CharlotteDunois\\Yasmin\\Interfaces\\ChannelInterface $channel */",
"foreach",
"(",
"$... | Cleans the text from mentions, by providing a context message.
@param \CharlotteDunois\Yasmin\Models\Message $message
@param string $text
@return string | [
"Cleans",
"the",
"text",
"from",
"mentions",
"by",
"providing",
"a",
"context",
"message",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/MessageHelpers.php#L22-L40 |
CharlotteDunois/Yasmin | src/Utils/MessageHelpers.php | MessageHelpers.escapeMarkdown | static function escapeMarkdown(string $text, bool $onlyCodeBlock = false, bool $onlyInlineCode = false) {
if($onlyCodeBlock) {
return \preg_replace('/(```)/miu', "\\`\\`\\`", $text);
}
if($onlyInlineCode) {
return \preg_replace('/(`)/miu', '\\\\$1', $text);
}
return \preg_replace('/(\\*|_|`|~)/miu', '\\\\$1', $text);
} | php | static function escapeMarkdown(string $text, bool $onlyCodeBlock = false, bool $onlyInlineCode = false) {
if($onlyCodeBlock) {
return \preg_replace('/(```)/miu', "\\`\\`\\`", $text);
}
if($onlyInlineCode) {
return \preg_replace('/(`)/miu', '\\\\$1', $text);
}
return \preg_replace('/(\\*|_|`|~)/miu', '\\\\$1', $text);
} | [
"static",
"function",
"escapeMarkdown",
"(",
"string",
"$",
"text",
",",
"bool",
"$",
"onlyCodeBlock",
"=",
"false",
",",
"bool",
"$",
"onlyInlineCode",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"onlyCodeBlock",
")",
"{",
"return",
"\\",
"preg_replace",
"(",... | Escapes any Discord-flavour markdown in a string.
@param string $text Content to escape.
@param bool $onlyCodeBlock Whether to only escape codeblocks (takes priority).
@param bool $onlyInlineCode Whether to only escape inline code.
@return string | [
"Escapes",
"any",
"Discord",
"-",
"flavour",
"markdown",
"in",
"a",
"string",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/MessageHelpers.php#L49-L59 |
CharlotteDunois/Yasmin | src/Utils/MessageHelpers.php | MessageHelpers.parseMentions | static function parseMentions(?\CharlotteDunois\Yasmin\Client $client, string $content) {
return (new \React\Promise\Promise(function (callable $resolve) use ($client, $content) {
$bucket = array();
$promises = array();
\preg_match_all('/(?:<(@&|@!?|#|a?:.+?:)(\d+)>)|@everyone|@here/su', $content, $matches);
foreach($matches[0] as $key => $val) {
if($val === '@everyone') {
$bucket[$key] = array('type' => 'everyone', 'ref' => $val);
} elseif($val === '@here') {
$bucket[$key] = array('type' => 'here', 'ref' => $val);
} elseif($matches[1][$key] === '@&') {
$type = 'role';
if($client) {
$role = $val;
foreach($client->guilds as $guild) {
if($guild->roles->has($matches[2][$key])) {
$role = $guild->roles->get($matches[2][$key]);
break 1;
}
}
$bucket[$key] = array('type' => $type, 'ref' => $role);
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
} elseif($matches[1][$key] === '#') {
$type = 'channel';
if($client) {
if($client->channels->has($matches[2][$key])) {
$channel = $client->channels->get($matches[2][$key]);
} else {
$channel = $val;
}
$bucket[$key] = array('type' => $type, 'ref' => $channel);
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
} elseif(\substr_count($matches[1][$key], ':') === 2) {
$type = 'emoji';
if($client) {
$emoji = $val;
foreach($client->guilds as $guild) {
if($guild->emojis->has($matches[2][$key])) {
$emoji = $guild->emojis->get($matches[2][$key]);
break 1;
}
}
$bucket[$key] = array('type' => $type, 'ref' => $emoji);
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
} else {
$type = 'user';
if($client) {
$promises[] = $client->fetchUser($matches[2][$key])->then(function (\CharlotteDunois\Yasmin\Models\User $user) use (&$bucket, $key, $type) {
$bucket[$key] = array('type' => $type, 'ref' => $user);
}, function () use (&$bucket, $key, $val, $type) {
$bucket[$key] = array('type' => $type, 'ref' => $val);
});
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
}
}
\React\Promise\all($promises)->done(function () use (&$bucket, $resolve) {
$resolve($bucket);
});
}));
} | php | static function parseMentions(?\CharlotteDunois\Yasmin\Client $client, string $content) {
return (new \React\Promise\Promise(function (callable $resolve) use ($client, $content) {
$bucket = array();
$promises = array();
\preg_match_all('/(?:<(@&|@!?|#|a?:.+?:)(\d+)>)|@everyone|@here/su', $content, $matches);
foreach($matches[0] as $key => $val) {
if($val === '@everyone') {
$bucket[$key] = array('type' => 'everyone', 'ref' => $val);
} elseif($val === '@here') {
$bucket[$key] = array('type' => 'here', 'ref' => $val);
} elseif($matches[1][$key] === '@&') {
$type = 'role';
if($client) {
$role = $val;
foreach($client->guilds as $guild) {
if($guild->roles->has($matches[2][$key])) {
$role = $guild->roles->get($matches[2][$key]);
break 1;
}
}
$bucket[$key] = array('type' => $type, 'ref' => $role);
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
} elseif($matches[1][$key] === '#') {
$type = 'channel';
if($client) {
if($client->channels->has($matches[2][$key])) {
$channel = $client->channels->get($matches[2][$key]);
} else {
$channel = $val;
}
$bucket[$key] = array('type' => $type, 'ref' => $channel);
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
} elseif(\substr_count($matches[1][$key], ':') === 2) {
$type = 'emoji';
if($client) {
$emoji = $val;
foreach($client->guilds as $guild) {
if($guild->emojis->has($matches[2][$key])) {
$emoji = $guild->emojis->get($matches[2][$key]);
break 1;
}
}
$bucket[$key] = array('type' => $type, 'ref' => $emoji);
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
} else {
$type = 'user';
if($client) {
$promises[] = $client->fetchUser($matches[2][$key])->then(function (\CharlotteDunois\Yasmin\Models\User $user) use (&$bucket, $key, $type) {
$bucket[$key] = array('type' => $type, 'ref' => $user);
}, function () use (&$bucket, $key, $val, $type) {
$bucket[$key] = array('type' => $type, 'ref' => $val);
});
} else {
$bucket[$key] = array('type' => $type, 'ref' => $val);
}
}
}
\React\Promise\all($promises)->done(function () use (&$bucket, $resolve) {
$resolve($bucket);
});
}));
} | [
"static",
"function",
"parseMentions",
"(",
"?",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Client",
"$",
"client",
",",
"string",
"$",
"content",
")",
"{",
"return",
"(",
"new",
"\\",
"React",
"\\",
"Promise",
"\\",
"Promise",
"(",
"function",
"(",
... | Parses mentions in a text. Resolves with an array of `[ 'type' => string, 'ref' => Models ]` arrays, in the order they were parsed.
For mentions not available to this method or the client (e.g. mentioning a channel with no access to), `ref` will be the parsed mention (string).
Includes everyone and here mentions.
@param \CharlotteDunois\Yasmin\Client|null $client
@param string $content
@return \React\Promise\ExtendedPromiseInterface | [
"Parses",
"mentions",
"in",
"a",
"text",
".",
"Resolves",
"with",
"an",
"array",
"of",
"[",
"type",
"=",
">",
"string",
"ref",
"=",
">",
"Models",
"]",
"arrays",
"in",
"the",
"order",
"they",
"were",
"parsed",
".",
"For",
"mentions",
"not",
"available"... | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/MessageHelpers.php#L70-L148 |
CharlotteDunois/Yasmin | src/Utils/MessageHelpers.php | MessageHelpers.resolveMessageOptionsFiles | static function resolveMessageOptionsFiles(array $options) {
if(empty($options['files'])) {
return \React\Promise\resolve(array());
}
$promises = array();
foreach($options['files'] as $file) {
if($file instanceof \CharlotteDunois\Yasmin\Models\MessageAttachment) {
$file = $file->_getMessageFilesArray();
}
if(\is_string($file)) {
if(\filter_var($file, \FILTER_VALIDATE_URL)) {
$promises[] = \CharlotteDunois\Yasmin\Utils\URLHelpers::resolveURLToData($file)->then(function ($data) use ($file) {
return array('name' => \basename($file), 'data' => $data);
});
} elseif(\realpath($file)) {
$promises[] = \CharlotteDunois\Yasmin\Utils\FileHelpers::resolveFileResolvable($file)->then(function ($data) use ($file) {
return array('name' => \basename($file), 'data' => $data);
});
} else {
$promises[] = \React\Promise\resolve(array('name' => 'file-'.\bin2hex(\random_bytes(3)).'.jpg', 'data' => $file));
}
continue;
}
if(!\is_array($file)) {
continue;
}
if(!isset($file['data']) && !isset($file['path'])) {
throw new \InvalidArgumentException('Invalid file array passed, missing data and path, one is required');
}
if(!isset($file['name'])) {
if(isset($file['path'])) {
$file['name'] = \basename($file['path']);
} else {
$file['name'] = 'file-'.\bin2hex(\random_bytes(3)).'.jpg';
}
}
if(isset($file['path'])) {
if(filter_var($file['path'], \FILTER_VALIDATE_URL)) {
$promises[] = \CharlotteDunois\Yasmin\Utils\URLHelpers::resolveURLToData($file['path'])->then(function ($data) use ($file) {
$file['data'] = $data;
return $file;
});
} elseif(\CharlotteDunois\Yasmin\Utils\FileHelpers::getFilesystem()) {
$promises[] = \CharlotteDunois\Yasmin\Utils\FileHelpers::getFilesystem()->getContents($file['path'])->then(function ($data) use ($file) {
$file['data'] = $data;
return $file;
});
} else {
$file['data'] = \file_get_contents($file['path']);
$promises[] = \React\Promise\resolve($file);
}
} else {
$promises[] = \React\Promise\resolve($file);
}
}
return \React\Promise\all($promises);
} | php | static function resolveMessageOptionsFiles(array $options) {
if(empty($options['files'])) {
return \React\Promise\resolve(array());
}
$promises = array();
foreach($options['files'] as $file) {
if($file instanceof \CharlotteDunois\Yasmin\Models\MessageAttachment) {
$file = $file->_getMessageFilesArray();
}
if(\is_string($file)) {
if(\filter_var($file, \FILTER_VALIDATE_URL)) {
$promises[] = \CharlotteDunois\Yasmin\Utils\URLHelpers::resolveURLToData($file)->then(function ($data) use ($file) {
return array('name' => \basename($file), 'data' => $data);
});
} elseif(\realpath($file)) {
$promises[] = \CharlotteDunois\Yasmin\Utils\FileHelpers::resolveFileResolvable($file)->then(function ($data) use ($file) {
return array('name' => \basename($file), 'data' => $data);
});
} else {
$promises[] = \React\Promise\resolve(array('name' => 'file-'.\bin2hex(\random_bytes(3)).'.jpg', 'data' => $file));
}
continue;
}
if(!\is_array($file)) {
continue;
}
if(!isset($file['data']) && !isset($file['path'])) {
throw new \InvalidArgumentException('Invalid file array passed, missing data and path, one is required');
}
if(!isset($file['name'])) {
if(isset($file['path'])) {
$file['name'] = \basename($file['path']);
} else {
$file['name'] = 'file-'.\bin2hex(\random_bytes(3)).'.jpg';
}
}
if(isset($file['path'])) {
if(filter_var($file['path'], \FILTER_VALIDATE_URL)) {
$promises[] = \CharlotteDunois\Yasmin\Utils\URLHelpers::resolveURLToData($file['path'])->then(function ($data) use ($file) {
$file['data'] = $data;
return $file;
});
} elseif(\CharlotteDunois\Yasmin\Utils\FileHelpers::getFilesystem()) {
$promises[] = \CharlotteDunois\Yasmin\Utils\FileHelpers::getFilesystem()->getContents($file['path'])->then(function ($data) use ($file) {
$file['data'] = $data;
return $file;
});
} else {
$file['data'] = \file_get_contents($file['path']);
$promises[] = \React\Promise\resolve($file);
}
} else {
$promises[] = \React\Promise\resolve($file);
}
}
return \React\Promise\all($promises);
} | [
"static",
"function",
"resolveMessageOptionsFiles",
"(",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"options",
"[",
"'files'",
"]",
")",
")",
"{",
"return",
"\\",
"React",
"\\",
"Promise",
"\\",
"resolve",
"(",
"array",
"(",
")",
... | Resolves files of Message Options.
@param array $options
@return \React\Promise\ExtendedPromiseInterface
@throws \InvalidArgumentException | [
"Resolves",
"files",
"of",
"Message",
"Options",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/MessageHelpers.php#L156-L220 |
CharlotteDunois/Yasmin | src/Utils/MessageHelpers.php | MessageHelpers.splitMessage | static function splitMessage(string $text, array $options = array()) {
$options = \array_merge(\CharlotteDunois\Yasmin\Models\Message::DEFAULT_SPLIT_OPTIONS, $options);
if(\mb_strlen($text) > $options['maxLength']) {
$i = 0;
$messages = array();
$parts = \explode($options['char'], $text);
foreach($parts as $part) {
if(!isset($messages[$i])) {
$messages[$i] = '';
}
if((\mb_strlen($messages[$i]) + \mb_strlen($part) + 2) >= $options['maxLength']) {
$i++;
$messages[$i] = '';
}
$messages[$i] .= $part.$options['char'];
}
return $messages;
}
return array($text);
} | php | static function splitMessage(string $text, array $options = array()) {
$options = \array_merge(\CharlotteDunois\Yasmin\Models\Message::DEFAULT_SPLIT_OPTIONS, $options);
if(\mb_strlen($text) > $options['maxLength']) {
$i = 0;
$messages = array();
$parts = \explode($options['char'], $text);
foreach($parts as $part) {
if(!isset($messages[$i])) {
$messages[$i] = '';
}
if((\mb_strlen($messages[$i]) + \mb_strlen($part) + 2) >= $options['maxLength']) {
$i++;
$messages[$i] = '';
}
$messages[$i] .= $part.$options['char'];
}
return $messages;
}
return array($text);
} | [
"static",
"function",
"splitMessage",
"(",
"string",
"$",
"text",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"options",
"=",
"\\",
"array_merge",
"(",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"Message",
"::... | Splits a string into multiple chunks at a designated character that do not exceed a specific length.
Options will be merged into default split options (see Message), so missing elements will get added.
```
array(
'before' => string, (the string to add before the chunk)
'after' => string, (the string to add after the chunk)
'char' => string, (the string to split on)
'maxLength' => int (the max. length of each chunk)
)
```
@param string $text
@param array $options Options controlling the behaviour of the split.
@return string[]
@see \CharlotteDunois\Yasmin\Models\Message | [
"Splits",
"a",
"string",
"into",
"multiple",
"chunks",
"at",
"a",
"designated",
"character",
"that",
"do",
"not",
"exceed",
"a",
"specific",
"length",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/MessageHelpers.php#L240-L265 |
CharlotteDunois/Yasmin | src/Models/GuildMemberStorage.php | GuildMemberStorage.resolve | function resolve($guildmember) {
if($guildmember instanceof \CharlotteDunois\Yasmin\Models\GuildMember) {
return $guildmember;
}
if($guildmember instanceof \CharlotteDunois\Yasmin\Models\User) {
$guildmember = $guildmember->id;
}
if(\is_int($guildmember)) {
$guildmember = (string) $guildmember;
}
if(\is_string($guildmember) && parent::has($guildmember)) {
return parent::get($guildmember);
}
throw new \InvalidArgumentException('Unable to resolve unknown guild member');
} | php | function resolve($guildmember) {
if($guildmember instanceof \CharlotteDunois\Yasmin\Models\GuildMember) {
return $guildmember;
}
if($guildmember instanceof \CharlotteDunois\Yasmin\Models\User) {
$guildmember = $guildmember->id;
}
if(\is_int($guildmember)) {
$guildmember = (string) $guildmember;
}
if(\is_string($guildmember) && parent::has($guildmember)) {
return parent::get($guildmember);
}
throw new \InvalidArgumentException('Unable to resolve unknown guild member');
} | [
"function",
"resolve",
"(",
"$",
"guildmember",
")",
"{",
"if",
"(",
"$",
"guildmember",
"instanceof",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"GuildMember",
")",
"{",
"return",
"$",
"guildmember",
";",
"}",
"if",
"(",
"$",
"guildmem... | Resolves given data to a guildmember.
@param \CharlotteDunois\Yasmin\Models\GuildMember|\CharlotteDunois\Yasmin\Models\User|string|int $guildmember string/int = user ID
@return \CharlotteDunois\Yasmin\Models\GuildMember
@throws \InvalidArgumentException | [
"Resolves",
"given",
"data",
"to",
"a",
"guildmember",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/GuildMemberStorage.php#L38-L56 |
CharlotteDunois/Yasmin | src/Models/GuildMemberStorage.php | GuildMemberStorage.factory | function factory(array $data) {
if(parent::has($data['user']['id'])) {
$member = parent::get($data['user']['id']);
$member->_patch($data);
return $member;
}
$member = new \CharlotteDunois\Yasmin\Models\GuildMember($this->client, $this->guild, $data);
$this->set($member->id, $member);
return $member;
} | php | function factory(array $data) {
if(parent::has($data['user']['id'])) {
$member = parent::get($data['user']['id']);
$member->_patch($data);
return $member;
}
$member = new \CharlotteDunois\Yasmin\Models\GuildMember($this->client, $this->guild, $data);
$this->set($member->id, $member);
return $member;
} | [
"function",
"factory",
"(",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"parent",
"::",
"has",
"(",
"$",
"data",
"[",
"'user'",
"]",
"[",
"'id'",
"]",
")",
")",
"{",
"$",
"member",
"=",
"parent",
"::",
"get",
"(",
"$",
"data",
"[",
"'user'",
"]"... | Factory to create (or retrieve existing) guild members.
@param array $data
@return \CharlotteDunois\Yasmin\Models\GuildMember
@internal | [
"Factory",
"to",
"create",
"(",
"or",
"retrieve",
"existing",
")",
"guild",
"members",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/GuildMemberStorage.php#L103-L113 |
CharlotteDunois/Yasmin | src/Utils/Collector.php | Collector.collect | function collect() {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) {
$this->resolve = $resolve;
$this->reject = $reject;
$filter = $this->filter;
$handler = $this->handler;
$this->listener = function (...$item) use (&$filter, &$handler) {
if($filter === null || $filter(...$item)) {
list($key, $value) = $handler(...$item);
$this->bucket->set($key, $value);
if(($this->options['max'] ?? \INF) <= $this->bucket->count()) {
$this->stop();
}
}
};
if(($this->options['time'] ?? 30) > 0) {
$this->timer = self::$loop->addTimer(($this->options['time'] ?? 30), function () {
$this->stop();
});
}
$this->emitter->on($this->event, $this->listener);
}, function (callable $resolve, callable $reject) {
if($this->timer) {
self::$loop->cancelTimer($this->timer);
$this->timer = null;
}
$this->emitter->removeListener($this->event, $this->listener);
$reject(new \OutOfBoundsException('Operation cancelled'));
}));
} | php | function collect() {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) {
$this->resolve = $resolve;
$this->reject = $reject;
$filter = $this->filter;
$handler = $this->handler;
$this->listener = function (...$item) use (&$filter, &$handler) {
if($filter === null || $filter(...$item)) {
list($key, $value) = $handler(...$item);
$this->bucket->set($key, $value);
if(($this->options['max'] ?? \INF) <= $this->bucket->count()) {
$this->stop();
}
}
};
if(($this->options['time'] ?? 30) > 0) {
$this->timer = self::$loop->addTimer(($this->options['time'] ?? 30), function () {
$this->stop();
});
}
$this->emitter->on($this->event, $this->listener);
}, function (callable $resolve, callable $reject) {
if($this->timer) {
self::$loop->cancelTimer($this->timer);
$this->timer = null;
}
$this->emitter->removeListener($this->event, $this->listener);
$reject(new \OutOfBoundsException('Operation cancelled'));
}));
} | [
"function",
"collect",
"(",
")",
"{",
"return",
"(",
"new",
"\\",
"React",
"\\",
"Promise",
"\\",
"Promise",
"(",
"function",
"(",
"callable",
"$",
"resolve",
",",
"callable",
"$",
"reject",
")",
"{",
"$",
"this",
"->",
"resolve",
"=",
"$",
"resolve",
... | Starts collecting. Resolves with a collection.
@return \React\Promise\ExtendedPromiseInterface This promise is cancellable.
@throws \RangeException The exception the promise gets rejected with, if collecting times out.
@throws \OutOfBoundsException The exception the promise gets rejected with, if the promise gets cancelled. | [
"Starts",
"collecting",
".",
"Resolves",
"with",
"a",
"collection",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/Collector.php#L114-L149 |
CharlotteDunois/Yasmin | src/Utils/Collector.php | Collector.stop | function stop() {
if($this->timer) {
self::$loop->cancelTimer($this->timer);
$this->timer = null;
}
$this->emitter->removeListener($this->event, $this->listener);
$errors = (array) ($this->options['errors'] ?? array());
if(\in_array('max', $errors, true) && ($this->options['max'] ?? 0) > 0 && $this->bucket->count() < $this->options['max']) {
$reject = $this->reject;
$reject(new \RangeException('Collecting timed out (max not reached in time)'));
return;
}
$resolve = $this->resolve;
$resolve($this->bucket);
} | php | function stop() {
if($this->timer) {
self::$loop->cancelTimer($this->timer);
$this->timer = null;
}
$this->emitter->removeListener($this->event, $this->listener);
$errors = (array) ($this->options['errors'] ?? array());
if(\in_array('max', $errors, true) && ($this->options['max'] ?? 0) > 0 && $this->bucket->count() < $this->options['max']) {
$reject = $this->reject;
$reject(new \RangeException('Collecting timed out (max not reached in time)'));
return;
}
$resolve = $this->resolve;
$resolve($this->bucket);
} | [
"function",
"stop",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"timer",
")",
"{",
"self",
"::",
"$",
"loop",
"->",
"cancelTimer",
"(",
"$",
"this",
"->",
"timer",
")",
";",
"$",
"this",
"->",
"timer",
"=",
"null",
";",
"}",
"$",
"this",
"->",... | This will stop the collector.
@return void | [
"This",
"will",
"stop",
"the",
"collector",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/Collector.php#L155-L172 |
CharlotteDunois/Yasmin | src/Models/Role.php | Role.comparePositionTo | function comparePositionTo(\CharlotteDunois\Yasmin\Models\Role $role) {
if($this->position === $role->position) {
return $role->id <=> $this->id;
}
return $this->position <=> $role->position;
} | php | function comparePositionTo(\CharlotteDunois\Yasmin\Models\Role $role) {
if($this->position === $role->position) {
return $role->id <=> $this->id;
}
return $this->position <=> $role->position;
} | [
"function",
"comparePositionTo",
"(",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"Role",
"$",
"role",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"position",
"===",
"$",
"role",
"->",
"position",
")",
"{",
"return",
"$",
"role",
"->",
"... | Compares the position from the role to the given role.
@param \CharlotteDunois\Yasmin\Models\Role $role
@return int | [
"Compares",
"the",
"position",
"from",
"the",
"role",
"to",
"the",
"given",
"role",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Role.php#L169-L175 |
CharlotteDunois/Yasmin | src/Models/Role.php | Role.edit | function edit(array $options, string $reason = '') {
if(empty($options)) {
throw new \InvalidArgumentException('Unable to edit role with zero information');
}
$data = \CharlotteDunois\Yasmin\Utils\DataHelpers::applyOptions($options, array(
'name' => array('type' => 'string'),
'color' => array('parse' => array(\CharlotteDunois\Yasmin\Utils\DataHelpers::class, 'resolveColor')),
'hoist' => array('type' => 'bool'),
'position' => array('type' => 'int'),
'permissions' => null,
'mentionable' => array('type' => 'bool')
));
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data, $reason) {
$this->client->apimanager()->endpoints->guild->modifyGuildRole($this->guild->id, $this->id, $data, $reason)->done(function () use ($resolve) {
$resolve($this);
}, $reject);
}));
} | php | function edit(array $options, string $reason = '') {
if(empty($options)) {
throw new \InvalidArgumentException('Unable to edit role with zero information');
}
$data = \CharlotteDunois\Yasmin\Utils\DataHelpers::applyOptions($options, array(
'name' => array('type' => 'string'),
'color' => array('parse' => array(\CharlotteDunois\Yasmin\Utils\DataHelpers::class, 'resolveColor')),
'hoist' => array('type' => 'bool'),
'position' => array('type' => 'int'),
'permissions' => null,
'mentionable' => array('type' => 'bool')
));
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data, $reason) {
$this->client->apimanager()->endpoints->guild->modifyGuildRole($this->guild->id, $this->id, $data, $reason)->done(function () use ($resolve) {
$resolve($this);
}, $reject);
}));
} | [
"function",
"edit",
"(",
"array",
"$",
"options",
",",
"string",
"$",
"reason",
"=",
"''",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"options",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Unable to edit role with zero information'",
... | Edits the role with the given options. Resolves with $this.
Options are as following (only one is required):
```
array(
'name' => string,
'color' => int|string,
'hoist' => bool,
'position' => int,
'permissions' => int|\CharlotteDunois\Yasmin\Models\Permissions,
'mentionable' => bool
)
```
@param array $options
@param string $reason
@return \React\Promise\ExtendedPromiseInterface
@throws \InvalidArgumentException
@see \CharlotteDunois\Yasmin\Utils\DataHelpers::resolveColor() | [
"Edits",
"the",
"role",
"with",
"the",
"given",
"options",
".",
"Resolves",
"with",
"$this",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Role.php#L199-L218 |
CharlotteDunois/Yasmin | src/Models/Role.php | Role.delete | function delete(string $reason = '') {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($reason) {
$this->client->apimanager()->endpoints->guild->deleteGuildRole($this->guild->id, $this->id, $reason)->done(function () use ($resolve) {
$resolve();
}, $reject);
}));
} | php | function delete(string $reason = '') {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($reason) {
$this->client->apimanager()->endpoints->guild->deleteGuildRole($this->guild->id, $this->id, $reason)->done(function () use ($resolve) {
$resolve();
}, $reject);
}));
} | [
"function",
"delete",
"(",
"string",
"$",
"reason",
"=",
"''",
")",
"{",
"return",
"(",
"new",
"\\",
"React",
"\\",
"Promise",
"\\",
"Promise",
"(",
"function",
"(",
"callable",
"$",
"resolve",
",",
"callable",
"$",
"reject",
")",
"use",
"(",
"$",
"r... | Deletes the role.
@param string $reason
@return \React\Promise\ExtendedPromiseInterface | [
"Deletes",
"the",
"role",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Role.php#L225-L231 |
CharlotteDunois/Yasmin | src/Models/Role.php | Role.getCalculatedPosition | function getCalculatedPosition() {
$sorted = $this->guild->roles->sortCustom(function (\CharlotteDunois\Yasmin\Models\Role $a, \CharlotteDunois\Yasmin\Models\Role $b) {
return $b->comparePositionTo($a);
});
return $sorted->indexOf($this);
} | php | function getCalculatedPosition() {
$sorted = $this->guild->roles->sortCustom(function (\CharlotteDunois\Yasmin\Models\Role $a, \CharlotteDunois\Yasmin\Models\Role $b) {
return $b->comparePositionTo($a);
});
return $sorted->indexOf($this);
} | [
"function",
"getCalculatedPosition",
"(",
")",
"{",
"$",
"sorted",
"=",
"$",
"this",
"->",
"guild",
"->",
"roles",
"->",
"sortCustom",
"(",
"function",
"(",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"Role",
"$",
"a",
",",
"\\",
"Char... | Calculates the positon of the role in the Discord client.
@return int | [
"Calculates",
"the",
"positon",
"of",
"the",
"role",
"in",
"the",
"Discord",
"client",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Role.php#L237-L243 |
CharlotteDunois/Yasmin | src/Models/Role.php | Role.isEditable | function isEditable() {
if($this->managed) {
return false;
}
$member = $this->guild->me;
if(!$member->permissions->has(\CharlotteDunois\Yasmin\Models\Permissions::PERMISSIONS['MANAGE_ROLES'])) {
return false;
}
return ($member->getHighestRole()->comparePositionTo($this) > 0);
} | php | function isEditable() {
if($this->managed) {
return false;
}
$member = $this->guild->me;
if(!$member->permissions->has(\CharlotteDunois\Yasmin\Models\Permissions::PERMISSIONS['MANAGE_ROLES'])) {
return false;
}
return ($member->getHighestRole()->comparePositionTo($this) > 0);
} | [
"function",
"isEditable",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"managed",
")",
"{",
"return",
"false",
";",
"}",
"$",
"member",
"=",
"$",
"this",
"->",
"guild",
"->",
"me",
";",
"if",
"(",
"!",
"$",
"member",
"->",
"permissions",
"->",
"h... | Whether the role can be edited by the client user.
@return bool | [
"Whether",
"the",
"role",
"can",
"be",
"edited",
"by",
"the",
"client",
"user",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Role.php#L249-L260 |
CharlotteDunois/Yasmin | src/HTTP/AthenaRatelimitBucket.php | AthenaRatelimitBucket.handleRatelimit | function handleRatelimit(?int $limit, ?int $remaining, ?float $resetTime) {
return $this->get()->then(function ($data) use ($limit, $remaining, $resetTime) {
if($limit === null && $remaining === null && $resetTime === null) {
$limit = $data['limit'];
$remaining = $data['remaining'] + 1; // there is no ratelimit...
$resetTime = $data['resetTime'];
} else {
$limit = $limit ?? $data['limit'];
$remaining = $remaining ?? $data['remaining'];
$resetTime = $resetTime ?? $data['resetTime'];
}
if($remaining === 0 && $resetTime > \microtime(true)) {
$this->api->client->emit('debug', 'Endpoint "'.$this->endpoint.'" ratelimit encountered, continueing in '.($resetTime - \microtime(true)).' seconds');
}
return $this->set(array('limit' => $limit, 'remaining' => $remaining, 'resetTime' => $resetTime));
});
} | php | function handleRatelimit(?int $limit, ?int $remaining, ?float $resetTime) {
return $this->get()->then(function ($data) use ($limit, $remaining, $resetTime) {
if($limit === null && $remaining === null && $resetTime === null) {
$limit = $data['limit'];
$remaining = $data['remaining'] + 1; // there is no ratelimit...
$resetTime = $data['resetTime'];
} else {
$limit = $limit ?? $data['limit'];
$remaining = $remaining ?? $data['remaining'];
$resetTime = $resetTime ?? $data['resetTime'];
}
if($remaining === 0 && $resetTime > \microtime(true)) {
$this->api->client->emit('debug', 'Endpoint "'.$this->endpoint.'" ratelimit encountered, continueing in '.($resetTime - \microtime(true)).' seconds');
}
return $this->set(array('limit' => $limit, 'remaining' => $remaining, 'resetTime' => $resetTime));
});
} | [
"function",
"handleRatelimit",
"(",
"?",
"int",
"$",
"limit",
",",
"?",
"int",
"$",
"remaining",
",",
"?",
"float",
"$",
"resetTime",
")",
"{",
"return",
"$",
"this",
"->",
"get",
"(",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"data",
")",
"use... | Sets the ratelimits from the response
@param int|null $limit
@param int|null $remaining
@param float|null $resetTime Reset time in seconds with milliseconds.
@return \React\Promise\ExtendedPromiseInterface|void | [
"Sets",
"the",
"ratelimits",
"from",
"the",
"response"
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/AthenaRatelimitBucket.php#L96-L114 |
CharlotteDunois/Yasmin | src/HTTP/AthenaRatelimitBucket.php | AthenaRatelimitBucket.unshift | function unshift(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) {
\array_unshift($this->queue, $request);
$this->get()->then(function ($data) {
$data['remaining']++;
return $this->set($data);
})->done(null, array($this->api->client, 'handlePromiseRejection'));
return $this;
} | php | function unshift(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) {
\array_unshift($this->queue, $request);
$this->get()->then(function ($data) {
$data['remaining']++;
return $this->set($data);
})->done(null, array($this->api->client, 'handlePromiseRejection'));
return $this;
} | [
"function",
"unshift",
"(",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"HTTP",
"\\",
"APIRequest",
"$",
"request",
")",
"{",
"\\",
"array_unshift",
"(",
"$",
"this",
"->",
"queue",
",",
"$",
"request",
")",
";",
"$",
"this",
"->",
"get",
"(",
")",
... | Unshifts a new request into the queue. Modifies remaining ratelimit.
@param \CharlotteDunois\Yasmin\HTTP\APIRequest $request
@return $this | [
"Unshifts",
"a",
"new",
"request",
"into",
"the",
"queue",
".",
"Modifies",
"remaining",
"ratelimit",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/AthenaRatelimitBucket.php#L147-L157 |
CharlotteDunois/Yasmin | src/HTTP/AthenaRatelimitBucket.php | AthenaRatelimitBucket.getMeta | function getMeta() {
return $this->get()->then(function ($data) {
if($data['resetTime'] && \microtime(true) > $data['resetTime']) {
$data['resetTime'] = null;
$limited = false;
} else {
$limited = ($data['limit'] !== 0 && $data['remaining'] === 0);
}
return array('limited' => $limited, 'resetTime' => $data['resetTime']);
});
} | php | function getMeta() {
return $this->get()->then(function ($data) {
if($data['resetTime'] && \microtime(true) > $data['resetTime']) {
$data['resetTime'] = null;
$limited = false;
} else {
$limited = ($data['limit'] !== 0 && $data['remaining'] === 0);
}
return array('limited' => $limited, 'resetTime' => $data['resetTime']);
});
} | [
"function",
"getMeta",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"get",
"(",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
"[",
"'resetTime'",
"]",
"&&",
"\\",
"microtime",
"(",
"true",
")",
">",
"$",
... | Retrieves ratelimit meta data.
The resolved value must be:
```
array(
'limited' => bool,
'resetTime' => int|null
)
```
@return \React\Promise\ExtendedPromiseInterface|array | [
"Retrieves",
"ratelimit",
"meta",
"data",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/AthenaRatelimitBucket.php#L172-L183 |
CharlotteDunois/Yasmin | src/HTTP/AthenaRatelimitBucket.php | AthenaRatelimitBucket.shift | function shift() {
if(\count($this->queue) === 0) {
return false;
}
$item = \array_shift($this->queue);
$this->get()->then(function ($data) {
$data['remaining']--;
return $this->set($data);
})->done(null, array($this->api->client, 'handlePromiseRejection'));
return $item;
} | php | function shift() {
if(\count($this->queue) === 0) {
return false;
}
$item = \array_shift($this->queue);
$this->get()->then(function ($data) {
$data['remaining']--;
return $this->set($data);
})->done(null, array($this->api->client, 'handlePromiseRejection'));
return $item;
} | [
"function",
"shift",
"(",
")",
"{",
"if",
"(",
"\\",
"count",
"(",
"$",
"this",
"->",
"queue",
")",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"$",
"item",
"=",
"\\",
"array_shift",
"(",
"$",
"this",
"->",
"queue",
")",
";",
"$",
"this"... | Returns the first queue item or false. Modifies remaining ratelimit.
@return \CharlotteDunois\Yasmin\HTTP\APIRequest|false | [
"Returns",
"the",
"first",
"queue",
"item",
"or",
"false",
".",
"Modifies",
"remaining",
"ratelimit",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/AthenaRatelimitBucket.php#L189-L203 |
CharlotteDunois/Yasmin | src/HTTP/AthenaRatelimitBucket.php | AthenaRatelimitBucket.clear | function clear(): void {
$queue = $this->queue;
$this->queue = array();
while($item = \array_shift($queue)) {
unset($item);
}
} | php | function clear(): void {
$queue = $this->queue;
$this->queue = array();
while($item = \array_shift($queue)) {
unset($item);
}
} | [
"function",
"clear",
"(",
")",
":",
"void",
"{",
"$",
"queue",
"=",
"$",
"this",
"->",
"queue",
";",
"$",
"this",
"->",
"queue",
"=",
"array",
"(",
")",
";",
"while",
"(",
"$",
"item",
"=",
"\\",
"array_shift",
"(",
"$",
"queue",
")",
")",
"{",... | Unsets all queue items.
@return void | [
"Unsets",
"all",
"queue",
"items",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/AthenaRatelimitBucket.php#L209-L216 |
CharlotteDunois/Yasmin | src/HTTP/AthenaRatelimitBucket.php | AthenaRatelimitBucket.get | protected function get() {
return $this->cache->get('yasmin-ratelimiter-'.$this->endpoint, null, true)->then(null, function () {
return array('limit' => 0, 'remaining' => 0, 'resetTime' => null);
});
} | php | protected function get() {
return $this->cache->get('yasmin-ratelimiter-'.$this->endpoint, null, true)->then(null, function () {
return array('limit' => 0, 'remaining' => 0, 'resetTime' => null);
});
} | [
"protected",
"function",
"get",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"cache",
"->",
"get",
"(",
"'yasmin-ratelimiter-'",
".",
"$",
"this",
"->",
"endpoint",
",",
"null",
",",
"true",
")",
"->",
"then",
"(",
"null",
",",
"function",
"(",
")",
"... | Retrieves the cache data.
@return \React\Promise\ExtendedPromiseInterface | [
"Retrieves",
"the",
"cache",
"data",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/AthenaRatelimitBucket.php#L222-L226 |
CharlotteDunois/Yasmin | src/HTTP/AthenaRatelimitBucket.php | AthenaRatelimitBucket.set | protected function set(array $value) {
return $this->cache->set('yasmin-ratelimiter-'.$this->endpoint, $value)->then(null, function (\Throwable $e) {
if($e->getMessage() !== 'Client got destroyed') {
throw $e;
}
});
} | php | protected function set(array $value) {
return $this->cache->set('yasmin-ratelimiter-'.$this->endpoint, $value)->then(null, function (\Throwable $e) {
if($e->getMessage() !== 'Client got destroyed') {
throw $e;
}
});
} | [
"protected",
"function",
"set",
"(",
"array",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"cache",
"->",
"set",
"(",
"'yasmin-ratelimiter-'",
".",
"$",
"this",
"->",
"endpoint",
",",
"$",
"value",
")",
"->",
"then",
"(",
"null",
",",
"function... | Sets the cache data.
@param array $value
@return \React\Promise\ExtendedPromiseInterface | [
"Sets",
"the",
"cache",
"data",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/AthenaRatelimitBucket.php#L233-L239 |
CharlotteDunois/Yasmin | src/Models/GuildStorage.php | GuildStorage.resolve | function resolve($guild) {
if($guild instanceof \CharlotteDunois\Yasmin\Models\Guild) {
return $guild;
}
if(\is_int($guild)) {
$guild = (string) $guild;
}
if(\is_string($guild) && parent::has($guild)) {
return parent::get($guild);
}
throw new \InvalidArgumentException('Unable to resolve unknown guild');
} | php | function resolve($guild) {
if($guild instanceof \CharlotteDunois\Yasmin\Models\Guild) {
return $guild;
}
if(\is_int($guild)) {
$guild = (string) $guild;
}
if(\is_string($guild) && parent::has($guild)) {
return parent::get($guild);
}
throw new \InvalidArgumentException('Unable to resolve unknown guild');
} | [
"function",
"resolve",
"(",
"$",
"guild",
")",
"{",
"if",
"(",
"$",
"guild",
"instanceof",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"Guild",
")",
"{",
"return",
"$",
"guild",
";",
"}",
"if",
"(",
"\\",
"is_int",
"(",
"$",
"guild... | Resolves given data to a guild.
@param \CharlotteDunois\Yasmin\Models\Guild|string|int $guild string/int = guild ID
@return \CharlotteDunois\Yasmin\Models\Guild
@throws \InvalidArgumentException | [
"Resolves",
"given",
"data",
"to",
"a",
"guild",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/GuildStorage.php#L22-L36 |
CharlotteDunois/Yasmin | src/Models/GuildStorage.php | GuildStorage.delete | function delete($key) {
parent::delete($key);
if($this !== $this->client->guilds) {
$this->client->guilds->delete($key);
}
return $this;
} | php | function delete($key) {
parent::delete($key);
if($this !== $this->client->guilds) {
$this->client->guilds->delete($key);
}
return $this;
} | [
"function",
"delete",
"(",
"$",
"key",
")",
"{",
"parent",
"::",
"delete",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"this",
"!==",
"$",
"this",
"->",
"client",
"->",
"guilds",
")",
"{",
"$",
"this",
"->",
"client",
"->",
"guilds",
"->",
"delete... | {@inheritdoc}
@param string $key
@return $this | [
"{"
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/GuildStorage.php#L72-L79 |
CharlotteDunois/Yasmin | src/Models/GuildStorage.php | GuildStorage.factory | function factory(array $data, ?int $shardID = null) {
if(parent::has($data['id'])) {
$guild = parent::get($data['id']);
$guild->_patch($data);
return $guild;
}
$guild = new \CharlotteDunois\Yasmin\Models\Guild($this->client, $data, $shardID);
$this->set($guild->id, $guild);
return $guild;
} | php | function factory(array $data, ?int $shardID = null) {
if(parent::has($data['id'])) {
$guild = parent::get($data['id']);
$guild->_patch($data);
return $guild;
}
$guild = new \CharlotteDunois\Yasmin\Models\Guild($this->client, $data, $shardID);
$this->set($guild->id, $guild);
return $guild;
} | [
"function",
"factory",
"(",
"array",
"$",
"data",
",",
"?",
"int",
"$",
"shardID",
"=",
"null",
")",
"{",
"if",
"(",
"parent",
"::",
"has",
"(",
"$",
"data",
"[",
"'id'",
"]",
")",
")",
"{",
"$",
"guild",
"=",
"parent",
"::",
"get",
"(",
"$",
... | Factory to create (or retrieve existing) guilds.
@param array $data
@param int|null $shardID
@return \CharlotteDunois\Yasmin\Models\Guild
@internal | [
"Factory",
"to",
"create",
"(",
"or",
"retrieve",
"existing",
")",
"guilds",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/GuildStorage.php#L88-L98 |
CharlotteDunois/Yasmin | src/Models/MessageAttachment.php | MessageAttachment.setAttachment | function setAttachment(string $attachment, string $filename = '') {
$this->attachment = $attachment;
$this->filename = $filename;
return $this;
} | php | function setAttachment(string $attachment, string $filename = '') {
$this->attachment = $attachment;
$this->filename = $filename;
return $this;
} | [
"function",
"setAttachment",
"(",
"string",
"$",
"attachment",
",",
"string",
"$",
"filename",
"=",
"''",
")",
"{",
"$",
"this",
"->",
"attachment",
"=",
"$",
"attachment",
";",
"$",
"this",
"->",
"filename",
"=",
"$",
"filename",
";",
"return",
"$",
"... | Sets the attachment.
@param string $attachment An URL or the filepath, or the data.
@param string $filename The filename.
@return $this | [
"Sets",
"the",
"attachment",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/MessageAttachment.php#L118-L122 |
CharlotteDunois/Yasmin | src/Models/MessageAttachment.php | MessageAttachment._getMessageFilesArray | function _getMessageFilesArray() {
$props = array(
'name' => $this->filename
);
$file = @\realpath($this->attachment);
if($file) {
$props['path'] = $file;
} elseif(\filter_var($this->attachment, \FILTER_VALIDATE_URL)) {
$props['path'] = $this->attachment;
} else {
$props['data'] = $this->attachment;
}
if(empty($props['name'])) {
if(!empty($props['path'])) {
$props['name'] = \basename($props['path']);
} else {
$props['name'] = 'file-'.\bin2hex(\random_bytes(3)).'.jpg';
}
}
return $props;
} | php | function _getMessageFilesArray() {
$props = array(
'name' => $this->filename
);
$file = @\realpath($this->attachment);
if($file) {
$props['path'] = $file;
} elseif(\filter_var($this->attachment, \FILTER_VALIDATE_URL)) {
$props['path'] = $this->attachment;
} else {
$props['data'] = $this->attachment;
}
if(empty($props['name'])) {
if(!empty($props['path'])) {
$props['name'] = \basename($props['path']);
} else {
$props['name'] = 'file-'.\bin2hex(\random_bytes(3)).'.jpg';
}
}
return $props;
} | [
"function",
"_getMessageFilesArray",
"(",
")",
"{",
"$",
"props",
"=",
"array",
"(",
"'name'",
"=>",
"$",
"this",
"->",
"filename",
")",
";",
"$",
"file",
"=",
"@",
"\\",
"realpath",
"(",
"$",
"this",
"->",
"attachment",
")",
";",
"if",
"(",
"$",
"... | Returns a proper message files array.
@return array
@internal | [
"Returns",
"a",
"proper",
"message",
"files",
"array",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/MessageAttachment.php#L129-L152 |
CharlotteDunois/Yasmin | src/Models/TextChannel.php | TextChannel.createWebhook | function createWebhook(string $name, ?string $avatar = null, string $reason = '') {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($name, $avatar, $reason) {
if(!empty($avatar)) {
$file = \CharlotteDunois\Yasmin\Utils\FileHelpers::resolveFileResolvable($avatar)->then(function ($avatar) {
return \CharlotteDunois\Yasmin\Utils\DataHelpers::makeBase64URI($avatar);
});
} else {
$file = \React\Promise\resolve(null);
}
$file->done(function ($avatar = null) use ($name, $reason, $resolve, $reject) {
$this->client->apimanager()->endpoints->webhook->createWebhook($this->id, $name, $avatar, $reason)->done(function ($data) use ($resolve) {
$hook = new \CharlotteDunois\Yasmin\Models\Webhook($this->client, $data);
$resolve($hook);
}, $reject);
}, $reject);
}));
} | php | function createWebhook(string $name, ?string $avatar = null, string $reason = '') {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($name, $avatar, $reason) {
if(!empty($avatar)) {
$file = \CharlotteDunois\Yasmin\Utils\FileHelpers::resolveFileResolvable($avatar)->then(function ($avatar) {
return \CharlotteDunois\Yasmin\Utils\DataHelpers::makeBase64URI($avatar);
});
} else {
$file = \React\Promise\resolve(null);
}
$file->done(function ($avatar = null) use ($name, $reason, $resolve, $reject) {
$this->client->apimanager()->endpoints->webhook->createWebhook($this->id, $name, $avatar, $reason)->done(function ($data) use ($resolve) {
$hook = new \CharlotteDunois\Yasmin\Models\Webhook($this->client, $data);
$resolve($hook);
}, $reject);
}, $reject);
}));
} | [
"function",
"createWebhook",
"(",
"string",
"$",
"name",
",",
"?",
"string",
"$",
"avatar",
"=",
"null",
",",
"string",
"$",
"reason",
"=",
"''",
")",
"{",
"return",
"(",
"new",
"\\",
"React",
"\\",
"Promise",
"\\",
"Promise",
"(",
"function",
"(",
"... | Create a webhook for the channel. Resolves with the new Webhook instance.
@param string $name
@param string|null $avatar An URL or file path, or data.
@param string $reason
@return \React\Promise\ExtendedPromiseInterface
@see \CharlotteDunois\Yasmin\Models\Webhook | [
"Create",
"a",
"webhook",
"for",
"the",
"channel",
".",
"Resolves",
"with",
"the",
"new",
"Webhook",
"instance",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/TextChannel.php#L151-L168 |
CharlotteDunois/Yasmin | src/Models/TextChannel.php | TextChannel.fetchWebhooks | function fetchWebhooks() {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) {
$this->client->apimanager()->endpoints->webhook->getChannelWebhooks($this->id)->done(function ($data) use ($resolve) {
$collect = new \CharlotteDunois\Collect\Collection();
foreach($data as $web) {
$hook = new \CharlotteDunois\Yasmin\Models\Webhook($this->client, $web);
$collect->set($hook->id, $hook);
}
$resolve($collect);
}, $reject);
}));
} | php | function fetchWebhooks() {
return (new \React\Promise\Promise(function (callable $resolve, callable $reject) {
$this->client->apimanager()->endpoints->webhook->getChannelWebhooks($this->id)->done(function ($data) use ($resolve) {
$collect = new \CharlotteDunois\Collect\Collection();
foreach($data as $web) {
$hook = new \CharlotteDunois\Yasmin\Models\Webhook($this->client, $web);
$collect->set($hook->id, $hook);
}
$resolve($collect);
}, $reject);
}));
} | [
"function",
"fetchWebhooks",
"(",
")",
"{",
"return",
"(",
"new",
"\\",
"React",
"\\",
"Promise",
"\\",
"Promise",
"(",
"function",
"(",
"callable",
"$",
"resolve",
",",
"callable",
"$",
"reject",
")",
"{",
"$",
"this",
"->",
"client",
"->",
"apimanager"... | Fetches the channel's webhooks. Resolves with a Collection of Webhook instances, mapped by their ID.
@return \React\Promise\ExtendedPromiseInterface
@see \CharlotteDunois\Yasmin\Models\Webhook | [
"Fetches",
"the",
"channel",
"s",
"webhooks",
".",
"Resolves",
"with",
"a",
"Collection",
"of",
"Webhook",
"instances",
"mapped",
"by",
"their",
"ID",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/TextChannel.php#L175-L188 |
CharlotteDunois/Yasmin | src/Models/PresenceStorage.php | PresenceStorage.resolve | function resolve($presence) {
if($presence instanceof \CharlotteDunois\Yasmin\Models\Presence) {
return $presence;
}
if($presence instanceof \CharlotteDunois\Yasmin\Models\User) {
$presence = $presence->id;
}
if(\is_int($presence)) {
$presence = (string) $presence;
}
if(\is_string($presence) && parent::has($presence)) {
return parent::get($presence);
}
throw new \InvalidArgumentException('Unable to resolve unknown presence');
} | php | function resolve($presence) {
if($presence instanceof \CharlotteDunois\Yasmin\Models\Presence) {
return $presence;
}
if($presence instanceof \CharlotteDunois\Yasmin\Models\User) {
$presence = $presence->id;
}
if(\is_int($presence)) {
$presence = (string) $presence;
}
if(\is_string($presence) && parent::has($presence)) {
return parent::get($presence);
}
throw new \InvalidArgumentException('Unable to resolve unknown presence');
} | [
"function",
"resolve",
"(",
"$",
"presence",
")",
"{",
"if",
"(",
"$",
"presence",
"instanceof",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"Presence",
")",
"{",
"return",
"$",
"presence",
";",
"}",
"if",
"(",
"$",
"presence",
"instan... | Resolves given data to a presence.
@param \CharlotteDunois\Yasmin\Models\Presence|\CharlotteDunois\Yasmin\Models\User|string|int $presence string/int = user ID
@return \CharlotteDunois\Yasmin\Models\Presence
@throws \InvalidArgumentException | [
"Resolves",
"given",
"data",
"to",
"a",
"presence",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/PresenceStorage.php#L36-L54 |
CharlotteDunois/Yasmin | src/Models/PresenceStorage.php | PresenceStorage.set | function set($key, $value) {
if(!$this->enabled) {
return $this;
}
parent::set($key, $value);
if($this !== $this->client->presences) {
$this->client->presences->set($key, $value);
}
return $this;
} | php | function set($key, $value) {
if(!$this->enabled) {
return $this;
}
parent::set($key, $value);
if($this !== $this->client->presences) {
$this->client->presences->set($key, $value);
}
return $this;
} | [
"function",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"$",
"this",
";",
"}",
"parent",
"::",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"if",
"(",
"$",
"... | {@inheritdoc}
@param string $key
@param \CharlotteDunois\Yasmin\Models\Presence $value
@return $this | [
"{"
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/PresenceStorage.php#L80-L91 |
CharlotteDunois/Yasmin | src/Models/PresenceStorage.php | PresenceStorage.delete | function delete($key) {
if(!$this->enabled) {
return $this;
}
parent::delete($key);
if($this !== $this->client->presences) {
$this->client->presences->delete($key);
}
return $this;
} | php | function delete($key) {
if(!$this->enabled) {
return $this;
}
parent::delete($key);
if($this !== $this->client->presences) {
$this->client->presences->delete($key);
}
return $this;
} | [
"function",
"delete",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"$",
"this",
";",
"}",
"parent",
"::",
"delete",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"this",
"!==",
"$",
"this",
"->",
"... | {@inheritdoc}
@param string $key
@return $this | [
"{"
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/PresenceStorage.php#L98-L109 |
CharlotteDunois/Yasmin | src/Models/PresenceStorage.php | PresenceStorage.factory | function factory(array $data) {
$presence = new \CharlotteDunois\Yasmin\Models\Presence($this->client, $data);
$this->set($presence->userID, $presence);
return $presence;
} | php | function factory(array $data) {
$presence = new \CharlotteDunois\Yasmin\Models\Presence($this->client, $data);
$this->set($presence->userID, $presence);
return $presence;
} | [
"function",
"factory",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"presence",
"=",
"new",
"\\",
"CharlotteDunois",
"\\",
"Yasmin",
"\\",
"Models",
"\\",
"Presence",
"(",
"$",
"this",
"->",
"client",
",",
"$",
"data",
")",
";",
"$",
"this",
"->",
"set"... | Factory to create presences.
@param array $data
@return \CharlotteDunois\Yasmin\Models\Presence
@internal | [
"Factory",
"to",
"create",
"presences",
"."
] | train | https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/PresenceStorage.php#L117-L121 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.initLanguageMap | private static function initLanguageMap($language = '')
{
if (count(self::$map) > 0 && (($language == '') || ($language == self::$language))) {
return;
}
// Is a specific map associated with $language?
if (isset(self::$maps[$language]) && is_array(self::$maps[$language])) {
// Move this map to end. This means it will have priority over others
$m = self::$maps[$language];
unset(self::$maps[$language]);
self::$maps[$language] = $m;
}
// Reset static vars
self::$language = $language;
self::$map = array();
self::$chars = '';
foreach (self::$maps as $map) {
foreach ($map as $orig => $conv) {
self::$map[$orig] = $conv;
self::$chars .= $orig;
}
}
self::$regex = '/[' . self::$chars . ']/u';
} | php | private static function initLanguageMap($language = '')
{
if (count(self::$map) > 0 && (($language == '') || ($language == self::$language))) {
return;
}
// Is a specific map associated with $language?
if (isset(self::$maps[$language]) && is_array(self::$maps[$language])) {
// Move this map to end. This means it will have priority over others
$m = self::$maps[$language];
unset(self::$maps[$language]);
self::$maps[$language] = $m;
}
// Reset static vars
self::$language = $language;
self::$map = array();
self::$chars = '';
foreach (self::$maps as $map) {
foreach ($map as $orig => $conv) {
self::$map[$orig] = $conv;
self::$chars .= $orig;
}
}
self::$regex = '/[' . self::$chars . ']/u';
} | [
"private",
"static",
"function",
"initLanguageMap",
"(",
"$",
"language",
"=",
"''",
")",
"{",
"if",
"(",
"count",
"(",
"self",
"::",
"$",
"map",
")",
">",
"0",
"&&",
"(",
"(",
"$",
"language",
"==",
"''",
")",
"||",
"(",
"$",
"language",
"==",
"... | Initializes the character map.
Part of the URLify.php Project <https://github.com/jbroadway/urlify/>
@see https://github.com/jbroadway/urlify/blob/master/URLify.php | [
"Initializes",
"the",
"character",
"map",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L260-L287 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.is_numeric_array | public static function is_numeric_array($array)
{
if (!is_array($array)) { return false; }
$current = 0;
foreach (array_keys($array) as $key) {
if ($key !== $current) { return false; }
$current++;
}
return true;
} | php | public static function is_numeric_array($array)
{
if (!is_array($array)) { return false; }
$current = 0;
foreach (array_keys($array) as $key) {
if ($key !== $current) { return false; }
$current++;
}
return true;
} | [
"public",
"static",
"function",
"is_numeric_array",
"(",
"$",
"array",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"array",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"current",
"=",
"0",
";",
"foreach",
"(",
"array_keys",
"(",
"$",
"array"... | Returns boolean if a function is flat/sequential numeric array
@param array $array An array to test
@return boolean | [
"Returns",
"boolean",
"if",
"a",
"function",
"is",
"flat",
"/",
"sequential",
"numeric",
"array"
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L359-L371 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.var_dump | public static function var_dump($var, $return = false, $expandLevel = 1)
{
self::$hasArray = false;
$toggScript = 'var colToggle = function(toggID) {var img = document.getElementById(toggID);if (document.getElementById(toggID + "-collapsable").style.display == "none") {document.getElementById(toggID + "-collapsable").style.display = "inline";setImg(toggID, 0);var previousSibling = document.getElementById(toggID + "-collapsable").previousSibling;while (previousSibling != null && (previousSibling.nodeType != 1 || previousSibling.tagName.toLowerCase() != "br")) {previousSibling = previousSibling.previousSibling;}} else {document.getElementById(toggID + "-collapsable").style.display = "none";setImg(toggID, 1);var previousSibling = document.getElementById(toggID + "-collapsable").previousSibling; while (previousSibling != null && (previousSibling.nodeType != 1 || previousSibling.tagName.toLowerCase() != "br")) {previousSibling = previousSibling.previousSibling;}}};';
$imgScript = 'var setImg = function(objID,imgID,addStyle) {var imgStore = ["data:image/png;base64,' . self::$icon_collapse . '", "data:image/png;base64,' . self::$icon_expand . '"];if (objID) {document.getElementById(objID).setAttribute("src", imgStore[imgID]);if (addStyle){document.getElementById(objID).setAttribute("style", "position:relative;left:-5px;top:-1px;cursor:pointer;");}}};';
$jsCode = preg_replace('/ +/', ' ', '<script>' . $toggScript . $imgScript . '</script>');
$html = '<pre style="margin-bottom: 18px;' .
'background: #f7f7f9;' .
'border: 1px solid #e1e1e8;' .
'padding: 8px;' .
'border-radius: 4px;' .
'-moz-border-radius: 4px;' .
'-webkit-border radius: 4px;' .
'display: block;' .
'font-size: 12.05px;' .
'white-space: pre-wrap;' .
'word-wrap: break-word;' .
'color: #333;' .
'font-family: Menlo,Monaco,Consolas,\'Courier New\',monospace;">';
$done = array();
$html .= self::recursiveVarDumpHelper($var, intval($expandLevel), 0, $done);
$html .= '</pre>';
if (self::$hasArray) {
$html = $jsCode . $html;
}
if (!$return) {
echo $html;
}
return $html;
} | php | public static function var_dump($var, $return = false, $expandLevel = 1)
{
self::$hasArray = false;
$toggScript = 'var colToggle = function(toggID) {var img = document.getElementById(toggID);if (document.getElementById(toggID + "-collapsable").style.display == "none") {document.getElementById(toggID + "-collapsable").style.display = "inline";setImg(toggID, 0);var previousSibling = document.getElementById(toggID + "-collapsable").previousSibling;while (previousSibling != null && (previousSibling.nodeType != 1 || previousSibling.tagName.toLowerCase() != "br")) {previousSibling = previousSibling.previousSibling;}} else {document.getElementById(toggID + "-collapsable").style.display = "none";setImg(toggID, 1);var previousSibling = document.getElementById(toggID + "-collapsable").previousSibling; while (previousSibling != null && (previousSibling.nodeType != 1 || previousSibling.tagName.toLowerCase() != "br")) {previousSibling = previousSibling.previousSibling;}}};';
$imgScript = 'var setImg = function(objID,imgID,addStyle) {var imgStore = ["data:image/png;base64,' . self::$icon_collapse . '", "data:image/png;base64,' . self::$icon_expand . '"];if (objID) {document.getElementById(objID).setAttribute("src", imgStore[imgID]);if (addStyle){document.getElementById(objID).setAttribute("style", "position:relative;left:-5px;top:-1px;cursor:pointer;");}}};';
$jsCode = preg_replace('/ +/', ' ', '<script>' . $toggScript . $imgScript . '</script>');
$html = '<pre style="margin-bottom: 18px;' .
'background: #f7f7f9;' .
'border: 1px solid #e1e1e8;' .
'padding: 8px;' .
'border-radius: 4px;' .
'-moz-border-radius: 4px;' .
'-webkit-border radius: 4px;' .
'display: block;' .
'font-size: 12.05px;' .
'white-space: pre-wrap;' .
'word-wrap: break-word;' .
'color: #333;' .
'font-family: Menlo,Monaco,Consolas,\'Courier New\',monospace;">';
$done = array();
$html .= self::recursiveVarDumpHelper($var, intval($expandLevel), 0, $done);
$html .= '</pre>';
if (self::$hasArray) {
$html = $jsCode . $html;
}
if (!$return) {
echo $html;
}
return $html;
} | [
"public",
"static",
"function",
"var_dump",
"(",
"$",
"var",
",",
"$",
"return",
"=",
"false",
",",
"$",
"expandLevel",
"=",
"1",
")",
"{",
"self",
"::",
"$",
"hasArray",
"=",
"false",
";",
"$",
"toggScript",
"=",
"'var colToggle = function(toggID) {var img ... | Display a variable's contents using nice HTML formatting and will
properly display the value of booleans as true or false
@see recursiveVarDumpHelper()
@param mixed $var The variable to dump
@return string | [
"Display",
"a",
"variable",
"s",
"contents",
"using",
"nice",
"HTML",
"formatting",
"and",
"will",
"properly",
"display",
"the",
"value",
"of",
"booleans",
"as",
"true",
"or",
"false"
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L382-L414 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.recursiveVarDumpHelper | protected static function recursiveVarDumpHelper($var, $expLevel, $depth = 0, $done = array())
{
$html = '';
if ($expLevel > 0) {
$expLevel--;
$setImg = 0;
$setStyle = 'display:inline;';
} elseif ($expLevel == 0) {
$setImg = 1;
$setStyle='display:none;';
} elseif ($expLevel < 0) {
$setImg = 0;
$setStyle = 'display:inline;';
}
if (is_bool($var)) {
$html .= '<span style="color:#588bff;">bool</span><span style="color:#999;">(</span><strong>' . (($var) ? 'true' : 'false') . '</strong><span style="color:#999;">)</span>';
} elseif (is_int($var)) {
$html .= '<span style="color:#588bff;">int</span><span style="color:#999;">(</span><strong>' . $var . '</strong><span style="color:#999;">)</span>';
} elseif (is_float($var)) {
$html .= '<span style="color:#588bff;">float</span><span style="color:#999;">(</span><strong>' . $var . '</strong><span style="color:#999;">)</span>';
} elseif (is_string($var)) {
$html .= '<span style="color:#588bff;">string</span><span style="color:#999;">(</span>' . strlen($var) . '<span style="color:#999;">)</span> <strong>"' . self::htmlentities($var) . '"</strong>';
} elseif (is_null($var)) {
$html .= '<strong>NULL</strong>';
} elseif (is_resource($var)) {
$html .= '<span style="color:#588bff;">resource</span>("' . get_resource_type($var) . '") <strong>"' . $var . '"</strong>';
} elseif (is_array($var)) {
// Check for recursion
if ($depth > 0) {
foreach ($done as $prev) {
if ($prev === $var) {
$html .= '<span style="color:#588bff;">array</span>(' . count($var) . ') *RECURSION DETECTED*';
return $html;
}
}
// Keep track of variables we have already processed to detect recursion
$done[] = &$var;
}
self::$hasArray = true;
$uuid = 'include-php-' . uniqid() . mt_rand(1, 1000000);
$html .= (!empty($var) ? ' <img id="' . $uuid . '" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" onclick="javascript:colToggle(this.id);" /><script>setImg("' . $uuid . '",'.$setImg.',1);</script>' : '') . '<span style="color:#588bff;">array</span>(' . count($var) . ')';
if (!empty($var)) {
$html .= ' <span id="' . $uuid . '-collapsable" style="'.$setStyle.'"><br />[<br />';
$indent = 4;
$longest_key = 0;
foreach ($var as $key => $value) {
if (is_string($key)) {
$longest_key = max($longest_key, strlen($key) + 2);
} else {
$longest_key = max($longest_key, strlen($key));
}
}
foreach ($var as $key => $value) {
if (is_numeric($key)) {
$html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, ' ');
} else {
$html .= str_repeat(' ', $indent) . str_pad('"' . self::htmlentities($key) . '"', $longest_key, ' ');
}
$html .= ' => ';
$value = explode('<br />', self::recursiveVarDumpHelper($value, $expLevel, $depth + 1, $done));
foreach ($value as $line => $val) {
if ($line != 0) {
$value[$line] = str_repeat(' ', $indent * 2) . $val;
}
}
$html .= implode('<br />', $value) . '<br />';
}
$html .= ']</span>';
}
} elseif (is_object($var)) {
// Check for recursion
foreach ($done as $prev) {
if ($prev === $var) {
$html .= '<span style="color:#588bff;">object</span>(' . get_class($var) . ') *RECURSION DETECTED*';
return $html;
}
}
// Keep track of variables we have already processed to detect recursion
$done[] = &$var;
self::$hasArray=true;
$uuid = 'include-php-' . uniqid() . mt_rand(1, 1000000);
$html .= ' <img id="' . $uuid . '" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" onclick="javascript:colToggle(this.id);" /><script>setImg("' . $uuid . '",'.$setImg.',1);</script><span style="color:#588bff;">object</span>(' . get_class($var) . ') <span id="' . $uuid . '-collapsable" style="'.$setStyle.'"><br />[<br />';
$varArray = (array) $var;
$indent = 4;
$longest_key = 0;
foreach ($varArray as $key => $value) {
if (substr($key, 0, 2) == "\0*") {
unset($varArray[$key]);
$key = 'protected:' . substr($key, 3);
$varArray[$key] = $value;
} elseif (substr($key, 0, 1) == "\0") {
unset($varArray[$key]);
$key = 'private:' . substr($key, 1, strpos(substr($key, 1), "\0")) . ':' . substr($key, strpos(substr($key, 1), "\0") + 2);
$varArray[$key] = $value;
}
if (is_string($key)) {
$longest_key = max($longest_key, strlen($key) + 2);
} else {
$longest_key = max($longest_key, strlen($key));
}
}
foreach ($varArray as $key => $value) {
if (is_numeric($key)) {
$html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, ' ');
} else {
$html .= str_repeat(' ', $indent) . str_pad('"' . self::htmlentities($key) . '"', $longest_key, ' ');
}
$html .= ' => ';
$value = explode('<br />', self::recursiveVarDumpHelper($value, $expLevel, $depth + 1, $done));
foreach ($value as $line => $val) {
if ($line != 0) {
$value[$line] = str_repeat(' ', $indent * 2) . $val;
}
}
$html .= implode('<br />', $value) . '<br />';
}
$html .= ']</span>';
}
return $html;
} | php | protected static function recursiveVarDumpHelper($var, $expLevel, $depth = 0, $done = array())
{
$html = '';
if ($expLevel > 0) {
$expLevel--;
$setImg = 0;
$setStyle = 'display:inline;';
} elseif ($expLevel == 0) {
$setImg = 1;
$setStyle='display:none;';
} elseif ($expLevel < 0) {
$setImg = 0;
$setStyle = 'display:inline;';
}
if (is_bool($var)) {
$html .= '<span style="color:#588bff;">bool</span><span style="color:#999;">(</span><strong>' . (($var) ? 'true' : 'false') . '</strong><span style="color:#999;">)</span>';
} elseif (is_int($var)) {
$html .= '<span style="color:#588bff;">int</span><span style="color:#999;">(</span><strong>' . $var . '</strong><span style="color:#999;">)</span>';
} elseif (is_float($var)) {
$html .= '<span style="color:#588bff;">float</span><span style="color:#999;">(</span><strong>' . $var . '</strong><span style="color:#999;">)</span>';
} elseif (is_string($var)) {
$html .= '<span style="color:#588bff;">string</span><span style="color:#999;">(</span>' . strlen($var) . '<span style="color:#999;">)</span> <strong>"' . self::htmlentities($var) . '"</strong>';
} elseif (is_null($var)) {
$html .= '<strong>NULL</strong>';
} elseif (is_resource($var)) {
$html .= '<span style="color:#588bff;">resource</span>("' . get_resource_type($var) . '") <strong>"' . $var . '"</strong>';
} elseif (is_array($var)) {
// Check for recursion
if ($depth > 0) {
foreach ($done as $prev) {
if ($prev === $var) {
$html .= '<span style="color:#588bff;">array</span>(' . count($var) . ') *RECURSION DETECTED*';
return $html;
}
}
// Keep track of variables we have already processed to detect recursion
$done[] = &$var;
}
self::$hasArray = true;
$uuid = 'include-php-' . uniqid() . mt_rand(1, 1000000);
$html .= (!empty($var) ? ' <img id="' . $uuid . '" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" onclick="javascript:colToggle(this.id);" /><script>setImg("' . $uuid . '",'.$setImg.',1);</script>' : '') . '<span style="color:#588bff;">array</span>(' . count($var) . ')';
if (!empty($var)) {
$html .= ' <span id="' . $uuid . '-collapsable" style="'.$setStyle.'"><br />[<br />';
$indent = 4;
$longest_key = 0;
foreach ($var as $key => $value) {
if (is_string($key)) {
$longest_key = max($longest_key, strlen($key) + 2);
} else {
$longest_key = max($longest_key, strlen($key));
}
}
foreach ($var as $key => $value) {
if (is_numeric($key)) {
$html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, ' ');
} else {
$html .= str_repeat(' ', $indent) . str_pad('"' . self::htmlentities($key) . '"', $longest_key, ' ');
}
$html .= ' => ';
$value = explode('<br />', self::recursiveVarDumpHelper($value, $expLevel, $depth + 1, $done));
foreach ($value as $line => $val) {
if ($line != 0) {
$value[$line] = str_repeat(' ', $indent * 2) . $val;
}
}
$html .= implode('<br />', $value) . '<br />';
}
$html .= ']</span>';
}
} elseif (is_object($var)) {
// Check for recursion
foreach ($done as $prev) {
if ($prev === $var) {
$html .= '<span style="color:#588bff;">object</span>(' . get_class($var) . ') *RECURSION DETECTED*';
return $html;
}
}
// Keep track of variables we have already processed to detect recursion
$done[] = &$var;
self::$hasArray=true;
$uuid = 'include-php-' . uniqid() . mt_rand(1, 1000000);
$html .= ' <img id="' . $uuid . '" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" onclick="javascript:colToggle(this.id);" /><script>setImg("' . $uuid . '",'.$setImg.',1);</script><span style="color:#588bff;">object</span>(' . get_class($var) . ') <span id="' . $uuid . '-collapsable" style="'.$setStyle.'"><br />[<br />';
$varArray = (array) $var;
$indent = 4;
$longest_key = 0;
foreach ($varArray as $key => $value) {
if (substr($key, 0, 2) == "\0*") {
unset($varArray[$key]);
$key = 'protected:' . substr($key, 3);
$varArray[$key] = $value;
} elseif (substr($key, 0, 1) == "\0") {
unset($varArray[$key]);
$key = 'private:' . substr($key, 1, strpos(substr($key, 1), "\0")) . ':' . substr($key, strpos(substr($key, 1), "\0") + 2);
$varArray[$key] = $value;
}
if (is_string($key)) {
$longest_key = max($longest_key, strlen($key) + 2);
} else {
$longest_key = max($longest_key, strlen($key));
}
}
foreach ($varArray as $key => $value) {
if (is_numeric($key)) {
$html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, ' ');
} else {
$html .= str_repeat(' ', $indent) . str_pad('"' . self::htmlentities($key) . '"', $longest_key, ' ');
}
$html .= ' => ';
$value = explode('<br />', self::recursiveVarDumpHelper($value, $expLevel, $depth + 1, $done));
foreach ($value as $line => $val) {
if ($line != 0) {
$value[$line] = str_repeat(' ', $indent * 2) . $val;
}
}
$html .= implode('<br />', $value) . '<br />';
}
$html .= ']</span>';
}
return $html;
} | [
"protected",
"static",
"function",
"recursiveVarDumpHelper",
"(",
"$",
"var",
",",
"$",
"expLevel",
",",
"$",
"depth",
"=",
"0",
",",
"$",
"done",
"=",
"array",
"(",
")",
")",
"{",
"$",
"html",
"=",
"''",
";",
"if",
"(",
"$",
"expLevel",
">",
"0",
... | Display a variable's contents using nice HTML formatting (Without
the <pre> tag) and will properly display the values of variables
like booleans and resources. Supports collapsable arrays and objects
as well.
@param mixed $var The variable to dump
@return string | [
"Display",
"a",
"variable",
"s",
"contents",
"using",
"nice",
"HTML",
"formatting",
"(",
"Without",
"the",
"<pre",
">",
"tag",
")",
"and",
"will",
"properly",
"display",
"the",
"values",
"of",
"variables",
"like",
"booleans",
"and",
"resources",
".",
"Suppor... | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L425-L571 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.slugify | public static function slugify($string, $separator = '-', $css_mode = false)
{
// Compatibility with 1.0.* parameter ordering for semver
if ($separator === true || $separator === false) {
$css_mode = $separator;
$separator = '-';
// Raise deprecation error
trigger_error(
'util::slugify() now takes $css_mode as the third parameter, please update your code',
E_USER_DEPRECATED
);
}
$slug = preg_replace('/([^a-z0-9]+)/', $separator, strtolower(self::remove_accents($string)));
if ($css_mode) {
$digits = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
if (is_numeric(substr($slug, 0, 1))) {
$slug = $digits[substr($slug, 0, 1)] . substr($slug, 1);
}
}
return $slug;
} | php | public static function slugify($string, $separator = '-', $css_mode = false)
{
// Compatibility with 1.0.* parameter ordering for semver
if ($separator === true || $separator === false) {
$css_mode = $separator;
$separator = '-';
// Raise deprecation error
trigger_error(
'util::slugify() now takes $css_mode as the third parameter, please update your code',
E_USER_DEPRECATED
);
}
$slug = preg_replace('/([^a-z0-9]+)/', $separator, strtolower(self::remove_accents($string)));
if ($css_mode) {
$digits = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
if (is_numeric(substr($slug, 0, 1))) {
$slug = $digits[substr($slug, 0, 1)] . substr($slug, 1);
}
}
return $slug;
} | [
"public",
"static",
"function",
"slugify",
"(",
"$",
"string",
",",
"$",
"separator",
"=",
"'-'",
",",
"$",
"css_mode",
"=",
"false",
")",
"{",
"// Compatibility with 1.0.* parameter ordering for semver",
"if",
"(",
"$",
"separator",
"===",
"true",
"||",
"$",
... | Converts any accent characters to their equivalent normal characters
and converts any other non-alphanumeric characters to dashes, then
converts any sequence of two or more dashes to a single dash. This
function generates slugs safe for use as URLs, and if you pass true
as the second parameter, it will create strings safe for use as CSS
classes or IDs.
@param string $string A string to convert to a slug
@param string $separator The string to separate words with
@param boolean $css_mode Whether or not to generate strings safe for
CSS classes/IDs (Default to false)
@return string | [
"Converts",
"any",
"accent",
"characters",
"to",
"their",
"equivalent",
"normal",
"characters",
"and",
"converts",
"any",
"other",
"non",
"-",
"alphanumeric",
"characters",
"to",
"dashes",
"then",
"converts",
"any",
"sequence",
"of",
"two",
"or",
"more",
"dashes... | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L587-L612 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.size_format | public static function size_format($bytes, $decimals = 0)
{
$bytes = floatval($bytes);
if ($bytes < 1024) {
return $bytes . ' B';
} elseif ($bytes < pow(1024, 2)) {
return number_format($bytes / 1024, $decimals, '.', '') . ' KiB';
} elseif ($bytes < pow(1024, 3)) {
return number_format($bytes / pow(1024, 2), $decimals, '.', '') . ' MiB';
} elseif ($bytes < pow(1024, 4)) {
return number_format($bytes / pow(1024, 3), $decimals, '.', '') . ' GiB';
} elseif ($bytes < pow(1024, 5)) {
return number_format($bytes / pow(1024, 4), $decimals, '.', '') . ' TiB';
} elseif ($bytes < pow(1024, 6)) {
return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PiB';
} else {
return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PiB';
}
} | php | public static function size_format($bytes, $decimals = 0)
{
$bytes = floatval($bytes);
if ($bytes < 1024) {
return $bytes . ' B';
} elseif ($bytes < pow(1024, 2)) {
return number_format($bytes / 1024, $decimals, '.', '') . ' KiB';
} elseif ($bytes < pow(1024, 3)) {
return number_format($bytes / pow(1024, 2), $decimals, '.', '') . ' MiB';
} elseif ($bytes < pow(1024, 4)) {
return number_format($bytes / pow(1024, 3), $decimals, '.', '') . ' GiB';
} elseif ($bytes < pow(1024, 5)) {
return number_format($bytes / pow(1024, 4), $decimals, '.', '') . ' TiB';
} elseif ($bytes < pow(1024, 6)) {
return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PiB';
} else {
return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PiB';
}
} | [
"public",
"static",
"function",
"size_format",
"(",
"$",
"bytes",
",",
"$",
"decimals",
"=",
"0",
")",
"{",
"$",
"bytes",
"=",
"floatval",
"(",
"$",
"bytes",
")",
";",
"if",
"(",
"$",
"bytes",
"<",
"1024",
")",
"{",
"return",
"$",
"bytes",
".",
"... | Nice formatting for computer sizes (Bytes).
@param integer $bytes The number in bytes to format
@param integer $decimals The number of decimal points to include
@return string | [
"Nice",
"formatting",
"for",
"computer",
"sizes",
"(",
"Bytes",
")",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L672-L691 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.maybe_unserialize | public static function maybe_unserialize($data)
{
// If it isn't a string, it isn't serialized
if (!is_string($data)) {
return $data;
}
$data = trim($data);
// Is it the serialized NULL value?
if ($data === 'N;') {
return null;
}
$length = strlen($data);
// Check some basic requirements of all serialized strings
if ($length < 4 || $data[1] !== ':' || ($data[$length - 1] !== ';' && $data[$length - 1] !== '}')) {
return $data;
}
// $data is the serialized false value
if ($data === 'b:0;') {
return false;
}
// Don't attempt to unserialize data that isn't serialized
$uns = @unserialize($data);
// Data failed to unserialize?
if ($uns === false) {
$uns = @unserialize(self::fix_broken_serialization($data));
if ($uns === false) {
return $data;
} else {
return $uns;
}
} else {
return $uns;
}
} | php | public static function maybe_unserialize($data)
{
// If it isn't a string, it isn't serialized
if (!is_string($data)) {
return $data;
}
$data = trim($data);
// Is it the serialized NULL value?
if ($data === 'N;') {
return null;
}
$length = strlen($data);
// Check some basic requirements of all serialized strings
if ($length < 4 || $data[1] !== ':' || ($data[$length - 1] !== ';' && $data[$length - 1] !== '}')) {
return $data;
}
// $data is the serialized false value
if ($data === 'b:0;') {
return false;
}
// Don't attempt to unserialize data that isn't serialized
$uns = @unserialize($data);
// Data failed to unserialize?
if ($uns === false) {
$uns = @unserialize(self::fix_broken_serialization($data));
if ($uns === false) {
return $data;
} else {
return $uns;
}
} else {
return $uns;
}
} | [
"public",
"static",
"function",
"maybe_unserialize",
"(",
"$",
"data",
")",
"{",
"// If it isn't a string, it isn't serialized",
"if",
"(",
"!",
"is_string",
"(",
"$",
"data",
")",
")",
"{",
"return",
"$",
"data",
";",
"}",
"$",
"data",
"=",
"trim",
"(",
"... | Unserialize value only if it is serialized.
@param string $data A variable that may or may not be serialized
@return mixed | [
"Unserialize",
"value",
"only",
"if",
"it",
"is",
"serialized",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L714-L755 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.is_serialized | public static function is_serialized($data)
{
// If it isn't a string, it isn't serialized
if (!is_string($data)) {
return false;
}
$data = trim($data);
// Is it the serialized NULL value?
if ($data === 'N;') {
return true;
} elseif ($data === 'b:0;' || $data === 'b:1;') {
// Is it a serialized boolean?
return true;
}
$length = strlen($data);
// Check some basic requirements of all serialized strings
if ($length < 4 || $data[1] !== ':' || ($data[$length - 1] !== ';' && $data[$length - 1] !== '}')) {
return false;
}
return @unserialize($data) !== false;
} | php | public static function is_serialized($data)
{
// If it isn't a string, it isn't serialized
if (!is_string($data)) {
return false;
}
$data = trim($data);
// Is it the serialized NULL value?
if ($data === 'N;') {
return true;
} elseif ($data === 'b:0;' || $data === 'b:1;') {
// Is it a serialized boolean?
return true;
}
$length = strlen($data);
// Check some basic requirements of all serialized strings
if ($length < 4 || $data[1] !== ':' || ($data[$length - 1] !== ';' && $data[$length - 1] !== '}')) {
return false;
}
return @unserialize($data) !== false;
} | [
"public",
"static",
"function",
"is_serialized",
"(",
"$",
"data",
")",
"{",
"// If it isn't a string, it isn't serialized",
"if",
"(",
"!",
"is_string",
"(",
"$",
"data",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"data",
"=",
"trim",
"(",
"$",
"dat... | Check value to find if it was serialized.
If $data is not an string, then returned value will always be false.
Serialized data is always a string.
@param mixed $data Value to check to see if was serialized
@return boolean | [
"Check",
"value",
"to",
"find",
"if",
"it",
"was",
"serialized",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L766-L791 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.fix_broken_serialization | public static function fix_broken_serialization($brokenSerializedData)
{
$fixdSerializedData = preg_replace_callback('!s:(\d+):"(.*?)";!', function ($matches) {
$snip = $matches[2];
return 's:' . strlen($snip) . ':"' . $snip . '";';
}, $brokenSerializedData);
return $fixdSerializedData;
} | php | public static function fix_broken_serialization($brokenSerializedData)
{
$fixdSerializedData = preg_replace_callback('!s:(\d+):"(.*?)";!', function ($matches) {
$snip = $matches[2];
return 's:' . strlen($snip) . ':"' . $snip . '";';
}, $brokenSerializedData);
return $fixdSerializedData;
} | [
"public",
"static",
"function",
"fix_broken_serialization",
"(",
"$",
"brokenSerializedData",
")",
"{",
"$",
"fixdSerializedData",
"=",
"preg_replace_callback",
"(",
"'!s:(\\d+):\"(.*?)\";!'",
",",
"function",
"(",
"$",
"matches",
")",
"{",
"$",
"snip",
"=",
"$",
... | Unserializes partially-corrupted arrays that occur sometimes. Addresses
specifically the `unserialize(): Error at offset xxx of yyy bytes` error.
NOTE: This error can *frequently* occur with mismatched character sets
and higher-than-ASCII characters.
Contributed by Theodore R. Smith of PHP Experts, Inc. <http://www.phpexperts.pro/>
@param string $brokenSerializedData
@return string | [
"Unserializes",
"partially",
"-",
"corrupted",
"arrays",
"that",
"occur",
"sometimes",
".",
"Addresses",
"specifically",
"the",
"unserialize",
"()",
":",
"Error",
"at",
"offset",
"xxx",
"of",
"yyy",
"bytes",
"error",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L805-L813 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.is_https | public static function is_https($trust_proxy_headers = false)
{
// Check standard HTTPS header
if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
}
// Check proxy headers if allowed
return $trust_proxy_headers && isset($_SERVER['X-FORWARDED-PROTO']) && $_SERVER['X-FORWARDED-PROTO'] == 'https';
// Default to not SSL
return false;
} | php | public static function is_https($trust_proxy_headers = false)
{
// Check standard HTTPS header
if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
}
// Check proxy headers if allowed
return $trust_proxy_headers && isset($_SERVER['X-FORWARDED-PROTO']) && $_SERVER['X-FORWARDED-PROTO'] == 'https';
// Default to not SSL
return false;
} | [
"public",
"static",
"function",
"is_https",
"(",
"$",
"trust_proxy_headers",
"=",
"false",
")",
"{",
"// Check standard HTTPS header",
"if",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",... | Checks to see if the page is being server over SSL or not
@return boolean | [
"Checks",
"to",
"see",
"if",
"the",
"page",
"is",
"being",
"server",
"over",
"SSL",
"or",
"not"
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L820-L832 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.add_query_arg | public static function add_query_arg($newKey, $newValue = null, $uri = null)
{
// Was an associative array of key => value pairs passed?
if (is_array($newKey)) {
$newParams = $newKey;
// Was the URL passed as an argument?
if (!is_null($newValue)) {
$uri = $newValue;
} elseif (!is_null($uri)) {
$uri = $uri;
} else {
$uri = self::array_get($_SERVER['REQUEST_URI'], '');
}
} else {
$newParams = array($newKey => $newValue);
// Was the URL passed as an argument?
$uri = is_null($uri) ? self::array_get($_SERVER['REQUEST_URI'], '') : $uri;
}
// Parse the URI into it's components
$puri = parse_url($uri);
if (isset($puri['query'])) {
parse_str($puri['query'], $queryParams);
$queryParams = array_merge($queryParams, $newParams);
} elseif (isset($puri['path']) && strstr($puri['path'], '=') !== false) {
$puri['query'] = $puri['path'];
unset($puri['path']);
parse_str($puri['query'], $queryParams);
$queryParams = array_merge($queryParams, $newParams);
} else {
$queryParams = $newParams;
}
// Strip out any query params that are set to false.
// Properly handle valueless parameters.
foreach ($queryParams as $param => $value) {
if ($value === false) {
unset($queryParams[$param]);
} elseif ($value === null) {
$queryParams[$param] = '';
}
}
// Re-construct the query string
$puri['query'] = http_build_query($queryParams);
// Strip = from valueless parameters.
$puri['query'] = preg_replace('/=(?=&|$)/', '', $puri['query']);
// Re-construct the entire URL
$nuri = self::http_build_url($puri);
// Make the URI consistent with our input
if ($nuri[0] === '/' && strstr($uri, '/') === false) {
$nuri = substr($nuri, 1);
}
if ($nuri[0] === '?' && strstr($uri, '?') === false) {
$nuri = substr($nuri, 1);
}
return rtrim($nuri, '?');
} | php | public static function add_query_arg($newKey, $newValue = null, $uri = null)
{
// Was an associative array of key => value pairs passed?
if (is_array($newKey)) {
$newParams = $newKey;
// Was the URL passed as an argument?
if (!is_null($newValue)) {
$uri = $newValue;
} elseif (!is_null($uri)) {
$uri = $uri;
} else {
$uri = self::array_get($_SERVER['REQUEST_URI'], '');
}
} else {
$newParams = array($newKey => $newValue);
// Was the URL passed as an argument?
$uri = is_null($uri) ? self::array_get($_SERVER['REQUEST_URI'], '') : $uri;
}
// Parse the URI into it's components
$puri = parse_url($uri);
if (isset($puri['query'])) {
parse_str($puri['query'], $queryParams);
$queryParams = array_merge($queryParams, $newParams);
} elseif (isset($puri['path']) && strstr($puri['path'], '=') !== false) {
$puri['query'] = $puri['path'];
unset($puri['path']);
parse_str($puri['query'], $queryParams);
$queryParams = array_merge($queryParams, $newParams);
} else {
$queryParams = $newParams;
}
// Strip out any query params that are set to false.
// Properly handle valueless parameters.
foreach ($queryParams as $param => $value) {
if ($value === false) {
unset($queryParams[$param]);
} elseif ($value === null) {
$queryParams[$param] = '';
}
}
// Re-construct the query string
$puri['query'] = http_build_query($queryParams);
// Strip = from valueless parameters.
$puri['query'] = preg_replace('/=(?=&|$)/', '', $puri['query']);
// Re-construct the entire URL
$nuri = self::http_build_url($puri);
// Make the URI consistent with our input
if ($nuri[0] === '/' && strstr($uri, '/') === false) {
$nuri = substr($nuri, 1);
}
if ($nuri[0] === '?' && strstr($uri, '?') === false) {
$nuri = substr($nuri, 1);
}
return rtrim($nuri, '?');
} | [
"public",
"static",
"function",
"add_query_arg",
"(",
"$",
"newKey",
",",
"$",
"newValue",
"=",
"null",
",",
"$",
"uri",
"=",
"null",
")",
"{",
"// Was an associative array of key => value pairs passed?",
"if",
"(",
"is_array",
"(",
"$",
"newKey",
")",
")",
"{... | Add or remove query arguments to the URL.
@param mixed $newKey Either newkey or an associative array
@param mixed $newValue Either newvalue or oldquery or uri
@param mixed $uri URI or URL to append the queru/queries to.
@return string | [
"Add",
"or",
"remove",
"query",
"arguments",
"to",
"the",
"URL",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L842-L908 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.remove_query_arg | public static function remove_query_arg($keys, $uri = null)
{
if (is_array($keys)) {
return self::add_query_arg(array_combine($keys, array_fill(0, count($keys), false)), $uri);
}
return self::add_query_arg(array($keys => false), $uri);
} | php | public static function remove_query_arg($keys, $uri = null)
{
if (is_array($keys)) {
return self::add_query_arg(array_combine($keys, array_fill(0, count($keys), false)), $uri);
}
return self::add_query_arg(array($keys => false), $uri);
} | [
"public",
"static",
"function",
"remove_query_arg",
"(",
"$",
"keys",
",",
"$",
"uri",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"keys",
")",
")",
"{",
"return",
"self",
"::",
"add_query_arg",
"(",
"array_combine",
"(",
"$",
"keys",
",",
... | Removes an item or list from the query string.
@param string|array $keys Query key or keys to remove.
@param bool $uri When false uses the $_SERVER value
@return string | [
"Removes",
"an",
"item",
"or",
"list",
"from",
"the",
"query",
"string",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L917-L924 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.http_build_url | public static function http_build_url($url, $parts = array(), $flags = self::HTTP_URL_REPLACE, &$new_url = array())
{
is_array($url) || $url = parse_url($url);
is_array($parts) || $parts = parse_url($parts);
isset($url['query']) && is_string($url['query']) || $url['query'] = null;
isset($parts['query']) && is_string($parts['query']) || $parts['query'] = null;
$keys = array('user', 'pass', 'port', 'path', 'query', 'fragment');
// HTTP_URL_STRIP_ALL and HTTP_URL_STRIP_AUTH cover several other flags.
if ($flags & self::HTTP_URL_STRIP_ALL) {
$flags |= self::HTTP_URL_STRIP_USER | self::HTTP_URL_STRIP_PASS
| self::HTTP_URL_STRIP_PORT | self::HTTP_URL_STRIP_PATH
| self::HTTP_URL_STRIP_QUERY | self::HTTP_URL_STRIP_FRAGMENT;
} elseif ($flags & self::HTTP_URL_STRIP_AUTH) {
$flags |= self::HTTP_URL_STRIP_USER | self::HTTP_URL_STRIP_PASS;
}
// Schema and host are alwasy replaced
foreach (array('scheme', 'host') as $part) {
if (isset($parts[$part])) {
$url[$part] = $parts[$part];
}
}
if ($flags & self::HTTP_URL_REPLACE) {
foreach ($keys as $key) {
if (isset($parts[$key])) {
$url[$key] = $parts[$key];
}
}
} else {
if (isset($parts['path']) && ($flags & self::HTTP_URL_JOIN_PATH)) {
if (isset($url['path']) && substr($parts['path'], 0, 1) !== '/') {
$url['path'] = rtrim(
str_replace(basename($url['path']), '', $url['path']),
'/'
) . '/' . ltrim($parts['path'], '/');
} else {
$url['path'] = $parts['path'];
}
}
if (isset($parts['query']) && ($flags & self::HTTP_URL_JOIN_QUERY)) {
if (isset($url['query'])) {
parse_str($url['query'], $url_query);
parse_str($parts['query'], $parts_query);
$url['query'] = http_build_query(
array_replace_recursive(
$url_query,
$parts_query
)
);
} else {
$url['query'] = $parts['query'];
}
}
}
if (isset($url['path']) && substr($url['path'], 0, 1) !== '/') {
$url['path'] = '/' . $url['path'];
}
foreach ($keys as $key) {
$strip = 'HTTP_URL_STRIP_' . strtoupper($key);
if ($flags & constant('utilphp\\util::' . $strip)) {
unset($url[$key]);
}
}
$parsed_string = '';
if (isset($url['scheme'])) {
$parsed_string .= $url['scheme'] . '://';
}
if (isset($url['user'])) {
$parsed_string .= $url['user'];
if (isset($url['pass'])) {
$parsed_string .= ':' . $url['pass'];
}
$parsed_string .= '@';
}
if (isset($url['host'])) {
$parsed_string .= $url['host'];
}
if (isset($url['port'])) {
$parsed_string .= ':' . $url['port'];
}
if (!empty($url['path'])) {
$parsed_string .= $url['path'];
} else {
$parsed_string .= '/';
}
if (isset($url['query'])) {
$parsed_string .= '?' . $url['query'];
}
if (isset($url['fragment'])) {
$parsed_string .= '#' . $url['fragment'];
}
$new_url = $url;
return $parsed_string;
} | php | public static function http_build_url($url, $parts = array(), $flags = self::HTTP_URL_REPLACE, &$new_url = array())
{
is_array($url) || $url = parse_url($url);
is_array($parts) || $parts = parse_url($parts);
isset($url['query']) && is_string($url['query']) || $url['query'] = null;
isset($parts['query']) && is_string($parts['query']) || $parts['query'] = null;
$keys = array('user', 'pass', 'port', 'path', 'query', 'fragment');
// HTTP_URL_STRIP_ALL and HTTP_URL_STRIP_AUTH cover several other flags.
if ($flags & self::HTTP_URL_STRIP_ALL) {
$flags |= self::HTTP_URL_STRIP_USER | self::HTTP_URL_STRIP_PASS
| self::HTTP_URL_STRIP_PORT | self::HTTP_URL_STRIP_PATH
| self::HTTP_URL_STRIP_QUERY | self::HTTP_URL_STRIP_FRAGMENT;
} elseif ($flags & self::HTTP_URL_STRIP_AUTH) {
$flags |= self::HTTP_URL_STRIP_USER | self::HTTP_URL_STRIP_PASS;
}
// Schema and host are alwasy replaced
foreach (array('scheme', 'host') as $part) {
if (isset($parts[$part])) {
$url[$part] = $parts[$part];
}
}
if ($flags & self::HTTP_URL_REPLACE) {
foreach ($keys as $key) {
if (isset($parts[$key])) {
$url[$key] = $parts[$key];
}
}
} else {
if (isset($parts['path']) && ($flags & self::HTTP_URL_JOIN_PATH)) {
if (isset($url['path']) && substr($parts['path'], 0, 1) !== '/') {
$url['path'] = rtrim(
str_replace(basename($url['path']), '', $url['path']),
'/'
) . '/' . ltrim($parts['path'], '/');
} else {
$url['path'] = $parts['path'];
}
}
if (isset($parts['query']) && ($flags & self::HTTP_URL_JOIN_QUERY)) {
if (isset($url['query'])) {
parse_str($url['query'], $url_query);
parse_str($parts['query'], $parts_query);
$url['query'] = http_build_query(
array_replace_recursive(
$url_query,
$parts_query
)
);
} else {
$url['query'] = $parts['query'];
}
}
}
if (isset($url['path']) && substr($url['path'], 0, 1) !== '/') {
$url['path'] = '/' . $url['path'];
}
foreach ($keys as $key) {
$strip = 'HTTP_URL_STRIP_' . strtoupper($key);
if ($flags & constant('utilphp\\util::' . $strip)) {
unset($url[$key]);
}
}
$parsed_string = '';
if (isset($url['scheme'])) {
$parsed_string .= $url['scheme'] . '://';
}
if (isset($url['user'])) {
$parsed_string .= $url['user'];
if (isset($url['pass'])) {
$parsed_string .= ':' . $url['pass'];
}
$parsed_string .= '@';
}
if (isset($url['host'])) {
$parsed_string .= $url['host'];
}
if (isset($url['port'])) {
$parsed_string .= ':' . $url['port'];
}
if (!empty($url['path'])) {
$parsed_string .= $url['path'];
} else {
$parsed_string .= '/';
}
if (isset($url['query'])) {
$parsed_string .= '?' . $url['query'];
}
if (isset($url['fragment'])) {
$parsed_string .= '#' . $url['fragment'];
}
$new_url = $url;
return $parsed_string;
} | [
"public",
"static",
"function",
"http_build_url",
"(",
"$",
"url",
",",
"$",
"parts",
"=",
"array",
"(",
")",
",",
"$",
"flags",
"=",
"self",
"::",
"HTTP_URL_REPLACE",
",",
"&",
"$",
"new_url",
"=",
"array",
"(",
")",
")",
"{",
"is_array",
"(",
"$",
... | Build a URL.
The parts of the second URL will be merged into the first according to
the flags argument.
@author Jake Smith <theman@jakeasmith.com>
@see https://github.com/jakeasmith/http_build_url/
@param mixed $url (part(s) of) an URL in form of a string or
associative array like parse_url() returns
@param mixed $parts same as the first argument
@param int $flags a bitmask of binary or'ed HTTP_URL constants;
HTTP_URL_REPLACE is the default
@param array $new_url if set, it will be filled with the parts of the
composed url like parse_url() would return
@return string | [
"Build",
"a",
"URL",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L944-L1057 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.str_to_bool | public static function str_to_bool($string, $default = false)
{
$yes_words = 'affirmative|all right|aye|indubitably|most assuredly|ok|of course|okay|sure thing|y|yes+|yea|yep|sure|yeah|true|t|on|1|oui|vrai';
$no_words = 'no*|no way|nope|nah|na|never|absolutely not|by no means|negative|never ever|false|f|off|0|non|faux';
if (preg_match('/^(' . $yes_words . ')$/i', $string)) {
return true;
} elseif (preg_match('/^(' . $no_words . ')$/i', $string)) {
return false;
}
return $default;
} | php | public static function str_to_bool($string, $default = false)
{
$yes_words = 'affirmative|all right|aye|indubitably|most assuredly|ok|of course|okay|sure thing|y|yes+|yea|yep|sure|yeah|true|t|on|1|oui|vrai';
$no_words = 'no*|no way|nope|nah|na|never|absolutely not|by no means|negative|never ever|false|f|off|0|non|faux';
if (preg_match('/^(' . $yes_words . ')$/i', $string)) {
return true;
} elseif (preg_match('/^(' . $no_words . ')$/i', $string)) {
return false;
}
return $default;
} | [
"public",
"static",
"function",
"str_to_bool",
"(",
"$",
"string",
",",
"$",
"default",
"=",
"false",
")",
"{",
"$",
"yes_words",
"=",
"'affirmative|all right|aye|indubitably|most assuredly|ok|of course|okay|sure thing|y|yes+|yea|yep|sure|yeah|true|t|on|1|oui|vrai'",
";",
"$",
... | Converts many english words that equate to true or false to boolean.
Supports 'y', 'n', 'yes', 'no' and a few other variations.
@param string $string The string to convert to boolean
@param bool $default The value to return if we can't match any
yes/no words
@return boolean | [
"Converts",
"many",
"english",
"words",
"that",
"equate",
"to",
"true",
"or",
"false",
"to",
"boolean",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1069-L1081 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.rmdir | public static function rmdir($dir, $traverseSymlinks = false)
{
if (!file_exists($dir)) {
return true;
} elseif (!is_dir($dir)) {
throw new \RuntimeException('Given path is not a directory');
}
if (!is_link($dir) || $traverseSymlinks) {
foreach (scandir($dir) as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$currentPath = $dir . '/' . $file;
if (is_dir($currentPath)) {
self::rmdir($currentPath, $traverseSymlinks);
} elseif (!unlink($currentPath)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to delete ' . $currentPath);
// @codeCoverageIgnoreEnd
}
}
}
// Windows treats removing directory symlinks identically to removing directories.
if (is_link($dir) && !defined('PHP_WINDOWS_VERSION_MAJOR')) {
if (!unlink($dir)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to delete ' . $dir);
// @codeCoverageIgnoreEnd
}
} else {
if (!rmdir($dir)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to delete ' . $dir);
// @codeCoverageIgnoreEnd
}
}
return true;
} | php | public static function rmdir($dir, $traverseSymlinks = false)
{
if (!file_exists($dir)) {
return true;
} elseif (!is_dir($dir)) {
throw new \RuntimeException('Given path is not a directory');
}
if (!is_link($dir) || $traverseSymlinks) {
foreach (scandir($dir) as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$currentPath = $dir . '/' . $file;
if (is_dir($currentPath)) {
self::rmdir($currentPath, $traverseSymlinks);
} elseif (!unlink($currentPath)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to delete ' . $currentPath);
// @codeCoverageIgnoreEnd
}
}
}
// Windows treats removing directory symlinks identically to removing directories.
if (is_link($dir) && !defined('PHP_WINDOWS_VERSION_MAJOR')) {
if (!unlink($dir)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to delete ' . $dir);
// @codeCoverageIgnoreEnd
}
} else {
if (!rmdir($dir)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to delete ' . $dir);
// @codeCoverageIgnoreEnd
}
}
return true;
} | [
"public",
"static",
"function",
"rmdir",
"(",
"$",
"dir",
",",
"$",
"traverseSymlinks",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"dir",
")",
")",
"{",
"return",
"true",
";",
"}",
"elseif",
"(",
"!",
"is_dir",
"(",
"$",
"dir"... | Removes a directory (and its contents) recursively.
Contributed by Askar (ARACOOL) <https://github.com/ARACOOOL>
@param string $dir The directory to be deleted recursively
@param bool $traverseSymlinks Delete contents of symlinks recursively
@return bool
@throws \RuntimeException | [
"Removes",
"a",
"directory",
"(",
"and",
"its",
"contents",
")",
"recursively",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1153-L1195 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.htmlentities | public static function htmlentities($string, $preserve_encoded_entities = false)
{
if ($preserve_encoded_entities) {
// @codeCoverageIgnoreStart
if (defined('HHVM_VERSION')) {
$translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
} else {
$translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES, self::mbInternalEncoding());
}
// @codeCoverageIgnoreEnd
$translation_table[chr(38)] = '&';
return preg_replace('/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&', strtr($string, $translation_table));
}
return htmlentities($string, ENT_QUOTES, self::mbInternalEncoding());
} | php | public static function htmlentities($string, $preserve_encoded_entities = false)
{
if ($preserve_encoded_entities) {
// @codeCoverageIgnoreStart
if (defined('HHVM_VERSION')) {
$translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
} else {
$translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES, self::mbInternalEncoding());
}
// @codeCoverageIgnoreEnd
$translation_table[chr(38)] = '&';
return preg_replace('/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&', strtr($string, $translation_table));
}
return htmlentities($string, ENT_QUOTES, self::mbInternalEncoding());
} | [
"public",
"static",
"function",
"htmlentities",
"(",
"$",
"string",
",",
"$",
"preserve_encoded_entities",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"preserve_encoded_entities",
")",
"{",
"// @codeCoverageIgnoreStart",
"if",
"(",
"defined",
"(",
"'HHVM_VERSION'",
")... | Convert entities, while preserving already-encoded entities.
@param string $string The text to be converted
@return string | [
"Convert",
"entities",
"while",
"preserving",
"already",
"-",
"encoded",
"entities",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1203-L1219 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.downcode | public static function downcode($text, $language = '')
{
self::initLanguageMap($language);
if (self::seems_utf8($text)) {
if (preg_match_all(self::$regex, $text, $matches)) {
for ($i = 0; $i < count($matches[0]); $i++) {
$char = $matches[0][$i];
if (isset(self::$map[$char])) {
$text = str_replace($char, self::$map[$char], $text);
}
}
}
} else {
// Not a UTF-8 string so we assume its ISO-8859-1
$search = "\x80\x83\x8a\x8e\x9a\x9e\x9f\xa2\xa5\xb5\xc0\xc1\xc2\xc3\xc4\xc5\xc7\xc8\xc9\xca\xcb\xcc\xcd";
$search .= "\xce\xcf\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9";
$search .= "\xea\xeb\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xff";
$text = strtr($text, $search, 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy');
// These latin characters should be represented by two characters so
// we can't use strtr
$complexSearch = array("\x8c", "\x9c", "\xc6", "\xd0", "\xde", "\xdf", "\xe6", "\xf0", "\xfe");
$complexReplace = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
$text = str_replace($complexSearch, $complexReplace, $text);
}
return $text;
} | php | public static function downcode($text, $language = '')
{
self::initLanguageMap($language);
if (self::seems_utf8($text)) {
if (preg_match_all(self::$regex, $text, $matches)) {
for ($i = 0; $i < count($matches[0]); $i++) {
$char = $matches[0][$i];
if (isset(self::$map[$char])) {
$text = str_replace($char, self::$map[$char], $text);
}
}
}
} else {
// Not a UTF-8 string so we assume its ISO-8859-1
$search = "\x80\x83\x8a\x8e\x9a\x9e\x9f\xa2\xa5\xb5\xc0\xc1\xc2\xc3\xc4\xc5\xc7\xc8\xc9\xca\xcb\xcc\xcd";
$search .= "\xce\xcf\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9";
$search .= "\xea\xeb\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xff";
$text = strtr($text, $search, 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy');
// These latin characters should be represented by two characters so
// we can't use strtr
$complexSearch = array("\x8c", "\x9c", "\xc6", "\xd0", "\xde", "\xdf", "\xe6", "\xf0", "\xfe");
$complexReplace = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
$text = str_replace($complexSearch, $complexReplace, $text);
}
return $text;
} | [
"public",
"static",
"function",
"downcode",
"(",
"$",
"text",
",",
"$",
"language",
"=",
"''",
")",
"{",
"self",
"::",
"initLanguageMap",
"(",
"$",
"language",
")",
";",
"if",
"(",
"self",
"::",
"seems_utf8",
"(",
"$",
"text",
")",
")",
"{",
"if",
... | Transliterates characters to their ASCII equivalents.
Part of the URLify.php Project <https://github.com/jbroadway/urlify/>
@see https://github.com/jbroadway/urlify/blob/master/URLify.php
@param string $text Text that might have not-ASCII characters
@param string $language Specifies a priority for a specific language.
@return string Filtered string with replaced "nice" characters | [
"Transliterates",
"characters",
"to",
"their",
"ASCII",
"equivalents",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1258-L1286 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.remove_accents | public static function remove_accents($string, $language = '')
{
if (!preg_match('/[\x80-\xff]/', $string)) {
return $string;
}
return self::downcode($string, $language);
} | php | public static function remove_accents($string, $language = '')
{
if (!preg_match('/[\x80-\xff]/', $string)) {
return $string;
}
return self::downcode($string, $language);
} | [
"public",
"static",
"function",
"remove_accents",
"(",
"$",
"string",
",",
"$",
"language",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/[\\x80-\\xff]/'",
",",
"$",
"string",
")",
")",
"{",
"return",
"$",
"string",
";",
"}",
"return",
"se... | Converts all accent characters to ASCII characters.
If there are no accent characters, then the string given is just
returned.
@param string $string Text that might have accent characters
@param string $language Specifies a priority for a specific language.
@return string Filtered string with replaced "nice" characters | [
"Converts",
"all",
"accent",
"characters",
"to",
"ASCII",
"characters",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1298-L1305 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.sanitize_string | public static function sanitize_string($string)
{
$string = self::remove_accents($string);
$string = strtolower($string);
$string = preg_replace('/[^a-zA-Z 0-9]+/', '', $string);
$string = self::strip_space($string);
return $string;
} | php | public static function sanitize_string($string)
{
$string = self::remove_accents($string);
$string = strtolower($string);
$string = preg_replace('/[^a-zA-Z 0-9]+/', '', $string);
$string = self::strip_space($string);
return $string;
} | [
"public",
"static",
"function",
"sanitize_string",
"(",
"$",
"string",
")",
"{",
"$",
"string",
"=",
"self",
"::",
"remove_accents",
"(",
"$",
"string",
")",
";",
"$",
"string",
"=",
"strtolower",
"(",
"$",
"string",
")",
";",
"$",
"string",
"=",
"preg... | Sanitize a string by performing the following operation :
- Remove accents
- Lower the string
- Remove punctuation characters
- Strip whitespaces
@param string $string the string to sanitize
@return string | [
"Sanitize",
"a",
"string",
"by",
"performing",
"the",
"following",
"operation",
":",
"-",
"Remove",
"accents",
"-",
"Lower",
"the",
"string",
"-",
"Remove",
"punctuation",
"characters",
"-",
"Strip",
"whitespaces"
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1328-L1336 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.human_time_diff | public static function human_time_diff($from, $to = '', $as_text = false, $suffix = ' ago')
{
if ($to == '') {
$to = time();
}
$from = new \DateTime(date('Y-m-d H:i:s', $from));
$to = new \DateTime(date('Y-m-d H:i:s', $to));
$diff = $from->diff($to);
if ($diff->y > 1) {
$text = $diff->y . ' years';
} elseif ($diff->y == 1) {
$text = '1 year';
} elseif ($diff->m > 1) {
$text = $diff->m . ' months';
} elseif ($diff->m == 1) {
$text = '1 month';
} elseif ($diff->d > 7) {
$text = ceil($diff->d / 7) . ' weeks';
} elseif ($diff->d == 7) {
$text = '1 week';
} elseif ($diff->d > 1) {
$text = $diff->d . ' days';
} elseif ($diff->d == 1) {
$text = '1 day';
} elseif ($diff->h > 1) {
$text = $diff->h . ' hours';
} elseif ($diff->h == 1) {
$text = ' 1 hour';
} elseif ($diff->i > 1) {
$text = $diff->i . ' minutes';
} elseif ($diff->i == 1) {
$text = '1 minute';
} elseif ($diff->s > 1) {
$text = $diff->s . ' seconds';
} else {
$text = '1 second';
}
if ($as_text) {
$text = explode(' ', $text, 2);
$text = self::number_to_word($text[0]) . ' ' . $text[1];
}
return trim($text) . $suffix;
} | php | public static function human_time_diff($from, $to = '', $as_text = false, $suffix = ' ago')
{
if ($to == '') {
$to = time();
}
$from = new \DateTime(date('Y-m-d H:i:s', $from));
$to = new \DateTime(date('Y-m-d H:i:s', $to));
$diff = $from->diff($to);
if ($diff->y > 1) {
$text = $diff->y . ' years';
} elseif ($diff->y == 1) {
$text = '1 year';
} elseif ($diff->m > 1) {
$text = $diff->m . ' months';
} elseif ($diff->m == 1) {
$text = '1 month';
} elseif ($diff->d > 7) {
$text = ceil($diff->d / 7) . ' weeks';
} elseif ($diff->d == 7) {
$text = '1 week';
} elseif ($diff->d > 1) {
$text = $diff->d . ' days';
} elseif ($diff->d == 1) {
$text = '1 day';
} elseif ($diff->h > 1) {
$text = $diff->h . ' hours';
} elseif ($diff->h == 1) {
$text = ' 1 hour';
} elseif ($diff->i > 1) {
$text = $diff->i . ' minutes';
} elseif ($diff->i == 1) {
$text = '1 minute';
} elseif ($diff->s > 1) {
$text = $diff->s . ' seconds';
} else {
$text = '1 second';
}
if ($as_text) {
$text = explode(' ', $text, 2);
$text = self::number_to_word($text[0]) . ' ' . $text[1];
}
return trim($text) . $suffix;
} | [
"public",
"static",
"function",
"human_time_diff",
"(",
"$",
"from",
",",
"$",
"to",
"=",
"''",
",",
"$",
"as_text",
"=",
"false",
",",
"$",
"suffix",
"=",
"' ago'",
")",
"{",
"if",
"(",
"$",
"to",
"==",
"''",
")",
"{",
"$",
"to",
"=",
"time",
... | Converts a unix timestamp to a relative time string, such as "3 days ago"
or "2 weeks ago".
@param int $from The date to use as a starting point
@param int $to The date to compare to, defaults to now
@param string $suffix The string to add to the end, defaults to " ago"
@return string | [
"Converts",
"a",
"unix",
"timestamp",
"to",
"a",
"relative",
"time",
"string",
"such",
"as",
"3",
"days",
"ago",
"or",
"2",
"weeks",
"ago",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1359-L1405 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.number_to_word | public static function number_to_word($number)
{
$number = (string) $number;
if (strpos($number, '.') !== false) {
list($number, $decimal) = explode('.', $number);
} else {
$decimal = false;
}
$output = '';
if ($number[0] == '-') {
$output = 'negative ';
$number = ltrim($number, '-');
} elseif ($number[0] == '+') {
$output = 'positive ';
$number = ltrim($number, '+');
}
if ($number[0] == '0') {
$output .= 'zero';
} else {
$length = 19;
$number = str_pad($number, 60, '0', STR_PAD_LEFT);
$group = rtrim(chunk_split($number, 3, ' '), ' ');
$groups = explode(' ', $group);
$groups2 = array();
foreach ($groups as $group) {
$group[1] = isset($group[1]) ? $group[1] : null;
$group[2] = isset($group[2]) ? $group[2] : null;
$groups2[] = self::numberToWordThreeDigits($group[0], $group[1], $group[2]);
}
for ($z = 0; $z < count($groups2); $z++) {
if ($groups2[$z] != '') {
$output .= $groups2[$z] . self::numberToWordConvertGroup($length - $z);
$output .= ($z < $length && ! array_search('', array_slice($groups2, $z + 1, -1)) && $groups2[$length] != '' && $groups[$length][0] == '0' ? ' and ' : ', ');
}
}
$output = rtrim($output, ', ');
}
if ($decimal > 0) {
$output .= ' point';
for ($i = 0; $i < strlen($decimal); $i++) {
$output .= ' ' . self::numberToWordConvertDigit($decimal[$i]);
}
}
return $output;
} | php | public static function number_to_word($number)
{
$number = (string) $number;
if (strpos($number, '.') !== false) {
list($number, $decimal) = explode('.', $number);
} else {
$decimal = false;
}
$output = '';
if ($number[0] == '-') {
$output = 'negative ';
$number = ltrim($number, '-');
} elseif ($number[0] == '+') {
$output = 'positive ';
$number = ltrim($number, '+');
}
if ($number[0] == '0') {
$output .= 'zero';
} else {
$length = 19;
$number = str_pad($number, 60, '0', STR_PAD_LEFT);
$group = rtrim(chunk_split($number, 3, ' '), ' ');
$groups = explode(' ', $group);
$groups2 = array();
foreach ($groups as $group) {
$group[1] = isset($group[1]) ? $group[1] : null;
$group[2] = isset($group[2]) ? $group[2] : null;
$groups2[] = self::numberToWordThreeDigits($group[0], $group[1], $group[2]);
}
for ($z = 0; $z < count($groups2); $z++) {
if ($groups2[$z] != '') {
$output .= $groups2[$z] . self::numberToWordConvertGroup($length - $z);
$output .= ($z < $length && ! array_search('', array_slice($groups2, $z + 1, -1)) && $groups2[$length] != '' && $groups[$length][0] == '0' ? ' and ' : ', ');
}
}
$output = rtrim($output, ', ');
}
if ($decimal > 0) {
$output .= ' point';
for ($i = 0; $i < strlen($decimal); $i++) {
$output .= ' ' . self::numberToWordConvertDigit($decimal[$i]);
}
}
return $output;
} | [
"public",
"static",
"function",
"number_to_word",
"(",
"$",
"number",
")",
"{",
"$",
"number",
"=",
"(",
"string",
")",
"$",
"number",
";",
"if",
"(",
"strpos",
"(",
"$",
"number",
",",
"'.'",
")",
"!==",
"false",
")",
"{",
"list",
"(",
"$",
"numbe... | Converts a number into the text equivalent. For example, 456 becomes four
hundred and fifty-six.
Part of the IntToWords Project.
@param int|float $number The number to convert into text
@return string | [
"Converts",
"a",
"number",
"into",
"the",
"text",
"equivalent",
".",
"For",
"example",
"456",
"becomes",
"four",
"hundred",
"and",
"fifty",
"-",
"six",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1416-L1470 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.calculate_percentage | public static function calculate_percentage($numerator, $denominator, $decimals = 2, $dec_point = '.', $thousands_sep = ',')
{
return number_format(($numerator / $denominator) * 100, $decimals, $dec_point, $thousands_sep);
} | php | public static function calculate_percentage($numerator, $denominator, $decimals = 2, $dec_point = '.', $thousands_sep = ',')
{
return number_format(($numerator / $denominator) * 100, $decimals, $dec_point, $thousands_sep);
} | [
"public",
"static",
"function",
"calculate_percentage",
"(",
"$",
"numerator",
",",
"$",
"denominator",
",",
"$",
"decimals",
"=",
"2",
",",
"$",
"dec_point",
"=",
"'.'",
",",
"$",
"thousands_sep",
"=",
"','",
")",
"{",
"return",
"number_format",
"(",
"(",... | Calculates percentage of numerator and denominator.
@param int|float $numerator
@param int|float $denominator
@param int $decimals
@param string $dec_point
@param string $thousands_sep
@return int|float | [
"Calculates",
"percentage",
"of",
"numerator",
"and",
"denominator",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1639-L1642 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.force_download | public static function force_download($filename, $content = false)
{
// @codeCoverageIgnoreStart
if (!headers_sent()) {
// Required for some browsers
if (ini_get('zlib.output_compression')) {
@ini_set('zlib.output_compression', 'Off');
}
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
// Required for certain browsers
header('Cache-Control: private', false);
header('Content-Disposition: attachment; filename="' . basename(str_replace('"', '', $filename)) . '";');
header('Content-Type: application/force-download');
header('Content-Transfer-Encoding: binary');
if ($content) {
header('Content-Length: ' . strlen($content));
}
ob_clean();
flush();
if ($content) {
echo $content;
}
return true;
}
return false;
// @codeCoverageIgnoreEnd
} | php | public static function force_download($filename, $content = false)
{
// @codeCoverageIgnoreStart
if (!headers_sent()) {
// Required for some browsers
if (ini_get('zlib.output_compression')) {
@ini_set('zlib.output_compression', 'Off');
}
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
// Required for certain browsers
header('Cache-Control: private', false);
header('Content-Disposition: attachment; filename="' . basename(str_replace('"', '', $filename)) . '";');
header('Content-Type: application/force-download');
header('Content-Transfer-Encoding: binary');
if ($content) {
header('Content-Length: ' . strlen($content));
}
ob_clean();
flush();
if ($content) {
echo $content;
}
return true;
}
return false;
// @codeCoverageIgnoreEnd
} | [
"public",
"static",
"function",
"force_download",
"(",
"$",
"filename",
",",
"$",
"content",
"=",
"false",
")",
"{",
"// @codeCoverageIgnoreStart",
"if",
"(",
"!",
"headers_sent",
"(",
")",
")",
"{",
"// Required for some browsers",
"if",
"(",
"ini_get",
"(",
... | Transmit headers that force a browser to display the download file
dialog. Cross browser compatible. Only fires if headers have not
already been sent.
@param string $filename The name of the filename to display to
browsers
@param string $content The content to output for the download.
If you don't specify this, just the
headers will be sent
@return boolean | [
"Transmit",
"headers",
"that",
"force",
"a",
"browser",
"to",
"display",
"the",
"download",
"file",
"dialog",
".",
"Cross",
"browser",
"compatible",
".",
"Only",
"fires",
"if",
"headers",
"have",
"not",
"already",
"been",
"sent",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1675-L1711 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.random_string | public static function random_string($length = 16, $human_friendly = true, $include_symbols = false, $no_duplicate_chars = false)
{
$nice_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefhjkmnprstuvwxyz23456789';
$all_an = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
$symbols = '!@#$%^&*()~_-=+{}[]|:;<>,.?/"\'\\`';
$string = '';
// Determine the pool of available characters based on the given parameters
if ($human_friendly) {
$pool = $nice_chars;
} else {
$pool = $all_an;
if ($include_symbols) {
$pool .= $symbols;
}
}
if (!$no_duplicate_chars) {
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
// Don't allow duplicate letters to be disabled if the length is
// longer than the available characters
if ($no_duplicate_chars && strlen($pool) < $length) {
throw new \LengthException('$length exceeds the size of the pool and $no_duplicate_chars is enabled');
}
// Convert the pool of characters into an array of characters and
// shuffle the array
$pool = str_split($pool);
$poolLength = count($pool);
$rand = mt_rand(0, $poolLength - 1);
// Generate our string
for ($i = 0; $i < $length; $i++) {
$string .= $pool[$rand];
// Remove the character from the array to avoid duplicates
array_splice($pool, $rand, 1);
// Generate a new number
if (($poolLength - 2 - $i) > 0) {
$rand = mt_rand(0, $poolLength - 2 - $i);
} else {
$rand = 0;
}
}
return $string;
} | php | public static function random_string($length = 16, $human_friendly = true, $include_symbols = false, $no_duplicate_chars = false)
{
$nice_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefhjkmnprstuvwxyz23456789';
$all_an = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
$symbols = '!@#$%^&*()~_-=+{}[]|:;<>,.?/"\'\\`';
$string = '';
// Determine the pool of available characters based on the given parameters
if ($human_friendly) {
$pool = $nice_chars;
} else {
$pool = $all_an;
if ($include_symbols) {
$pool .= $symbols;
}
}
if (!$no_duplicate_chars) {
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
// Don't allow duplicate letters to be disabled if the length is
// longer than the available characters
if ($no_duplicate_chars && strlen($pool) < $length) {
throw new \LengthException('$length exceeds the size of the pool and $no_duplicate_chars is enabled');
}
// Convert the pool of characters into an array of characters and
// shuffle the array
$pool = str_split($pool);
$poolLength = count($pool);
$rand = mt_rand(0, $poolLength - 1);
// Generate our string
for ($i = 0; $i < $length; $i++) {
$string .= $pool[$rand];
// Remove the character from the array to avoid duplicates
array_splice($pool, $rand, 1);
// Generate a new number
if (($poolLength - 2 - $i) > 0) {
$rand = mt_rand(0, $poolLength - 2 - $i);
} else {
$rand = 0;
}
}
return $string;
} | [
"public",
"static",
"function",
"random_string",
"(",
"$",
"length",
"=",
"16",
",",
"$",
"human_friendly",
"=",
"true",
",",
"$",
"include_symbols",
"=",
"false",
",",
"$",
"no_duplicate_chars",
"=",
"false",
")",
"{",
"$",
"nice_chars",
"=",
"'ABCDEFGHJKLM... | Generates a string of random characters.
@throws LengthException If $length is bigger than the available
character pool and $no_duplicate_chars is
enabled
@param integer $length The length of the string to
generate
@param boolean $human_friendly Whether or not to make the
string human friendly by
removing characters that can be
confused with other characters (
O and 0, l and 1, etc)
@param boolean $include_symbols Whether or not to include
symbols in the string. Can not
be enabled if $human_friendly is
true
@param boolean $no_duplicate_chars Whether or not to only use
characters once in the string.
@return string | [
"Generates",
"a",
"string",
"of",
"random",
"characters",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1760-L1810 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.secure_random_string | public static function secure_random_string($length = 16)
{
if (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($length * 2);
if ($bytes === false) {
throw new \LengthException('$length is not accurate, unable to generate random string');
}
return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
}
// @codeCoverageIgnoreStart
return static::random_string($length);
// @codeCoverageIgnoreEnd
} | php | public static function secure_random_string($length = 16)
{
if (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($length * 2);
if ($bytes === false) {
throw new \LengthException('$length is not accurate, unable to generate random string');
}
return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
}
// @codeCoverageIgnoreStart
return static::random_string($length);
// @codeCoverageIgnoreEnd
} | [
"public",
"static",
"function",
"secure_random_string",
"(",
"$",
"length",
"=",
"16",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'openssl_random_pseudo_bytes'",
")",
")",
"{",
"$",
"bytes",
"=",
"openssl_random_pseudo_bytes",
"(",
"$",
"length",
"*",
"2",
... | Generate secure random string of given length
If 'openssl_random_pseudo_bytes' is not available
then generate random string using default function
Part of the Laravel Project <https://github.com/laravel/laravel>
@param int $length length of string
@return bool | [
"Generate",
"secure",
"random",
"string",
"of",
"given",
"length",
"If",
"openssl_random_pseudo_bytes",
"is",
"not",
"available",
"then",
"generate",
"random",
"string",
"using",
"default",
"function"
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1822-L1837 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.get_gravatar | public static function get_gravatar($email, $size = 32)
{
if (self::is_https()) {
$url = 'https://secure.gravatar.com/';
} else {
$url = 'http://www.gravatar.com/';
}
$url .= 'avatar/' . md5($email) . '?s=' . (int) abs($size);
return $url;
} | php | public static function get_gravatar($email, $size = 32)
{
if (self::is_https()) {
$url = 'https://secure.gravatar.com/';
} else {
$url = 'http://www.gravatar.com/';
}
$url .= 'avatar/' . md5($email) . '?s=' . (int) abs($size);
return $url;
} | [
"public",
"static",
"function",
"get_gravatar",
"(",
"$",
"email",
",",
"$",
"size",
"=",
"32",
")",
"{",
"if",
"(",
"self",
"::",
"is_https",
"(",
")",
")",
"{",
"$",
"url",
"=",
"'https://secure.gravatar.com/'",
";",
"}",
"else",
"{",
"$",
"url",
"... | Return the URL to a user's gravatar.
@param string $email The email of the user
@param integer $size The size of the gravatar
@return string | [
"Return",
"the",
"URL",
"to",
"a",
"user",
"s",
"gravatar",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1884-L1895 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.linkify | public static function linkify($text)
{
$text = preg_replace('/'/', ''', $text); // IE does not handle ' entity!
$section_html_pattern = '%# Rev:20100913_0900 github.com/jmrware/LinkifyURL
# Section text into HTML <A> tags and everything else.
( # $1: Everything not HTML <A> tag.
[^<]+(?:(?!<a\b)<[^<]*)* # non A tag stuff starting with non-"<".
| (?:(?!<a\b)<[^<]*)+ # non A tag stuff starting with "<".
) # End $1.
| ( # $2: HTML <A...>...</A> tag.
<a\b[^>]*> # <A...> opening tag.
[^<]*(?:(?!</a\b)<[^<]*)* # A tag contents.
</a\s*> # </A> closing tag.
) # End $2:
%ix';
return preg_replace_callback($section_html_pattern, array(__CLASS__, 'linkifyCallback'), $text);
} | php | public static function linkify($text)
{
$text = preg_replace('/'/', ''', $text); // IE does not handle ' entity!
$section_html_pattern = '%# Rev:20100913_0900 github.com/jmrware/LinkifyURL
# Section text into HTML <A> tags and everything else.
( # $1: Everything not HTML <A> tag.
[^<]+(?:(?!<a\b)<[^<]*)* # non A tag stuff starting with non-"<".
| (?:(?!<a\b)<[^<]*)+ # non A tag stuff starting with "<".
) # End $1.
| ( # $2: HTML <A...>...</A> tag.
<a\b[^>]*> # <A...> opening tag.
[^<]*(?:(?!</a\b)<[^<]*)* # A tag contents.
</a\s*> # </A> closing tag.
) # End $2:
%ix';
return preg_replace_callback($section_html_pattern, array(__CLASS__, 'linkifyCallback'), $text);
} | [
"public",
"static",
"function",
"linkify",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"preg_replace",
"(",
"'/'/'",
",",
"'''",
",",
"$",
"text",
")",
";",
"// IE does not handle ' entity!",
"$",
"section_html_pattern",
"=",
"'%# Rev:20100913_0900... | Turns all of the links in a string into HTML links.
Part of the LinkifyURL Project <https://github.com/jmrware/LinkifyURL>
@param string $text The string to parse
@return string | [
"Turns",
"all",
"of",
"the",
"links",
"in",
"a",
"string",
"into",
"HTML",
"links",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L1905-L1922 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.get_current_url | public static function get_current_url()
{
$url = '';
// Check to see if it's over https
$is_https = self::is_https();
if ($is_https) {
$url .= 'https://';
} else {
$url .= 'http://';
}
// Was a username or password passed?
if (isset($_SERVER['PHP_AUTH_USER'])) {
$url .= $_SERVER['PHP_AUTH_USER'];
if (isset($_SERVER['PHP_AUTH_PW'])) {
$url .= ':' . $_SERVER['PHP_AUTH_PW'];
}
$url .= '@';
}
// We want the user to stay on the same host they are currently on,
// but beware of security issues
// see http://shiflett.org/blog/2006/mar/server-name-versus-http-host
$url .= $_SERVER['HTTP_HOST'];
$port = $_SERVER['SERVER_PORT'];
// Is it on a non standard port?
if ($is_https && ($port != 443)) {
$url .= ':' . $_SERVER['SERVER_PORT'];
} elseif (!$is_https && ($port != 80)) {
$url .= ':' . $_SERVER['SERVER_PORT'];
}
// Get the rest of the URL
if (!isset($_SERVER['REQUEST_URI'])) {
// Microsoft IIS doesn't set REQUEST_URI by default
$url .= $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$url .= '?' . $_SERVER['QUERY_STRING'];
}
} else {
$url .= $_SERVER['REQUEST_URI'];
}
return $url;
} | php | public static function get_current_url()
{
$url = '';
// Check to see if it's over https
$is_https = self::is_https();
if ($is_https) {
$url .= 'https://';
} else {
$url .= 'http://';
}
// Was a username or password passed?
if (isset($_SERVER['PHP_AUTH_USER'])) {
$url .= $_SERVER['PHP_AUTH_USER'];
if (isset($_SERVER['PHP_AUTH_PW'])) {
$url .= ':' . $_SERVER['PHP_AUTH_PW'];
}
$url .= '@';
}
// We want the user to stay on the same host they are currently on,
// but beware of security issues
// see http://shiflett.org/blog/2006/mar/server-name-versus-http-host
$url .= $_SERVER['HTTP_HOST'];
$port = $_SERVER['SERVER_PORT'];
// Is it on a non standard port?
if ($is_https && ($port != 443)) {
$url .= ':' . $_SERVER['SERVER_PORT'];
} elseif (!$is_https && ($port != 80)) {
$url .= ':' . $_SERVER['SERVER_PORT'];
}
// Get the rest of the URL
if (!isset($_SERVER['REQUEST_URI'])) {
// Microsoft IIS doesn't set REQUEST_URI by default
$url .= $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$url .= '?' . $_SERVER['QUERY_STRING'];
}
} else {
$url .= $_SERVER['REQUEST_URI'];
}
return $url;
} | [
"public",
"static",
"function",
"get_current_url",
"(",
")",
"{",
"$",
"url",
"=",
"''",
";",
"// Check to see if it's over https",
"$",
"is_https",
"=",
"self",
"::",
"is_https",
"(",
")",
";",
"if",
"(",
"$",
"is_https",
")",
"{",
"$",
"url",
".=",
"'h... | Return the current URL.
@return string | [
"Return",
"the",
"current",
"URL",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2002-L2053 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.get_client_ip | public static function get_client_ip($trust_proxy_headers = false)
{
if (!$trust_proxy_headers) {
return $_SERVER['REMOTE_ADDR'];
}
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
} | php | public static function get_client_ip($trust_proxy_headers = false)
{
if (!$trust_proxy_headers) {
return $_SERVER['REMOTE_ADDR'];
}
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
} | [
"public",
"static",
"function",
"get_client_ip",
"(",
"$",
"trust_proxy_headers",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"trust_proxy_headers",
")",
"{",
"return",
"$",
"_SERVER",
"[",
"'REMOTE_ADDR'",
"]",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"... | Returns the IP address of the client.
@param boolean $trust_proxy_headers Whether or not to trust the
proxy headers HTTP_CLIENT_IP
and HTTP_X_FORWARDED_FOR. ONLY
use if your server is behind a
proxy that sets these values
@return string | [
"Returns",
"the",
"IP",
"address",
"of",
"the",
"client",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2065-L2080 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.safe_truncate | public static function safe_truncate($string, $length, $append = '...')
{
$ret = substr($string, 0, $length);
$last_space = strrpos($ret, ' ');
if ($last_space !== false && $string != $ret) {
$ret = substr($ret, 0, $last_space);
}
if ($ret != $string) {
$ret .= $append;
}
return $ret;
} | php | public static function safe_truncate($string, $length, $append = '...')
{
$ret = substr($string, 0, $length);
$last_space = strrpos($ret, ' ');
if ($last_space !== false && $string != $ret) {
$ret = substr($ret, 0, $last_space);
}
if ($ret != $string) {
$ret .= $append;
}
return $ret;
} | [
"public",
"static",
"function",
"safe_truncate",
"(",
"$",
"string",
",",
"$",
"length",
",",
"$",
"append",
"=",
"'...'",
")",
"{",
"$",
"ret",
"=",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"$",
"length",
")",
";",
"$",
"last_space",
"=",
"str... | Truncate a string to a specified length without cutting a word off.
@param string $string The string to truncate
@param integer $length The length to truncate the string to
@param string $append Text to append to the string IF it gets
truncated, defaults to '...'
@return string | [
"Truncate",
"a",
"string",
"to",
"a",
"specified",
"length",
"without",
"cutting",
"a",
"word",
"off",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2091-L2105 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.limit_characters | public static function limit_characters($string, $limit = 100, $append = '...')
{
if (mb_strlen($string) <= $limit) {
return $string;
}
return rtrim(mb_substr($string, 0, $limit, 'UTF-8')) . $append;
} | php | public static function limit_characters($string, $limit = 100, $append = '...')
{
if (mb_strlen($string) <= $limit) {
return $string;
}
return rtrim(mb_substr($string, 0, $limit, 'UTF-8')) . $append;
} | [
"public",
"static",
"function",
"limit_characters",
"(",
"$",
"string",
",",
"$",
"limit",
"=",
"100",
",",
"$",
"append",
"=",
"'...'",
")",
"{",
"if",
"(",
"mb_strlen",
"(",
"$",
"string",
")",
"<=",
"$",
"limit",
")",
"{",
"return",
"$",
"string",... | Truncate the string to given length of characters.
@param string $string The variable to truncate
@param integer $limit The length to truncate the string to
@param string $append Text to append to the string IF it gets
truncated, defaults to '...'
@return string | [
"Truncate",
"the",
"string",
"to",
"given",
"length",
"of",
"characters",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2117-L2124 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.limit_words | public static function limit_words($string, $limit = 100, $append = '...')
{
preg_match('/^\s*+(?:\S++\s*+){1,' . $limit . '}/u', $string, $matches);
if (!isset($matches[0]) || strlen($string) === strlen($matches[0])) {
return $string;
}
return rtrim($matches[0]).$append;
} | php | public static function limit_words($string, $limit = 100, $append = '...')
{
preg_match('/^\s*+(?:\S++\s*+){1,' . $limit . '}/u', $string, $matches);
if (!isset($matches[0]) || strlen($string) === strlen($matches[0])) {
return $string;
}
return rtrim($matches[0]).$append;
} | [
"public",
"static",
"function",
"limit_words",
"(",
"$",
"string",
",",
"$",
"limit",
"=",
"100",
",",
"$",
"append",
"=",
"'...'",
")",
"{",
"preg_match",
"(",
"'/^\\s*+(?:\\S++\\s*+){1,'",
".",
"$",
"limit",
".",
"'}/u'",
",",
"$",
"string",
",",
"$",
... | Truncate the string to given length of words.
@param $string
@param $limit
@param string $append
@return string | [
"Truncate",
"the",
"string",
"to",
"given",
"length",
"of",
"words",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2134-L2143 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.ordinal | public static function ordinal($number)
{
$test_c = abs($number) % 10;
$ext = ((abs($number) % 100 < 21 && abs($number) % 100 > 4) ? 'th' : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
return $number . $ext;
} | php | public static function ordinal($number)
{
$test_c = abs($number) % 10;
$ext = ((abs($number) % 100 < 21 && abs($number) % 100 > 4) ? 'th' : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
return $number . $ext;
} | [
"public",
"static",
"function",
"ordinal",
"(",
"$",
"number",
")",
"{",
"$",
"test_c",
"=",
"abs",
"(",
"$",
"number",
")",
"%",
"10",
";",
"$",
"ext",
"=",
"(",
"(",
"abs",
"(",
"$",
"number",
")",
"%",
"100",
"<",
"21",
"&&",
"abs",
"(",
"... | Returns the ordinal version of a number (appends th, st, nd, rd).
@param string $number The number to append an ordinal suffix to
@return string | [
"Returns",
"the",
"ordinal",
"version",
"of",
"a",
"number",
"(",
"appends",
"th",
"st",
"nd",
"rd",
")",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2151-L2157 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.full_permissions | public static function full_permissions($file, $perms = null)
{
if (is_null($perms)) {
if (!file_exists($file)) {
return false;
}
$perms = fileperms($file);
}
if (($perms & 0xC000) == 0xC000) {
// Socket
$info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
// Symbolic Link
$info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
// Regular
$info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
// Block special
$info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
// Directory
$info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
// Character special
$info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
// FIFO pipe
$info = 'p';
} else {
// Unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x') :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x') :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x') :
(($perms & 0x0200) ? 'T' : '-'));
return $info;
} | php | public static function full_permissions($file, $perms = null)
{
if (is_null($perms)) {
if (!file_exists($file)) {
return false;
}
$perms = fileperms($file);
}
if (($perms & 0xC000) == 0xC000) {
// Socket
$info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
// Symbolic Link
$info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
// Regular
$info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
// Block special
$info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
// Directory
$info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
// Character special
$info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
// FIFO pipe
$info = 'p';
} else {
// Unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x') :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x') :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x') :
(($perms & 0x0200) ? 'T' : '-'));
return $info;
} | [
"public",
"static",
"function",
"full_permissions",
"(",
"$",
"file",
",",
"$",
"perms",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"perms",
")",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"return",
"false... | Returns the file permissions as a nice string, like -rw-r--r-- or false
if the file is not found.
@param string $file The name of the file to get permissions form
@param int $perms Numerical value of permissions to display as text.
@return string | [
"Returns",
"the",
"file",
"permissions",
"as",
"a",
"nice",
"string",
"like",
"-",
"rw",
"-",
"r",
"--",
"r",
"--",
"or",
"false",
"if",
"the",
"file",
"is",
"not",
"found",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2167-L2224 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.array_flatten | public static function array_flatten(array $array, $preserve_keys = true)
{
$flattened = array();
array_walk_recursive($array, function ($value, $key) use (&$flattened, $preserve_keys) {
if ($preserve_keys && !is_int($key)) {
$flattened[$key] = $value;
} else {
$flattened[] = $value;
}
});
return $flattened;
} | php | public static function array_flatten(array $array, $preserve_keys = true)
{
$flattened = array();
array_walk_recursive($array, function ($value, $key) use (&$flattened, $preserve_keys) {
if ($preserve_keys && !is_int($key)) {
$flattened[$key] = $value;
} else {
$flattened[] = $value;
}
});
return $flattened;
} | [
"public",
"static",
"function",
"array_flatten",
"(",
"array",
"$",
"array",
",",
"$",
"preserve_keys",
"=",
"true",
")",
"{",
"$",
"flattened",
"=",
"array",
"(",
")",
";",
"array_walk_recursive",
"(",
"$",
"array",
",",
"function",
"(",
"$",
"value",
"... | Flatten a multi-dimensional array into a one dimensional array.
Contributed by Theodore R. Smith of PHP Experts, Inc. <http://www.phpexperts.pro/>
@param array $array The array to flatten
@param boolean $preserve_keys Whether or not to preserve array keys.
Keys from deeply nested arrays will
overwrite keys from shallowy nested arrays
@return array | [
"Flatten",
"a",
"multi",
"-",
"dimensional",
"array",
"into",
"a",
"one",
"dimensional",
"array",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2285-L2298 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.array_search_deep | public static function array_search_deep(array $array, $search, $field = false)
{
// *grumbles* stupid PHP type system
$search = (string) $search;
foreach ($array as $key => $elem) {
// *grumbles* stupid PHP type system
$key = (string) $key;
if ($field) {
if (is_object($elem) && $elem->{$field} === $search) {
return $key;
} elseif (is_array($elem) && $elem[$field] === $search) {
return $key;
} elseif (is_scalar($elem) && $elem === $search) {
return $key;
}
} else {
if (is_object($elem)) {
$elem = (array) $elem;
if (in_array($search, $elem)) {
return $key;
}
} elseif (is_array($elem) && in_array($search, $elem)) {
return $key;
} elseif (is_scalar($elem) && $elem === $search) {
return $key;
}
}
}
return false;
} | php | public static function array_search_deep(array $array, $search, $field = false)
{
// *grumbles* stupid PHP type system
$search = (string) $search;
foreach ($array as $key => $elem) {
// *grumbles* stupid PHP type system
$key = (string) $key;
if ($field) {
if (is_object($elem) && $elem->{$field} === $search) {
return $key;
} elseif (is_array($elem) && $elem[$field] === $search) {
return $key;
} elseif (is_scalar($elem) && $elem === $search) {
return $key;
}
} else {
if (is_object($elem)) {
$elem = (array) $elem;
if (in_array($search, $elem)) {
return $key;
}
} elseif (is_array($elem) && in_array($search, $elem)) {
return $key;
} elseif (is_scalar($elem) && $elem === $search) {
return $key;
}
}
}
return false;
} | [
"public",
"static",
"function",
"array_search_deep",
"(",
"array",
"$",
"array",
",",
"$",
"search",
",",
"$",
"field",
"=",
"false",
")",
"{",
"// *grumbles* stupid PHP type system",
"$",
"search",
"=",
"(",
"string",
")",
"$",
"search",
";",
"foreach",
"("... | Searches for a given value in an array of arrays, objects and scalar
values. You can optionally specify a field of the nested arrays and
objects to search in.
@param array $array The array to search
@param scalar $search The value to search for
@param string $field The field to search in, if not specified
all fields will be searched
@return boolean|scalar False on failure or the array key on success | [
"Searches",
"for",
"a",
"given",
"value",
"in",
"an",
"array",
"of",
"arrays",
"objects",
"and",
"scalar",
"values",
".",
"You",
"can",
"optionally",
"specify",
"a",
"field",
"of",
"the",
"nested",
"arrays",
"and",
"objects",
"to",
"search",
"in",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2356-L2389 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.array_merge_deep | public static function array_merge_deep(array $dest, array $src, $appendIntegerKeys = true)
{
foreach ($src as $key => $value) {
if (is_int($key) and $appendIntegerKeys) {
$dest[] = $value;
} elseif (isset($dest[$key]) and is_array($dest[$key]) and is_array($value)) {
$dest[$key] = static::array_merge_deep($dest[$key], $value, $appendIntegerKeys);
} else {
$dest[$key] = $value;
}
}
return $dest;
} | php | public static function array_merge_deep(array $dest, array $src, $appendIntegerKeys = true)
{
foreach ($src as $key => $value) {
if (is_int($key) and $appendIntegerKeys) {
$dest[] = $value;
} elseif (isset($dest[$key]) and is_array($dest[$key]) and is_array($value)) {
$dest[$key] = static::array_merge_deep($dest[$key], $value, $appendIntegerKeys);
} else {
$dest[$key] = $value;
}
}
return $dest;
} | [
"public",
"static",
"function",
"array_merge_deep",
"(",
"array",
"$",
"dest",
",",
"array",
"$",
"src",
",",
"$",
"appendIntegerKeys",
"=",
"true",
")",
"{",
"foreach",
"(",
"$",
"src",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_... | Merges two arrays recursively and returns the result.
@param array $dest Destination array
@param array $src Source array
@param boolean $appendIntegerKeys Whether to append elements of $src
to $dest if the key is an integer.
This is the default behavior.
Otherwise elements from $src will
overwrite the ones in $dest.
@return array | [
"Merges",
"two",
"arrays",
"recursively",
"and",
"returns",
"the",
"result",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2430-L2442 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.set_writable | public static function set_writable($filename, $writable = true)
{
$stat = @stat($filename);
if ($stat === false) {
return false;
}
// We're on Windows
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
return true;
}
list($myuid, $mygid) = array(posix_geteuid(), posix_getgid());
if ($writable) {
// Set only the user writable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, fileperms($filename) | 0200);
}
// Set only the group writable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, fileperms($filename) | 0220);
}
// Set the world writable bit (file isn't owned or grouped by us)
return chmod($filename, fileperms($filename) | 0222);
} else {
// Set only the user writable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, (fileperms($filename) | 0222) ^ 0222);
}
// Set only the group writable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, (fileperms($filename) | 0222) ^ 0022);
}
// Set the world writable bit (file isn't owned or grouped by us)
return chmod($filename, (fileperms($filename) | 0222) ^ 0002);
}
} | php | public static function set_writable($filename, $writable = true)
{
$stat = @stat($filename);
if ($stat === false) {
return false;
}
// We're on Windows
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
return true;
}
list($myuid, $mygid) = array(posix_geteuid(), posix_getgid());
if ($writable) {
// Set only the user writable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, fileperms($filename) | 0200);
}
// Set only the group writable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, fileperms($filename) | 0220);
}
// Set the world writable bit (file isn't owned or grouped by us)
return chmod($filename, fileperms($filename) | 0222);
} else {
// Set only the user writable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, (fileperms($filename) | 0222) ^ 0222);
}
// Set only the group writable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, (fileperms($filename) | 0222) ^ 0022);
}
// Set the world writable bit (file isn't owned or grouped by us)
return chmod($filename, (fileperms($filename) | 0222) ^ 0002);
}
} | [
"public",
"static",
"function",
"set_writable",
"(",
"$",
"filename",
",",
"$",
"writable",
"=",
"true",
")",
"{",
"$",
"stat",
"=",
"@",
"stat",
"(",
"$",
"filename",
")",
";",
"if",
"(",
"$",
"stat",
"===",
"false",
")",
"{",
"return",
"false",
"... | Set the writable bit on a file to the minimum value that allows the user
running PHP to write to it.
@param string $filename The filename to set the writable bit on
@param boolean $writable Whether to make the file writable or not
@return boolean | [
"Set",
"the",
"writable",
"bit",
"on",
"a",
"file",
"to",
"the",
"minimum",
"value",
"that",
"allows",
"the",
"user",
"running",
"PHP",
"to",
"write",
"to",
"it",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2475-L2517 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.set_readable | public static function set_readable($filename, $readable = true)
{
$stat = @stat($filename);
if ($stat === false) {
return false;
}
// We're on Windows
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
return true;
}
list($myuid, $mygid) = array(posix_geteuid(), posix_getgid());
if ($readable) {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, fileperms($filename) | 0400);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, fileperms($filename) | 0440);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, fileperms($filename) | 0444);
} else {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, (fileperms($filename) | 0444) ^ 0444);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, (fileperms($filename) | 0444) ^ 0044);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, (fileperms($filename) | 0444) ^ 0004);
}
} | php | public static function set_readable($filename, $readable = true)
{
$stat = @stat($filename);
if ($stat === false) {
return false;
}
// We're on Windows
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
return true;
}
list($myuid, $mygid) = array(posix_geteuid(), posix_getgid());
if ($readable) {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, fileperms($filename) | 0400);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, fileperms($filename) | 0440);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, fileperms($filename) | 0444);
} else {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, (fileperms($filename) | 0444) ^ 0444);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, (fileperms($filename) | 0444) ^ 0044);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, (fileperms($filename) | 0444) ^ 0004);
}
} | [
"public",
"static",
"function",
"set_readable",
"(",
"$",
"filename",
",",
"$",
"readable",
"=",
"true",
")",
"{",
"$",
"stat",
"=",
"@",
"stat",
"(",
"$",
"filename",
")",
";",
"if",
"(",
"$",
"stat",
"===",
"false",
")",
"{",
"return",
"false",
"... | Set the readable bit on a file to the minimum value that allows the user
running PHP to read to it.
@param string $filename The filename to set the readable bit on
@param boolean $readable Whether to make the file readable or not
@return boolean | [
"Set",
"the",
"readable",
"bit",
"on",
"a",
"file",
"to",
"the",
"minimum",
"value",
"that",
"allows",
"the",
"user",
"running",
"PHP",
"to",
"read",
"to",
"it",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2527-L2569 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.set_executable | public static function set_executable($filename, $executable = true)
{
$stat = @stat($filename);
if ($stat === false) {
return false;
}
// We're on Windows
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
return true;
}
list($myuid, $mygid) = array(posix_geteuid(), posix_getgid());
if ($executable) {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, fileperms($filename) | 0100);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, fileperms($filename) | 0110);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, fileperms($filename) | 0111);
} else {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, (fileperms($filename) | 0111) ^ 0111);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, (fileperms($filename) | 0111) ^ 0011);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, (fileperms($filename) | 0111) ^ 0001);
}
} | php | public static function set_executable($filename, $executable = true)
{
$stat = @stat($filename);
if ($stat === false) {
return false;
}
// We're on Windows
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
return true;
}
list($myuid, $mygid) = array(posix_geteuid(), posix_getgid());
if ($executable) {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, fileperms($filename) | 0100);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, fileperms($filename) | 0110);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, fileperms($filename) | 0111);
} else {
// Set only the user readable bit (file is owned by us)
if ($stat['uid'] == $myuid) {
return chmod($filename, (fileperms($filename) | 0111) ^ 0111);
}
// Set only the group readable bit (file group is the same as us)
if ($stat['gid'] == $mygid) {
return chmod($filename, (fileperms($filename) | 0111) ^ 0011);
}
// Set the world readable bit (file isn't owned or grouped by us)
return chmod($filename, (fileperms($filename) | 0111) ^ 0001);
}
} | [
"public",
"static",
"function",
"set_executable",
"(",
"$",
"filename",
",",
"$",
"executable",
"=",
"true",
")",
"{",
"$",
"stat",
"=",
"@",
"stat",
"(",
"$",
"filename",
")",
";",
"if",
"(",
"$",
"stat",
"===",
"false",
")",
"{",
"return",
"false",... | Set the executable bit on a file to the minimum value that allows the
user running PHP to read to it.
@param string $filename The filename to set the executable bit on
@param boolean $executable Whether to make the file executable or not
@return boolean | [
"Set",
"the",
"executable",
"bit",
"on",
"a",
"file",
"to",
"the",
"minimum",
"value",
"that",
"allows",
"the",
"user",
"running",
"PHP",
"to",
"read",
"to",
"it",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2579-L2621 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.directory_size | public static function directory_size($dir)
{
$size = 0;
foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS)) as $file => $key) {
if ($key->isFile()) {
$size += $key->getSize();
}
}
return $size;
} | php | public static function directory_size($dir)
{
$size = 0;
foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS)) as $file => $key) {
if ($key->isFile()) {
$size += $key->getSize();
}
}
return $size;
} | [
"public",
"static",
"function",
"directory_size",
"(",
"$",
"dir",
")",
"{",
"$",
"size",
"=",
"0",
";",
"foreach",
"(",
"new",
"\\",
"RecursiveIteratorIterator",
"(",
"new",
"\\",
"RecursiveDirectoryIterator",
"(",
"$",
"dir",
",",
"\\",
"FilesystemIterator",... | Returns size of a given directory in bytes.
@param string $dir
@return integer | [
"Returns",
"size",
"of",
"a",
"given",
"directory",
"in",
"bytes",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2629-L2638 |
brandonwamboldt/utilphp | src/utilphp/util.php | util.directory_contents | public static function directory_contents($dir)
{
$contents = array();
foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS)) as $pathname => $fi) {
$contents[] = $pathname;
}
natsort($contents);
return $contents;
} | php | public static function directory_contents($dir)
{
$contents = array();
foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS)) as $pathname => $fi) {
$contents[] = $pathname;
}
natsort($contents);
return $contents;
} | [
"public",
"static",
"function",
"directory_contents",
"(",
"$",
"dir",
")",
"{",
"$",
"contents",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"new",
"\\",
"RecursiveIteratorIterator",
"(",
"new",
"\\",
"RecursiveDirectoryIterator",
"(",
"$",
"dir",
",",
"\\... | Returns all paths inside a directory.
@param string $dir
@return array | [
"Returns",
"all",
"paths",
"inside",
"a",
"directory",
"."
] | train | https://github.com/brandonwamboldt/utilphp/blob/8d4e335434724e699469350e3cf49017992511c8/src/utilphp/util.php#L2660-L2668 |
thephpleague/uri-components | src/Component/UserInfo.php | UserInfo.getContent | public function getContent(): ?string
{
if (null === $this->user) {
return null;
}
$userInfo = $this->encodeComponent($this->user, self::RFC3986_ENCODING, self::REGEXP_USERINFO_ENCODING);
if (null === $this->pass) {
return $userInfo;
}
return $userInfo.':'.$this->encodeComponent($this->pass, self::RFC3986_ENCODING, self::REGEXP_USERINFO_ENCODING);
} | php | public function getContent(): ?string
{
if (null === $this->user) {
return null;
}
$userInfo = $this->encodeComponent($this->user, self::RFC3986_ENCODING, self::REGEXP_USERINFO_ENCODING);
if (null === $this->pass) {
return $userInfo;
}
return $userInfo.':'.$this->encodeComponent($this->pass, self::RFC3986_ENCODING, self::REGEXP_USERINFO_ENCODING);
} | [
"public",
"function",
"getContent",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"user",
")",
"{",
"return",
"null",
";",
"}",
"$",
"userInfo",
"=",
"$",
"this",
"->",
"encodeComponent",
"(",
"$",
"this",
"->",
"u... | {@inheritdoc} | [
"{"
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/UserInfo.php#L64-L76 |
thephpleague/uri-components | src/Component/UserInfo.php | UserInfo.decoded | public function decoded(): ?string
{
if (null === $this->user) {
return null;
}
$userInfo = $this->getUser();
if (null === $this->pass) {
return $userInfo;
}
return $userInfo.':'.$this->getPass();
} | php | public function decoded(): ?string
{
if (null === $this->user) {
return null;
}
$userInfo = $this->getUser();
if (null === $this->pass) {
return $userInfo;
}
return $userInfo.':'.$this->getPass();
} | [
"public",
"function",
"decoded",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"user",
")",
"{",
"return",
"null",
";",
"}",
"$",
"userInfo",
"=",
"$",
"this",
"->",
"getUser",
"(",
")",
";",
"if",
"(",
"null",
... | Returns the decoded component. | [
"Returns",
"the",
"decoded",
"component",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/UserInfo.php#L89-L101 |
thephpleague/uri-components | src/Component/UserInfo.php | UserInfo.getUser | public function getUser(): ?string
{
return $this->encodeComponent($this->user, self::NO_ENCODING, self::REGEXP_USERINFO_ENCODING);
} | php | public function getUser(): ?string
{
return $this->encodeComponent($this->user, self::NO_ENCODING, self::REGEXP_USERINFO_ENCODING);
} | [
"public",
"function",
"getUser",
"(",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"encodeComponent",
"(",
"$",
"this",
"->",
"user",
",",
"self",
"::",
"NO_ENCODING",
",",
"self",
"::",
"REGEXP_USERINFO_ENCODING",
")",
";",
"}"
] | Retrieve the user component of the URI User Info part. | [
"Retrieve",
"the",
"user",
"component",
"of",
"the",
"URI",
"User",
"Info",
"part",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/UserInfo.php#L106-L109 |
thephpleague/uri-components | src/Component/UserInfo.php | UserInfo.getPass | public function getPass(): ?string
{
return $this->encodeComponent($this->pass, self::NO_ENCODING, self::REGEXP_USERINFO_ENCODING);
} | php | public function getPass(): ?string
{
return $this->encodeComponent($this->pass, self::NO_ENCODING, self::REGEXP_USERINFO_ENCODING);
} | [
"public",
"function",
"getPass",
"(",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"encodeComponent",
"(",
"$",
"this",
"->",
"pass",
",",
"self",
"::",
"NO_ENCODING",
",",
"self",
"::",
"REGEXP_USERINFO_ENCODING",
")",
";",
"}"
] | Retrieve the pass component of the URI User Info part. | [
"Retrieve",
"the",
"pass",
"component",
"of",
"the",
"URI",
"User",
"Info",
"part",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/UserInfo.php#L114-L117 |
thephpleague/uri-components | src/Component/UserInfo.php | UserInfo.withContent | public function withContent($content): self
{
$content = $this->filterComponent($content);
if ($content === $this->getContent()) {
return $this;
}
if (null === $content) {
return new self();
}
return new self(...explode(':', $content, 2) + [1 => null]);
} | php | public function withContent($content): self
{
$content = $this->filterComponent($content);
if ($content === $this->getContent()) {
return $this;
}
if (null === $content) {
return new self();
}
return new self(...explode(':', $content, 2) + [1 => null]);
} | [
"public",
"function",
"withContent",
"(",
"$",
"content",
")",
":",
"self",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"filterComponent",
"(",
"$",
"content",
")",
";",
"if",
"(",
"$",
"content",
"===",
"$",
"this",
"->",
"getContent",
"(",
")",
")... | {@inheritdoc} | [
"{"
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/UserInfo.php#L122-L134 |
thephpleague/uri-components | src/Component/UserInfo.php | UserInfo.withUserInfo | public function withUserInfo($user, $pass = null): self
{
$user = $this->validateComponent($user);
$pass = $this->validateComponent($pass);
if (null === $user || '' === $user) {
$pass = null;
}
if ($user === $this->user && $pass === $this->pass) {
return $this;
}
$clone = clone $this;
$clone->user = $user;
$clone->pass = $pass;
return $clone;
} | php | public function withUserInfo($user, $pass = null): self
{
$user = $this->validateComponent($user);
$pass = $this->validateComponent($pass);
if (null === $user || '' === $user) {
$pass = null;
}
if ($user === $this->user && $pass === $this->pass) {
return $this;
}
$clone = clone $this;
$clone->user = $user;
$clone->pass = $pass;
return $clone;
} | [
"public",
"function",
"withUserInfo",
"(",
"$",
"user",
",",
"$",
"pass",
"=",
"null",
")",
":",
"self",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"validateComponent",
"(",
"$",
"user",
")",
";",
"$",
"pass",
"=",
"$",
"this",
"->",
"validateComponen... | Return an instance with the specified user.
This method MUST retain the state of the current instance, and return
an instance that contains the specified user.
An empty user is equivalent to removing the user information.
@param null|mixed $pass | [
"Return",
"an",
"instance",
"with",
"the",
"specified",
"user",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/UserInfo.php#L145-L162 |
thephpleague/uri-components | src/Component/Scheme.php | Scheme.validate | private function validate($scheme): ?string
{
$scheme = $this->filterComponent($scheme);
if (null === $scheme) {
return $scheme;
}
if (1 === preg_match(self::REGEXP_SCHEME, $scheme)) {
return strtolower($scheme);
}
throw new SyntaxError(sprintf("The scheme '%s' is invalid", $scheme));
} | php | private function validate($scheme): ?string
{
$scheme = $this->filterComponent($scheme);
if (null === $scheme) {
return $scheme;
}
if (1 === preg_match(self::REGEXP_SCHEME, $scheme)) {
return strtolower($scheme);
}
throw new SyntaxError(sprintf("The scheme '%s' is invalid", $scheme));
} | [
"private",
"function",
"validate",
"(",
"$",
"scheme",
")",
":",
"?",
"string",
"{",
"$",
"scheme",
"=",
"$",
"this",
"->",
"filterComponent",
"(",
"$",
"scheme",
")",
";",
"if",
"(",
"null",
"===",
"$",
"scheme",
")",
"{",
"return",
"$",
"scheme",
... | Validate a scheme.
@throws SyntaxError if the scheme is invalid | [
"Validate",
"a",
"scheme",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Scheme.php#L58-L70 |
thephpleague/uri-components | src/Component/Scheme.php | Scheme.withContent | public function withContent($content): self
{
$content = $this->validate($this->filterComponent($content));
if ($content === $this->scheme) {
return $this;
}
return new self($content);
} | php | public function withContent($content): self
{
$content = $this->validate($this->filterComponent($content));
if ($content === $this->scheme) {
return $this;
}
return new self($content);
} | [
"public",
"function",
"withContent",
"(",
"$",
"content",
")",
":",
"self",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"this",
"->",
"filterComponent",
"(",
"$",
"content",
")",
")",
";",
"if",
"(",
"$",
"content",
"===",
"$",... | {@inheritdoc} | [
"{"
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Scheme.php#L91-L99 |
thephpleague/uri-components | src/Component/Query.php | Query.createFromParams | public static function createFromParams($params, string $separator = '&'): self
{
if ($params instanceof self) {
return new self(
http_build_query($params->toParams(), '', $separator, PHP_QUERY_RFC3986),
PHP_QUERY_RFC3986,
$separator
);
}
if ($params instanceof Traversable) {
$params = iterator_to_array($params, true);
}
if (is_object($params)) {
return new self(
http_build_query($params, '', $separator, PHP_QUERY_RFC3986),
PHP_QUERY_RFC3986,
$separator
);
}
if ([] === $params) {
return new self(null, PHP_QUERY_RFC3986, $separator);
}
if (is_array($params)) {
return new self(
http_build_query($params, '', $separator, PHP_QUERY_RFC3986),
PHP_QUERY_RFC3986,
$separator
);
}
throw new TypeError(sprintf('The parameter is expected to be iterable or an Object `%s` given', gettype($params)));
} | php | public static function createFromParams($params, string $separator = '&'): self
{
if ($params instanceof self) {
return new self(
http_build_query($params->toParams(), '', $separator, PHP_QUERY_RFC3986),
PHP_QUERY_RFC3986,
$separator
);
}
if ($params instanceof Traversable) {
$params = iterator_to_array($params, true);
}
if (is_object($params)) {
return new self(
http_build_query($params, '', $separator, PHP_QUERY_RFC3986),
PHP_QUERY_RFC3986,
$separator
);
}
if ([] === $params) {
return new self(null, PHP_QUERY_RFC3986, $separator);
}
if (is_array($params)) {
return new self(
http_build_query($params, '', $separator, PHP_QUERY_RFC3986),
PHP_QUERY_RFC3986,
$separator
);
}
throw new TypeError(sprintf('The parameter is expected to be iterable or an Object `%s` given', gettype($params)));
} | [
"public",
"static",
"function",
"createFromParams",
"(",
"$",
"params",
",",
"string",
"$",
"separator",
"=",
"'&'",
")",
":",
"self",
"{",
"if",
"(",
"$",
"params",
"instanceof",
"self",
")",
"{",
"return",
"new",
"self",
"(",
"http_build_query",
"(",
"... | Returns a new instance from the result of PHP's parse_str. | [
"Returns",
"a",
"new",
"instance",
"from",
"the",
"result",
"of",
"PHP",
"s",
"parse_str",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L66-L101 |
thephpleague/uri-components | src/Component/Query.php | Query.createFromPairs | public static function createFromPairs(iterable $pairs, string $separator = '&'): self
{
if ($pairs instanceof self) {
return $pairs->withSeparator($separator);
}
return new self(QueryString::build($pairs, $separator, PHP_QUERY_RFC3986), PHP_QUERY_RFC3986, $separator);
} | php | public static function createFromPairs(iterable $pairs, string $separator = '&'): self
{
if ($pairs instanceof self) {
return $pairs->withSeparator($separator);
}
return new self(QueryString::build($pairs, $separator, PHP_QUERY_RFC3986), PHP_QUERY_RFC3986, $separator);
} | [
"public",
"static",
"function",
"createFromPairs",
"(",
"iterable",
"$",
"pairs",
",",
"string",
"$",
"separator",
"=",
"'&'",
")",
":",
"self",
"{",
"if",
"(",
"$",
"pairs",
"instanceof",
"self",
")",
"{",
"return",
"$",
"pairs",
"->",
"withSeparator",
... | Returns a new instance from the result of QueryString::parse. | [
"Returns",
"a",
"new",
"instance",
"from",
"the",
"result",
"of",
"QueryString",
"::",
"parse",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L106-L113 |
thephpleague/uri-components | src/Component/Query.php | Query.has | public function has(string $key): bool
{
return isset(array_flip(array_column($this->pairs, 0))[$key]);
} | php | public function has(string $key): bool
{
return isset(array_flip(array_column($this->pairs, 0))[$key]);
} | [
"public",
"function",
"has",
"(",
"string",
"$",
"key",
")",
":",
"bool",
"{",
"return",
"isset",
"(",
"array_flip",
"(",
"array_column",
"(",
"$",
"this",
"->",
"pairs",
",",
"0",
")",
")",
"[",
"$",
"key",
"]",
")",
";",
"}"
] | Tell whether a parameter with a specific name exists.
@see https://url.spec.whatwg.org/#dom-urlsearchparams-has | [
"Tell",
"whether",
"a",
"parameter",
"with",
"a",
"specific",
"name",
"exists",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L254-L257 |
thephpleague/uri-components | src/Component/Query.php | Query.get | public function get(string $key)
{
foreach ($this->pairs as $pair) {
if ($key === $pair[0]) {
return $pair[1];
}
}
return null;
} | php | public function get(string $key)
{
foreach ($this->pairs as $pair) {
if ($key === $pair[0]) {
return $pair[1];
}
}
return null;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"key",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"pairs",
"as",
"$",
"pair",
")",
"{",
"if",
"(",
"$",
"key",
"===",
"$",
"pair",
"[",
"0",
"]",
")",
"{",
"return",
"$",
"pair",
"[",
"1",
"]... | Returns the first value associated to the given parameter.
If no value is found null is returned
@see https://url.spec.whatwg.org/#dom-urlsearchparams-get | [
"Returns",
"the",
"first",
"value",
"associated",
"to",
"the",
"given",
"parameter",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L266-L275 |
thephpleague/uri-components | src/Component/Query.php | Query.getAll | public function getAll(string $key): array
{
$filter = static function (array $pair) use ($key): bool {
return $key === $pair[0];
};
return array_column(array_filter($this->pairs, $filter), 1);
} | php | public function getAll(string $key): array
{
$filter = static function (array $pair) use ($key): bool {
return $key === $pair[0];
};
return array_column(array_filter($this->pairs, $filter), 1);
} | [
"public",
"function",
"getAll",
"(",
"string",
"$",
"key",
")",
":",
"array",
"{",
"$",
"filter",
"=",
"static",
"function",
"(",
"array",
"$",
"pair",
")",
"use",
"(",
"$",
"key",
")",
":",
"bool",
"{",
"return",
"$",
"key",
"===",
"$",
"pair",
... | Returns all the values associated to the given parameter as an array or all
the instance pairs.
If no value is found an empty array is returned
@see https://url.spec.whatwg.org/#dom-urlsearchparams-getall | [
"Returns",
"all",
"the",
"values",
"associated",
"to",
"the",
"given",
"parameter",
"as",
"an",
"array",
"or",
"all",
"the",
"instance",
"pairs",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L285-L292 |
thephpleague/uri-components | src/Component/Query.php | Query.withSeparator | public function withSeparator(string $separator): self
{
if ($separator === $this->separator) {
return $this;
}
$clone = clone $this;
$clone->separator = $this->filterSeparator($separator);
return $clone;
} | php | public function withSeparator(string $separator): self
{
if ($separator === $this->separator) {
return $this;
}
$clone = clone $this;
$clone->separator = $this->filterSeparator($separator);
return $clone;
} | [
"public",
"function",
"withSeparator",
"(",
"string",
"$",
"separator",
")",
":",
"self",
"{",
"if",
"(",
"$",
"separator",
"===",
"$",
"this",
"->",
"separator",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"clone",
"=",
"clone",
"$",
"this",
";"... | Returns an instance with a different separator.
This method MUST retain the state of the current instance, and return
an instance that contains the query component with a different separator | [
"Returns",
"an",
"instance",
"with",
"a",
"different",
"separator",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L315-L325 |
thephpleague/uri-components | src/Component/Query.php | Query.sort | public function sort(): self
{
if (count($this->pairs) === count(array_count_values(array_column($this->pairs, 0)))) {
return $this;
}
$pairs = array_merge(...array_values(array_reduce($this->pairs, [$this, 'reducePairs'], [])));
if ($pairs === $this->pairs) {
return $this;
}
$clone = clone $this;
$clone->pairs = $pairs;
return $clone;
} | php | public function sort(): self
{
if (count($this->pairs) === count(array_count_values(array_column($this->pairs, 0)))) {
return $this;
}
$pairs = array_merge(...array_values(array_reduce($this->pairs, [$this, 'reducePairs'], [])));
if ($pairs === $this->pairs) {
return $this;
}
$clone = clone $this;
$clone->pairs = $pairs;
return $clone;
} | [
"public",
"function",
"sort",
"(",
")",
":",
"self",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"pairs",
")",
"===",
"count",
"(",
"array_count_values",
"(",
"array_column",
"(",
"$",
"this",
"->",
"pairs",
",",
"0",
")",
")",
")",
")",
"{",
... | Sort the query string by offset, maintaining offset to data correlations.
This method MUST retain the state of the current instance, and return
an instance that contains the modified query
@see https://url.spec.whatwg.org/#dom-urlsearchparams-sort | [
"Sort",
"the",
"query",
"string",
"by",
"offset",
"maintaining",
"offset",
"to",
"data",
"correlations",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L348-L363 |
thephpleague/uri-components | src/Component/Query.php | Query.reducePairs | private function reducePairs(array $pairs, array $pair): array
{
$pairs[$pair[0]] = $pairs[$pair[0]] ?? [];
$pairs[$pair[0]][] = $pair;
return $pairs;
} | php | private function reducePairs(array $pairs, array $pair): array
{
$pairs[$pair[0]] = $pairs[$pair[0]] ?? [];
$pairs[$pair[0]][] = $pair;
return $pairs;
} | [
"private",
"function",
"reducePairs",
"(",
"array",
"$",
"pairs",
",",
"array",
"$",
"pair",
")",
":",
"array",
"{",
"$",
"pairs",
"[",
"$",
"pair",
"[",
"0",
"]",
"]",
"=",
"$",
"pairs",
"[",
"$",
"pair",
"[",
"0",
"]",
"]",
"??",
"[",
"]",
... | Reduce pairs to help sorting them according to their keys. | [
"Reduce",
"pairs",
"to",
"help",
"sorting",
"them",
"according",
"to",
"their",
"keys",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L368-L374 |
thephpleague/uri-components | src/Component/Query.php | Query.withoutDuplicates | public function withoutDuplicates(): self
{
if (count($this->pairs) === count(array_count_values(array_column($this->pairs, 0)))) {
return $this;
}
$pairs = array_reduce($this->pairs, [$this, 'removeDuplicates'], []);
if ($pairs === $this->pairs) {
return $this;
}
$clone = clone $this;
$clone->pairs = $pairs;
return $clone;
} | php | public function withoutDuplicates(): self
{
if (count($this->pairs) === count(array_count_values(array_column($this->pairs, 0)))) {
return $this;
}
$pairs = array_reduce($this->pairs, [$this, 'removeDuplicates'], []);
if ($pairs === $this->pairs) {
return $this;
}
$clone = clone $this;
$clone->pairs = $pairs;
return $clone;
} | [
"public",
"function",
"withoutDuplicates",
"(",
")",
":",
"self",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"pairs",
")",
"===",
"count",
"(",
"array_count_values",
"(",
"array_column",
"(",
"$",
"this",
"->",
"pairs",
",",
"0",
")",
")",
")",
... | Returns an instance without duplicate key/value pair.
This method MUST retain the state of the current instance, and return
an instance that contains the query component normalized by removing
duplicate pairs whose key/value are the same. | [
"Returns",
"an",
"instance",
"without",
"duplicate",
"key",
"/",
"value",
"pair",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L383-L398 |
thephpleague/uri-components | src/Component/Query.php | Query.removeDuplicates | private function removeDuplicates(array $pairs, array $pair): array
{
if (!in_array($pair, $pairs, true)) {
$pairs[] = $pair;
}
return $pairs;
} | php | private function removeDuplicates(array $pairs, array $pair): array
{
if (!in_array($pair, $pairs, true)) {
$pairs[] = $pair;
}
return $pairs;
} | [
"private",
"function",
"removeDuplicates",
"(",
"array",
"$",
"pairs",
",",
"array",
"$",
"pair",
")",
":",
"array",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"pair",
",",
"$",
"pairs",
",",
"true",
")",
")",
"{",
"$",
"pairs",
"[",
"]",
"=",
"$... | Adds a query pair only if it is not already present in a given array. | [
"Adds",
"a",
"query",
"pair",
"only",
"if",
"it",
"is",
"not",
"already",
"present",
"in",
"a",
"given",
"array",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L403-L410 |
thephpleague/uri-components | src/Component/Query.php | Query.withoutEmptyPairs | public function withoutEmptyPairs(): self
{
$pairs = array_filter($this->pairs, [$this, 'filterEmptyPair']);
if ($pairs === $this->pairs) {
return $this;
}
$clone = clone $this;
$clone->pairs = $pairs;
return $clone;
} | php | public function withoutEmptyPairs(): self
{
$pairs = array_filter($this->pairs, [$this, 'filterEmptyPair']);
if ($pairs === $this->pairs) {
return $this;
}
$clone = clone $this;
$clone->pairs = $pairs;
return $clone;
} | [
"public",
"function",
"withoutEmptyPairs",
"(",
")",
":",
"self",
"{",
"$",
"pairs",
"=",
"array_filter",
"(",
"$",
"this",
"->",
"pairs",
",",
"[",
"$",
"this",
",",
"'filterEmptyPair'",
"]",
")",
";",
"if",
"(",
"$",
"pairs",
"===",
"$",
"this",
"-... | Returns an instance without empty key/value where the value is the null value.
This method MUST retain the state of the current instance, and return
an instance that contains the query component normalized by removing
empty pairs.
A pair is considered empty if its value is equal to the null value | [
"Returns",
"an",
"instance",
"without",
"empty",
"key",
"/",
"value",
"where",
"the",
"value",
"is",
"the",
"null",
"value",
"."
] | train | https://github.com/thephpleague/uri-components/blob/215f10d66ad3463b1f31bdc1e1ab135e6911ad83/src/Component/Query.php#L421-L432 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.