_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q261400 | GeocoderStatus.getGeocoderStatus | test | public static function getGeocoderStatus()
{
return array(
self::ERROR,
self::INVALID_REQUEST,
self::OK,
self::OVER_QUERY_LIMIT,
self::REQUEST_DENIED,
self::UNKNOWN_ERROR,
self::ZERO_RESULTS,
);
} | php | {
"resource": ""
} |
q261401 | DirCache.get | test | public function get(string $primary_key, $sub_key, int $max_age = 0, array $args = [])
{
if (!isset($primary_key, $sub_key)) {
return null; // Not possible.
}
$file = $this->dir; // App-specific.
$file .= '/'.$this->subPath($primary_key, $sub_key, $args);
if (!is_file($file)) {
return null; // Cache miss.
} elseif ($max_age && time() - filemtime($file) > $max_age) {
return null; // Cache miss, too old.
} elseif (($cache = file_get_contents($file)) === false) {
return null; // Cache miss, read failure.
} elseif (($cache = unserialize($cache)) === false) {
return null; // Cache miss, unserialize failure.
}
if (isset($cache['x___value'], $cache['x___expires'])) {
if ($cache['x___expires'] && $cache['x___expires'] <= time()) {
return null; // Cache miss, value has expired.
} else {
return $cache['x___value']; // Cache hit!
}
} else { // e.g., Perhaps stored by an older version.
return null; // Cache miss, unexpected data.
}
} | php | {
"resource": ""
} |
q261402 | DirCache.subPath | test | protected function subPath(string $primary_key, $sub_key = null, array $args = []): string
{
if (!isset($sub_key)) {
if (empty($args['preserve_keys'])) {
extract($this->sha1Keys($primary_key, null, $args));
}
return $sub_path = $primary_key;
} else {
if (empty($args['preserve_keys'])) {
extract($this->sha1Keys($primary_key, $sub_key, $args));
}
$shard_id = $this->c::sha1ModShardId($primary_key.$sub_key);
return $sub_path = $primary_key.'/'.$shard_id.'/'.$sub_key;
}
} | php | {
"resource": ""
} |
q261403 | DirCache.sha1Keys | test | protected function sha1Keys(string $primary_key, $sub_key = null, array $args = []): array
{
if (!$primary_key || !$this->c::isSha1($primary_key)) {
$primary_key = sha1($primary_key);
}
if (!isset($sub_key)) {
return compact('primary_key');
} else {
if (!$sub_key || !$this->c::isSha1($sub_key)) {
$sub_key = sha1((string) $sub_key);
}
return compact('primary_key', 'sub_key');
}
} | php | {
"resource": ""
} |
q261404 | Di.get | test | public function get(string $class_name, array $args = [], bool $as_is = false)
{
return parent::get($as_is ? $class_name : $this->App->getClass($class_name), $args);
} | php | {
"resource": ""
} |
q261405 | RegexPatterns.match | test | public function match(string $string, $value, bool $collect_key_props = false)
{
if (!isset($string[0])) { // Empty?
return $collect_key_props ? [] : false;
}
$matching_key_props = []; // Initialize.
if (is_array($value) || is_object($value)) {
foreach ($value as $_key_prop => $_value) {
if (is_array($_value) || is_object($_value)) {
if (($_matching_key_props = $this->match($string, $_value, $collect_key_props))) {
if ($collect_key_props) {
$matching_key_props[] = [$_key_prop => $_matching_key_props];
} else {
return true;
}
}
} elseif (is_string($_value) && isset($_value[0])) {
if (@preg_match($_value, $string)) {
if ($collect_key_props) {
$matching_key_props[] = $_key_prop;
} else {
return true;
}
}
}
} // unset($_key_prop, $_value, $_matching_key_props);
} elseif (!$collect_key_props && is_string($value) && isset($value[0])) {
if (@preg_match($value, $string)) {
return true;
}
}
return $collect_key_props ? $matching_key_props : false;
} | php | {
"resource": ""
} |
q261406 | Template.get | test | public function get(string $file, string $dir = '', array $args = []): Classes\Core\Template
{
return $this->App->Di->get(Classes\Core\Template::class, compact('dir', 'file', 'args'));
} | php | {
"resource": ""
} |
q261407 | Password.strength | test | public function strength(string $password): int
{
$score = 0; // Initialize.
if (!isset($password[0])) {
return $score;
}
if (preg_match('/\p{N}/u', $password)) {
$score += 25; // Number.
}
if (preg_match('/\p{Ll}/u', $password)) {
$score += 25; // Lowercase.
}
if (preg_match('/\p{Lu}/u', $password)) {
$score += 25; // Uppercase.
}
if (preg_match('/[^\p{N}\p{Ll}\p{Lu}]/u', $password)) {
$score += 25; // Special symbol.
}
return $score;
} | php | {
"resource": ""
} |
q261408 | Sri.& | test | public function &checkProcess(string $url, string $sha1)
{
if (is_string($sri = &$this->cacheGet('sris', $sha1))) {
return $sri; // Cached this already.
} else { // Set in-process cache to `null`.
$sri = null; // Not in the cache.
return $sri; // By reference.
}
} | php | {
"resource": ""
} |
q261409 | Sri.checkMemcache | test | public function checkMemcache(string $url, string $sha1)
{
if (!$this->memcache_enabled) {
return $sri = null; // Not possible.
} elseif (is_string($sri = $this->c::memcacheGet('sris', $sha1))) {
return $sri; // Ideal; this avoids disk IO.
}
return $sri = null; // Not in the cache.
} | php | {
"resource": ""
} |
q261410 | Sri.checkMap | test | public function checkMap(string $url, string $sha1)
{
$this->map = $this->getMap();
if (isset($this->map[$url]['sri'])) {
return $sri = (string) $this->map[$url]['sri'];
}
if (mb_strpos($url, '//') !== 0) { // Should check `//`?
${'//'} = preg_replace('/^https?\:/ui', '', $url);
if (isset($this->map[${'//'}]['sri'])) {
return $sri = (string) $this->map[${'//'}]['sri'];
} // i.e., If a map entry covers all schemes.
}
return $sri = null; // Not in the map.
} | php | {
"resource": ""
} |
q261411 | Sri.checkMapCache | test | public function checkMapCache(string $url, string $sha1)
{
$this->map_cache = $this->getMapCache();
if (isset($this->map_cache[$url]['sri']) && $this->map_cache[$url]['time'] >= $this->cache_max_age) {
return $sri = (string) $this->map_cache[$url]['sri'];
}
if (mb_strpos($url, '//') !== 0) { // Should check `//`?
${'//'} = preg_replace('/^https?\:/ui', '', $url);
if (isset($this->map_cache[${'//'}]['sri']) && $this->map_cache[${'//'}]['time'] >= $this->cache_max_age) {
return $sri = (string) $this->map_cache[${'//'}]['sri'];
} // i.e., If a map entry covers all schemes.
}
return $sri = null; // Not in the map.
} | php | {
"resource": ""
} |
q261412 | Sri.checkContents | test | public function checkContents(string $url, string $sha1)
{
if (static::$content_checks >= $this->max_content_checks) {
return $sri = null; // Not possible at this time.
} // There is a limit on the number of checks per process.
if (mb_stripos($url, '//') === 0) {
$url = ($this->current_scheme ?: 'http').':'.$url;
} // Because we must have a scheme to do a lookup.
$args = [ // HTTP args.
'max_con_secs' => 2,
'max_stream_secs' => 6,
'max_stream_size' => $this::BYTES_IN_MB * 2,
]; // Most servers can download 1MB+ in this time.
++static::$content_checks; // Increment counter.
$response = $this->c::remoteResponse('GET::'.$url, $args);
if ($response->code !== 200) {
return $sri = ''; // Unable to determine.
// However, we do return an empty SRI in this case anyway.
// NOTE: This may (at times) return an empty SRI whenever
// there is a temporary connectivity issue that is resolved later.
// Rationale: If we chose not to cache failed responses, that could result in HTTP
// requests occurring over and over again, which is want we need to avoid at all costs.
// Therefore, if it fails, game is over until clearing the cache or adding a new map entry.
}
return $sri = 'sha384-'.base64_encode(hash('sha384', $response->body, true));
} | php | {
"resource": ""
} |
q261413 | Sri.cacheIt | test | public function cacheIt(string $url, string $sha1, string $sri)
{
$this->memcacheIt($url, $sha1, $sri);
$this->mapCacheIt($url, $sha1, $sri);
} | php | {
"resource": ""
} |
q261414 | Sri.memcacheIt | test | public function memcacheIt(string $url, string $sha1, string $sri)
{
if ($this->memcache_enabled) {
$this->c::memcacheSet('sris', $sha1, $sri, $this->cache_expires_in);
} // This is, by far, the fastest way.
} | php | {
"resource": ""
} |
q261415 | Sri.& | test | protected function &getMap(): array
{
if (!isset($this->map)) {
$this->map = []; // Define.
if (is_file($this->map_file)) {
$this->map = file_get_contents($this->map_file);
$this->map = json_decode($this->map, true);
$this->map = is_array($this->map) ? $this->map : [];
} // Only if file exists, otherwise empty array.
}
return $this->map;
} | php | {
"resource": ""
} |
q261416 | Sri.& | test | protected function &getMapCache(): array
{
if (!isset($this->map_cache)) {
$this->map_cache = []; // Define.
if (is_file($this->map_cache_file)) {
$this->map_cache = file_get_contents($this->map_cache_file);
$this->map_cache = json_decode($this->map_cache, true);
$this->map_cache = is_array($this->map_cache) ? $this->map_cache : [];
} // Only if file exists, otherwise empty array.
}
return $this->map_cache;
} | php | {
"resource": ""
} |
q261417 | Sri.isLocal | test | protected function isLocal(string $url)
{
if (mb_stripos($url, '//') === false) {
return true; // Relative.
} elseif ($this->current_host) {
return mb_stripos($url, '//'.$this->current_host.'/') !== false;
}
return null; // Unable to determine.
} | php | {
"resource": ""
} |
q261418 | Varz.isValid | test | public function isValid(string $var, bool $strict = true): bool
{
return (bool) preg_match($strict ? $this::VAR_STRICT_REGEX_VALID : $this::VAR_REGEX_VALID, $var);
} | php | {
"resource": ""
} |
q261419 | Varz.toAcronym | test | public function toAcronym(string $var, bool $strict = true): string
{
return $this->c::nameToAcronym($this->toName($var), $strict);
} | php | {
"resource": ""
} |
q261420 | Varz.toSlug | test | public function toSlug(string $var, bool $strict = true): string
{
$slug = $var; // Initialize.
$slug = mb_strtolower($this->c::forceAscii($slug));
$slug = preg_replace('/[^a-z0-9]+/u', '-', $slug);
$slug = $this->c::mbTrim($slug, '', '-');
if ($strict && $slug && !preg_match('/^[a-z]/u', $slug)) {
$slug = 'x'.$slug; // Force `^[a-z]`.
}
return $slug;
} | php | {
"resource": ""
} |
q261421 | Varz.toCamelCase | test | public function toCamelCase(string $var, bool $strict = true): string
{
$var = mb_strtolower($this->c::forceAscii($var));
$var = preg_replace('/[^a-z0-9]+/u', '_', $var);
$var = $this->c::mbTrim($var, '', '_');
if ($strict && $var && !preg_match('/^[a-z]/u', $var)) {
$var = 'x'.$var; // Force `^[a-z]`.
}
return $camelCase = $var ? preg_replace_callback('/_(.)/u', function (array $m): string {
return mb_strtoupper($m[1]); // e.g., `_x` becomes `X` for camelCase.
}, $var) : $var; // Converts variable into camelCase variable.
} | php | {
"resource": ""
} |
q261422 | SizeHelper.render | test | public function render(Size $size)
{
if ($size->hasUnits()) {
return sprintf(
'%s = new google.maps.Size(%s, %s, "%s", "%s");'.PHP_EOL,
$size->getJavascriptVariable(),
$size->getWidth(),
$size->getHeight(),
$size->getWidthUnit(),
$size->getHeightUnit()
);
}
return sprintf(
'%s = new google.maps.Size(%s, %s);'.PHP_EOL,
$size->getJavascriptVariable(),
$size->getWidth(), $size->getHeight()
);
} | php | {
"resource": ""
} |
q261423 | Email.isRoleBased | test | public function isRoleBased(string $email): bool
{
$user = mb_strtolower(mb_strstr($email, '@', true));
$user = str_replace(['-', '_', '.'], '', $user);
if (!is_null($is = &$this->cacheKey(__FUNCTION__, $user))) {
return $is; // Cached this already.
}
if (in_array($user, $this::EMAIL_ROLE_BASED_STRINGS, true)) {
return $is = true;
}
foreach ($this::EMAIL_ROLE_BASED_REGEX_FRAGS as $_regex_frag) {
if (preg_match('/^'.$_regex_frag.'$/ui', $user)) {
return $is = true;
}
} // unset($_regex_frag); // Housekeeping.
return $is = false;
} | php | {
"resource": ""
} |
q261424 | Email.parseAddresses | test | public function parseAddresses($value, bool $strict = false): array
{
$addresses = []; // Initialize.
if (is_array($value) || is_object($value)) {
foreach ($value as $_key => $_value) {
$addresses = array_merge($addresses, $this->parseAddresses($_value, $strict));
} // unset($_key, $_value); // Housekeeping.
return $addresses;
}
$string = (string) $value;
$delimiter = mb_strpos($string, ';') !== false ? ';' : ',';
$regex_delimitation_splitter = '/'.$delimiter.'+/u'; // `$this->c::escRegex()` unnecessary.
$possible_addresses = preg_split($regex_delimitation_splitter, $string, -1, PREG_SPLIT_NO_EMPTY);
$possible_addresses = $this->c::mbTrim($possible_addresses);
foreach ($possible_addresses as $_address) {
if (!$_address || mb_strpos($_address, '@', 1) === false) {
continue; // NOT an email address.
}
if (mb_strpos($_address, '<') !== false && preg_match('/(?:"(?<name>[^"]+?)"\s*)?\<(?<email>.+?)\>/u', $_address, $_m)) {
if ($_m['email'] && mb_strpos($_m['email'], '@', 1) !== false && (!$strict || $this->isValid($_m['email']))) {
$_email = mb_strtolower($_m['email']);
$_name = !empty($_m['name']) ? $_m['name'] : '';
$_fname = $_name ? $this->c::fnameIn($_name) : '';
$_lname = $_name ? $this->c::lnameIn($_name) : '';
$addresses[$_email] = (object) ['name' => $_name, 'fname' => $_fname, 'lname' => $_lname, 'email' => $_email];
}
} elseif (!$strict || $this->isValid($_address)) {
$_email = mb_strtolower($_address);
$addresses[$_email] = (object) ['name' => '', 'fname' => '', 'lname' => '', 'email' => $_email];
}
} // unset($_address, $_m, $_email, $_name, $_fname, $_lname); // Housekeeping.
return $addresses;
} | php | {
"resource": ""
} |
q261425 | Email.parseHeaders | test | protected function parseHeaders($value, array $refs = [], bool $strict = false): array
{
$headers = []; // Initialize parsed headers.
foreach ($this->c::parseHeaders($value) as $_header => $_value) {
switch ($_header) { // Maybe populate refs.
case 'from':
if (array_key_exists('from_name', $refs) && array_key_exists('from_email', $refs)) {
if (($_from_addresses = $this->parseAddresses($_value, $strict))) {
$_from = array_shift($_from_addresses);
$refs['from_name'] = $this->c::mbTrim($_from->fname.' '.$_from->lname);
$refs['from_email'] = $_from->email; // By reference.
} // unset($_from_addresses, $_from);
} else {
$headers[$_header] = $_value;
}
break; // Break switch.
case 'reply-to':
if (array_key_exists('reply_to_name', $refs) && array_key_exists('reply_to_email', $refs)) {
if (($_reply_to_addresses = $this->parseAddresses($_value, $strict))) {
$_reply_to = array_shift($_reply_to_addresses);
$refs['reply_to_name'] = $this->c::mbTrim($_reply_to->fname.' '.$_reply_to->lname);
$refs['reply_to_email'] = $_reply_to->email; // By reference.
} // unset($_reply_to_addresses, $_reply_to);
} else {
$headers[$_header] = $_value;
}
break; // Break switch.
case 'cc':
case 'bcc':
if (array_key_exists('recipients', $refs)) {
if (($_recipient_addresses = $this->parseAddresses($_value, $strict))) {
$refs['recipients'] = array_merge($refs['recipients'], $_recipient_addresses);
$refs['recipients'] = array_unique($refs['recipients']);
} // unset($_recipient_addresses);
} else {
$headers[$_header] = $_value;
}
break; // Break switch.
default: // Everything else (default).
$headers[$_header] = $_value;
break; // Break switch.
}
}
return $headers;
} | php | {
"resource": ""
} |
q261426 | Email.parseAttachments | test | protected function parseAttachments($value): array
{
$attachments = []; // Initialize.
if (is_array($value) || is_object($value)) {
foreach ($value as $_key => $_value) {
$attachments = array_merge($attachments, $this->parseAttachments($_value));
} // unset($_key, $_value); // Housekeeping.
return $attachments;
}
$string = (string) $value;
if (is_file($string)) {
$attachments[$string] = $string;
}
return $attachments;
} | php | {
"resource": ""
} |
q261427 | Tool.parseContentTypeToRepresentation | test | public static function parseContentTypeToRepresentation($contentType)
{
$matches = array();
preg_match('/^application\/(.*)\+json; charset=utf-8$/im', $contentType, $matches);
if (count($matches) == 2) {
return $matches[1];
}
return false;
} | php | {
"resource": ""
} |
q261428 | Tool.parseRepresentationToClass | test | public static function parseRepresentationToClass($inputRepresentation)
{
$version = substr($inputRepresentation, -2);
$representation = substr($inputRepresentation, 0, -3);
switch (substr($representation, 0, 7)) {
case "vnd.ccp": // EVE
$data = explode(".", $representation);
array_shift($data);
array_shift($data);
array_shift($data);
$classname = '\Perry\Representation\Eve\\'.$version.'\\'.$data[0];
break;
case "net.3rd": // OldApi
$data = explode(".", $representation);
array_shift($data);
array_shift($data);
array_shift($data);
$classname = '\Perry\Representation\OldApi\\'.$version.'\\'.$data[0];
if (count($data) > 1) {
$classname .= '\\'.$data[1];
}
break;
default:
throw new \Exception("wtf, what representation is this? ".$inputRepresentation);
}
return $classname;
} | php | {
"resource": ""
} |
q261429 | Percent.diff | test | public function diff(float $from, float $to, int $precision = 0, bool $format_string = false)
{
if (!$from) {
++$from;
++$to;
} // Stop division by `0`.
$precision = max(0, $precision);
$percent = ($to - $from) / $from * 100;
if ($precision) {
$percent = (float) number_format($percent, $precision, '.', '');
} else {
$percent = (int) $percent;
}
if ($format_string) { // e.g., add a prefix/suffix?
$percent = $percent > 0 ? '+'.$percent.'%' : $percent.'%';
}
return $percent;
} | php | {
"resource": ""
} |
q261430 | Base64.urlSafeEncode | test | public function urlSafeEncode(string $string, array $url_unsafe_chars = ['+', '/'], array $url_safe_chars = ['-', '_'], string $trim_padding_chars = '='): string
{
if (!is_string($base64_url_safe = base64_encode($string))) {
throw $this->c::issue('Base64 encoding failure.');
}
$base64_url_safe = str_replace($url_unsafe_chars, $url_safe_chars, $base64_url_safe);
$base64_url_safe = isset($trim_padding_chars[0]) ? rtrim($base64_url_safe, $trim_padding_chars) : $base64_url_safe;
return $base64_url_safe;
} | php | {
"resource": ""
} |
q261431 | Base64.urlSafeDecode | test | public function urlSafeDecode(string $base64_url_safe, array $url_unsafe_chars = ['+', '/'], array $url_safe_chars = ['-', '_'], string $trim_padding_chars = '='): string
{
$string = isset($trim_padding_chars[0]) ? rtrim($base64_url_safe, $trim_padding_chars) : $base64_url_safe;
$string = isset($trim_padding_chars[0]) ? str_pad($string, strlen($string) % 4, '=', STR_PAD_RIGHT) : $string;
$string = str_replace($url_safe_chars, $url_unsafe_chars, $string);
if (!is_string($string = base64_decode($string, true))) {
throw $this->c::issue('Base64 decoding failure.');
}
return $string;
} | php | {
"resource": ""
} |
q261432 | Nonce.create | test | public function create(string $action = null, callable $callback = null): string
{
$Nonce = (object) [
'token' => $this->c::uuidV4(),
'action' => mb_strtolower($action ?? ''),
'expire_time' => time() + $this::SECONDS_IN_DAY,
'used' => false, // Unused on creation.
];
if (isset($callback)) {
$callback($Nonce);
return $Nonce->token;
}
if ($this->c::isActiveSession()) {
$_SESSION['_nonce'] = $_SESSION['_nonce'] ?? [];
$this->c::arrayUnshiftAssoc($_SESSION['_nonce'], $Nonce->token, $Nonce);
$_SESSION['_nonce'] = array_slice($_SESSION['_nonce'], 0, 64, true);
return $Nonce->token;
}
throw $this->c::issue('No storage handler.');
} | php | {
"resource": ""
} |
q261433 | Nonce.input | test | public function input(string $action = null, callable $callback = null): string
{
$token = $this->create($action, $callback);
return '<input type="hidden" name="_nonce" value="'.$this->c::escAttr($token).'" />';
} | php | {
"resource": ""
} |
q261434 | Nonce.verify | test | public function verify(string $action = null, string $token = null, callable $callback = null): bool
{
if (!isset($token)) {
$token = (string) $_REQUEST['_nonce'];
} // Defaults to current request.
$action = mb_strtolower($action ?? '');
$token = mb_strtolower($token);
if (isset($callback)) {
return $callback($action, $token);
}
if ($this->c::isActiveSession()) {
if (!isset($_SESSION['_nonce'][$token])) {
return false; // Bad token.
} // Reference Nonce in session.
$Nonce = &$_SESSION['_nonce'][$token];
if ($action !== $Nonce->action) {
return false;
} elseif (time() >= $Nonce->expire_time) {
return false;
} elseif ($Nonce->used) {
return false;
}
return $Nonce->used = true;
}
throw $this->c::issue('No verification handler.');
} | php | {
"resource": ""
} |
q261435 | DistanceMatrixResponse.setOrigins | test | public function setOrigins(array $origins)
{
$this->origins = array();
foreach ($origins as $origin) {
$this->addOrigin($origin);
}
} | php | {
"resource": ""
} |
q261436 | Time.humanDiff | test | public function humanDiff(int $from, int $to = null, string $format = ''): string
{
$to = $to ?? time();
$diff = (int) abs($to - $from);
if ($format !== 'abbrev' && $format !== 'default') {
$format = 'default'; // Must be valid.
}
if ($diff < $this::SECONDS_IN_MINUTE) {
$diff = max(1, $diff);
$fmat['abbrev'] = ['%1$ss', '%1$ss'];
$fmat['default'] = ['%1$s sec', '%1$s secs'];
} elseif ($diff < $this::SECONDS_IN_HOUR) {
$diff = max(1, round($diff / $this::SECONDS_IN_MINUTE));
$fmat['abbrev'] = ['%1$sm', '%1$sm'];
$fmat['default'] = ['%1$s min', '%1$s mins'];
} elseif ($diff < $this::SECONDS_IN_DAY) {
$diff = max(1, round($diff / $this::SECONDS_IN_HOUR));
$fmat['abbrev'] = ['%1$sh', '%1$sh'];
$fmat['default'] = ['%1$s hour', '%1$s hours'];
} elseif ($diff < $this::SECONDS_IN_WEEK) {
$diff = max(1, round($diff / $this::SECONDS_IN_DAY));
$fmat['abbrev'] = ['%1$sd', '%1$sd'];
$fmat['default'] = ['%1$s day', '%1$s days'];
} elseif ($diff < $this::SECONDS_IN_WEEK * 4) {
$diff = max(1, round($diff / $this::SECONDS_IN_WEEK));
$fmat['abbrev'] = ['%1$sw', '%1$sw'];
$fmat['default'] = ['%1$s week', '%1$s weeks'];
} elseif ($diff < $this::SECONDS_IN_YEAR) {
$diff = max(1, round($diff / ($this::SECONDS_IN_WEEK * 4)));
$fmat['abbrev'] = ['%1$smo', '%1$smo'];
$fmat['default'] = ['%1$s month', '%1$s months'];
} else {
$diff = max(1, round($diff / $this::SECONDS_IN_YEAR));
$fmat['abbrev'] = ['%1$sy', '%1$sy'];
$fmat['default'] = ['%1$s year', '%1$s years'];
}
return sprintf(_n($fmat[$format][0], $fmat[$format][1], $diff), $diff);
} | php | {
"resource": ""
} |
q261437 | FilePool.getItems | test | public function getItems(array $keys)
{
$result = array();
foreach ($keys as $key) {
$result[$key] = $this->getItem($key);
}
return $result;
} | php | {
"resource": ""
} |
q261438 | MarkerHelper.render | test | public function render(Marker $marker, Map $map = null)
{
$this->jsonBuilder
->reset()
->setValue('[position]', $marker->getPosition()->getJavascriptVariable(), false);
if ($map !== null) {
$this->jsonBuilder->setValue('[map]', $map->getJavascriptVariable(), false);
}
if ($marker->hasAnimation()) {
$this->jsonBuilder->setValue('[animation]', $this->animationHelper->render($marker->getAnimation()), false);
}
if ($marker->hasIcon()) {
$this->jsonBuilder->setValue('[icon]', $marker->getIcon()->getJavascriptVariable(), false);
}
if ($marker->hasShadow()) {
$this->jsonBuilder->setValue('[shadow]', $marker->getShadow()->getJavascriptVariable(), false);
}
if ($marker->hasShape()) {
$this->jsonBuilder->setValue('[shape]', $marker->getShape()->getJavascriptVariable(), false);
}
$this->jsonBuilder->setValues($marker->getOptions());
return sprintf(
'%s = new google.maps.Marker(%s);'.PHP_EOL,
$marker->getJavascriptVariable(),
$this->jsonBuilder->build()
);
} | php | {
"resource": ""
} |
q261439 | Builder.build | test | public function build($build=false)
{
if($build){
header('Content-Type: application/json');
echo json_encode($this->json);
return true;
}
return json_encode($this->json);
} | php | {
"resource": ""
} |
q261440 | MarkerShapeHelper.render | test | public function render(MarkerShape $markerShape)
{
return sprintf(
'%s = new google.maps.MarkerShape(%s);'.PHP_EOL,
$markerShape->getJavascriptVariable(),
json_encode(array('type' => $markerShape->getType(), 'coords' => $markerShape->getCoordinates()))
);
} | php | {
"resource": ""
} |
q261441 | ScaleControlStyleHelper.render | test | public function render($scaleControlStyle)
{
switch ($scaleControlStyle) {
case ScaleControlStyle::DEFAULT_:
return sprintf('google.maps.ScaleControlStyle.%s', strtoupper($scaleControlStyle));
default:
throw HelperException::invalidScaleControlStyle();
}
} | php | {
"resource": ""
} |
q261442 | Slug.isValid | test | public function isValid(string $slug, bool $strict = true): bool
{
return (bool) preg_match($strict ? $this::SLUG_STRICT_REGEX_VALID : $this::SLUG_REGEX_VALID, $slug);
} | php | {
"resource": ""
} |
q261443 | Slug.isReserved | test | public function isReserved(string $slug): bool
{
$slug = mb_strtolower($slug);
$slug = str_replace(['-', '_', '.'], '', $slug);
if (($is = &$this->cacheKey(__FUNCTION__, $slug)) !== null) {
return $is; // Cached this already.
}
if (mb_strlen($slug) < 3) {
return $is = true;
} elseif (in_array($slug, $this::SLUG_RESERVED_STRINGS, true)) {
return $is = true;
}
foreach ($this::SLUG_RESERVED_REGEX_FRAGS as $_regex_frag) {
if (preg_match('/^'.$_regex_frag.'$/ui', $slug)) {
return $is = true;
}
} // unset($_regex_frag); // Housekeeping.
return $is = false;
} | php | {
"resource": ""
} |
q261444 | Slug.toName | test | public function toName(string $slug): string
{
$name = $slug; // Initialize.
$name = preg_replace('/[^\p{L}\p{N}]+/u', ' ', $name);
$name = $this->c::mbUcWords($name);
$name = $this->c::mbTrim($name);
return $name;
} | php | {
"resource": ""
} |
q261445 | Slug.toVar | test | public function toVar(string $slug, bool $strict = true): string
{
$var = $slug; // Initialize.
$var = mb_strtolower($this->c::forceAscii($var));
$var = preg_replace('/[^a-z0-9]+/u', '_', $var);
$var = $this->c::mbTrim($var, '', '_');
if ($strict && $var && !preg_match('/^[a-z]/u', $var)) {
$var = 'x'.$var; // Force `^[a-z]`.
}
return $var;
} | php | {
"resource": ""
} |
q261446 | Polyline.setCoordinates | test | public function setCoordinates($coordinates)
{
$this->coordinates = array();
foreach ($coordinates as $coordinate) {
$this->addCoordinate($coordinate);
}
} | php | {
"resource": ""
} |
q261447 | ManagerImpl.store | test | public function store()
{
if (empty($cacheFile = $this->cacheFile())) {
return;
}
file_put_contents(
base_path($cacheFile),
json_encode($this->all()->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
} | php | {
"resource": ""
} |
q261448 | ManagerImpl.all | test | public function all(): Repository
{
if ($this->repository === null && !$this->restore()) {
$this->repository = new Repository();
$this->scan();
}
return $this->repository;
} | php | {
"resource": ""
} |
q261449 | Template.parse | test | public function parse(array $vars = []): string
{
++$this->parsed; // Parsing now.
if ($this->ext === 'php') {
$_this = $this; // `$this` in symbol table.
// ↑ Strange magic makes it possible for `$this` to be used from
// inside the template file also. We just need to reference it here.
// See: <http://stackoverflow.com/a/4994799/1219741>
unset($_this, $vars['this']); // Avoid conflicts.
$this->vars = $vars; // Set current template variables.
unset($vars); // Don't include as a part of template variables.
extract($this->vars); // Extract for template.
ob_start(); // Output buffer.
require $this->dir.'/'.$this->file;
return ob_get_clean();
} else {
return file_get_contents($this->dir.'/'.$this->file);
}
} | php | {
"resource": ""
} |
q261450 | Template.setVars | test | protected function setVars(array $defaults, array ...$vars): array
{
return $this->vars = array_replace_recursive($defaults, $this->vars, ...$vars);
} | php | {
"resource": ""
} |
q261451 | Template.hasParent | test | protected function hasParent(string $file = null): bool
{
if (isset($file)) {
return in_array($file, $this->parents, true);
}
return !empty($this->parents);
} | php | {
"resource": ""
} |
q261452 | Template.parentVars | test | protected function parentVars(string $file = null): array
{
if (isset($file)) {
return $this->parent_vars[$file] ?? [];
}
$closest_ancestor_vars = end($this->parent_vars);
return $parent_vars = $closest_ancestor_vars ?: [];
} | php | {
"resource": ""
} |
q261453 | Template.get | test | protected function get(string $new_child_file, array $new_child_vars = [], string $new_child_dir = ''): string
{
$new_child_parents = array_merge($this->parents, [$this->file]);
$new_child_parent_vars = array_merge($this->parent_vars, [$this->file => &$this->vars]);
$new_child_Template = $this->c::getTemplate($new_child_file, $new_child_dir, [
'parents' => $new_child_parents,
'parent_vars' => $new_child_parent_vars,
'Route' => $this->Route,
]);
// Variables from the closest ancestors take precedence over further/older ancestors.
// File-specific variables in those ancestors take precedence over those that aren't file-specific.
foreach (array_reverse($new_child_parent_vars, true) as $_parent_file => $_parent_vars) {
if (isset($_parent_vars[$new_child_file]) && is_array($_parent_vars[$new_child_file])) {
$new_child_vars = array_replace_recursive($_parent_vars[$new_child_file], $new_child_vars);
}
$_parent_vars_not_file_specific = array_diff_key($_parent_vars, $new_child_parent_vars + [$new_child_file => 0]);
$new_child_vars = array_replace_recursive($_parent_vars_not_file_specific, $new_child_vars);
} // unset($_parent_file, $_parent_vars, $_parent_vars_not_file_specific); // Housekeeping.
return $new_child_Template->parse($new_child_vars);
} | php | {
"resource": ""
} |
q261454 | SeedCommand.getOptions | test | protected function getOptions()
{
$options = parent::getOptions();
foreach ($options as &$option) {
if ($option[0] === 'class') {
$option[4] = DatabaseSeeder::class;
}
}
return $options;
} | php | {
"resource": ""
} |
q261455 | RotateControlHelper.render | test | public function render(RotateControl $rotateControl)
{
return $this->jsonBuilder
->reset()
->setValue('[position]', $this->controlPositionHelper->render($rotateControl->getControlPosition()), false)
->build();
} | php | {
"resource": ""
} |
q261456 | HtmlEntities.encode | test | public function encode($value, bool $double_encode = false, int $flags = null)
{
if (is_array($value) || is_object($value)) {
foreach ($value as $_key => &$_value) {
$_value = $this->encode($_value, $double_encode, $flags);
} // unset($_key, $_value); // Housekeeping.
return $value;
}
if (!($string = (string) $value)) {
return $string; // Nothing to do.
}
if (!isset($flags)) {
$flags = ENT_HTML5 | ENT_QUOTES | ENT_SUBSTITUTE;
}
return htmlspecialchars($string, $flags, 'UTF-8', $double_encode);
} | php | {
"resource": ""
} |
q261457 | HtmlEntities.decode | test | public function decode($value, int $flags = null)
{
if (is_array($value) || is_object($value)) {
foreach ($value as $_key => &$_value) {
$_value = $this->decode($_value, $flags);
} // unset($_key, $_value);
return $value;
}
if (!($string = (string) $value)) {
return $string; // Nothing to do.
}
if (!isset($flags)) {
$flags = ENT_HTML5 | ENT_QUOTES;
}
return html_entity_decode($string, $flags, 'UTF-8');
} | php | {
"resource": ""
} |
q261458 | ModuleController.callAction | test | public function callAction($method, $parameters)
{
if (method_exists($this, 'before')) {
$this->app->call([$this, 'before'], ['method' => $method]);
}
$response = parent::callAction($method, $parameters);
if ($this->cache > 0) {
$response = Route::prepareResponse(App::make('request'), $response);
$response->headers->addCacheControlDirective('public');
$response->headers->addCacheControlDirective('max-age', (int)$this->cache);
}
return $response;
} | php | {
"resource": ""
} |
q261459 | KMLLayerHelper.render | test | public function render(KMLLayer $kmlLayer, Map $map)
{
$this->jsonBuilder
->reset()
->setValue('[map]', $map->getJavascriptVariable(), false)
->setValues($kmlLayer->getOptions());
return sprintf(
'%s = new google.maps.KmlLayer("%s", %s);'.PHP_EOL,
$kmlLayer->getJavascriptVariable(),
$kmlLayer->getUrl(),
$this->jsonBuilder->build()
);
} | php | {
"resource": ""
} |
q261460 | Memcache.get | test | public function get(string $primary_key, $sub_key)
{
if (!$this->enabled) {
return; // Not possible.
//
} elseif (!($key = $this->key($primary_key, $sub_key))) {
return; // Fail; e.g., race condition.
}
$value = $this->Pool->get($key); // Possibly `false`.
// See: <http://php.net/manual/en/memcached.get.php#92275>
if ($this->Pool->getResultCode() === \Memcached::RES_SUCCESS) {
return $value; // Return the value.
}
} | php | {
"resource": ""
} |
q261461 | Memcache.set | test | public function set(string $primary_key, $sub_key, $value, int $expires_in = 0): bool
{
if (!$this->enabled) {
return false; // Not possible.
}
$expires_in = max(0, $expires_in);
$expires = $expires_in ? time() + $expires_in : 0;
if (!($key = $this->key($primary_key, $sub_key))) {
return false; // Fail; e.g., race condition.
//
} elseif ($value === null || is_resource($value)) {
throw $this->c::issue('Incompatible data type.');
}
do { // Avoid race issues.
$cas = $cas ?? 0;
$attempts = $attempts ?? 0;
++$attempts; // Counter.
$this->Pool->get($key, null, $cas);
if ($this->Pool->getResultCode() === \Memcached::RES_NOTFOUND) {
if ($this->Pool->add($key, $value, $expires)) {
return true; // All good; stop here.
}
} elseif ($this->Pool->cas($cas, $key, $value, $expires)) {
return true; // All good; stop here.
}
$result_code = $this->Pool->getResultCode();
//
} while ($attempts < $this::MAX_WRITE_ATTEMPTS // Give up after X attempts.
&& ($result_code === \Memcached::RES_NOTSTORED || $result_code === \Memcached::RES_DATA_EXISTS));
return false; // Fail; e.g., race condition or unexpected error.
} | php | {
"resource": ""
} |
q261462 | Memcache.clear | test | public function clear(string $primary_key, $sub_key = null, int $delay = 0): bool
{
if (!$this->enabled) {
return false; // Not possible.
}
if (!isset($sub_key)) {
$key = $this->nspKey($primary_key);
} else {
$key = $this->key($primary_key, $sub_key);
}
return $key && $this->Pool->delete($key, $delay);
} | php | {
"resource": ""
} |
q261463 | Memcache.key | test | protected function key(string $primary_key, $sub_key): string
{
if (!$this->enabled) {
return ''; // Not possible.
//
} elseif (!($namespaced_primary_key = $this->nspKey($primary_key))) {
return ''; // Not possible; e.g., empty key.
}
$namespaced_primary_key_uuid = ''; // Initialize.
do { // Avoid race issues.
$attempts = $attempts ?? 0;
++$attempts; // Counter.
if (($existing_namespaced_primary_key_uuid = (string) $this->Pool->get($namespaced_primary_key))) {
$namespaced_primary_key_uuid = $existing_namespaced_primary_key_uuid;
break; // All good; stop here.
}
if (!isset($new_namespaced_primary_key_uuid)) {
$new_namespaced_primary_key_uuid = $this->c::uuidV4();
}
if ($this->Pool->add($namespaced_primary_key, $new_namespaced_primary_key_uuid)) {
$namespaced_primary_key_uuid = $new_namespaced_primary_key_uuid;
break; // All good; stop here.
}
$result_code = $this->Pool->getResultCode();
//
} while ($attempts < $this::MAX_WRITE_ATTEMPTS && $result_code === \Memcached::RES_NOTSTORED);
if (!$namespaced_primary_key_uuid) {
return ''; // Failure; e.g., race condition.
}
$sub_key = (string) $sub_key;
$namespaced_primary_key_uuid_prefix = $namespaced_primary_key_uuid.'\\';
$namespaced_key = $namespaced_primary_key_uuid_prefix.$sub_key;
if (isset($namespaced_key[251])) {
throw $this->c::issue(sprintf('Sub key too long; %1$s bytes max.', 250 - strlen($namespaced_primary_key_uuid_prefix)));
}
return $namespaced_key;
} | php | {
"resource": ""
} |
q261464 | Memcache.nspKey | test | protected function nspKey(string $primary_key): string
{
if (!$this->enabled) {
return ''; // Not possible.
//
} elseif (!isset($primary_key[0])) {
return ''; // Not possible.
}
$namespace_prefix = 'x___'.$this->namespace.'\\';
$namespaced_primary_key = $namespace_prefix.$primary_key;
if (isset($namespaced_primary_key[251])) {
throw $this->c::issue(sprintf('Primary key too long; %1$s bytes max.', 250 - strlen($namespace_prefix)));
}
return $namespaced_primary_key;
} | php | {
"resource": ""
} |
q261465 | Memcache.serversDiffer | test | protected function serversDiffer(): bool
{
if (!$this->enabled) {
return false; // Not possible.
}
$active_servers = []; // Initialize.
foreach ($this->Pool->getServerList() as $_server) {
$active_servers[$_server['host'].':'.$_server['port']] = $_server;
} // unset($_server); // Housekeeping.
if (count($this->servers) !== count($active_servers)) {
return true; // They definitely differ.
}
foreach ($this->servers as $_key => $_server) {
if (!isset($active_servers[$_key])) {
return true;
} // unset($_key, $_server);
}
foreach ($active_servers as $_key => $_server) {
if (!isset($this->servers[$_key])) {
return true;
} // unset($_key, $_server);
}
return false;
} | php | {
"resource": ""
} |
q261466 | Memcache.maybeAddServerConnections | test | protected function maybeAddServerConnections()
{
if (!$this->enabled) {
return; // Not possible.
}
if ($this->serversDiffer()) {
$this->Pool->quit();
$this->Pool->resetServerList();
$this->Pool->setOption(\Memcached::OPT_NO_BLOCK, true);
$this->Pool->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
if (\Memcached::HAVE_IGBINARY) { // Size and speed gains.
$this->Pool->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
$this->Pool->setOption(\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_IGBINARY);
}
$this->Pool->setOption(\Memcached::OPT_CONNECT_TIMEOUT, 1000);
$this->Pool->setOption(\Memcached::OPT_POLL_TIMEOUT, 1000);
$this->Pool->setOption(\Memcached::OPT_RETRY_TIMEOUT, 1);
$this->Pool->setOption(\Memcached::OPT_SEND_TIMEOUT, 1000000);
$this->Pool->setOption(\Memcached::OPT_RECV_TIMEOUT, 1000000);
$this->Pool->addServers($this->servers);
}
} | php | {
"resource": ""
} |
q261467 | AutocompleteHelper.renderHtmlContainer | test | public function renderHtmlContainer(Autocomplete $autocomplete)
{
$inputAttributes = $autocomplete->getInputAttributes();
$inputAttributes['id'] = $autocomplete->getInputId();
if ($autocomplete->hasValue()) {
$inputAttributes['value'] = $autocomplete->getValue();
}
$htmlAttributes = array();
foreach ($inputAttributes as $attribute => $value) {
$htmlAttributes[] = sprintf('%s="%s"', $attribute, $value);
}
return sprintf('<input %s />'.PHP_EOL, implode(' ', $htmlAttributes));
} | php | {
"resource": ""
} |
q261468 | AutocompleteHelper.renderJavascripts | test | public function renderJavascripts(Autocomplete $autocomplete)
{
$output = array();
if (!$this->apiHelper->isLoaded() && !$autocomplete->isAsync()) {
$output[] = $this->apiHelper->render($autocomplete->getLanguage(), array('places'));
}
$output[] = '<script type="text/javascript">'.PHP_EOL;
if ($autocomplete->isAsync()) {
$output[] = 'function load_ivory_google_place () {'.PHP_EOL;
}
if ($autocomplete->hasBound()) {
if (!$autocomplete->getBound()->hasCoordinates()) {
throw HelperException::invalidAutocompleteBound();
}
$output[] = $this->coordinateHelper->render($autocomplete->getBound()->getSouthWest());
$output[] = $this->coordinateHelper->render($autocomplete->getBound()->getNorthEast());
$output[] = $this->boundHelper->render($autocomplete->getBound());
}
$output[] = $this->renderAutocomplete($autocomplete);
if ($autocomplete->isAsync()) {
$output[] = '}'.PHP_EOL;
}
$output[] = '</script>'.PHP_EOL;
if (!$this->apiHelper->isLoaded() && $autocomplete->isAsync()) {
$output[] = $this->apiHelper->render(
$autocomplete->getLanguage(),
array('places'),
'load_ivory_google_place'
);
}
return implode('', $output);
} | php | {
"resource": ""
} |
q261469 | AutocompleteHelper.renderAutocomplete | test | public function renderAutocomplete(Autocomplete $autocomplete)
{
$this->jsonBuilder->reset();
if ($autocomplete->hasTypes()) {
$this->jsonBuilder->setValue('[types]', $autocomplete->getTypes());
}
if ($autocomplete->hasBound()) {
$this->jsonBuilder->setValue('[bounds]', $autocomplete->getBound()->getJavascriptVariable(), false);
}
if ($autocomplete->hasComponentRestrictions()) {
$this->jsonBuilder->setValue('[componentRestrictions]', $autocomplete->getComponentRestrictions());
}
if (!$this->jsonBuilder->hasValues()) {
$this->jsonBuilder->setJsonEncodeOptions(JSON_FORCE_OBJECT);
}
return sprintf(
'%s = new google.maps.places.Autocomplete(document.getElementById(\'%s\'), %s);'.PHP_EOL,
$autocomplete->getJavascriptVariable(),
$autocomplete->getInputId(),
$this->jsonBuilder->build()
);
} | php | {
"resource": ""
} |
q261470 | SeedServiceProvider.register | test | public function register()
{
$this->app->singleton(DatabaseSeeder::class);
$this->app->extend('command.seed', function () {
return new SeedCommand($this->app['db']);
});
} | php | {
"resource": ""
} |
q261471 | Output.closeRequestEarly | test | public function closeRequestEarly()
{
ignore_user_abort(true);
$this->sessionWriteClose();
if ($this->c::canCallFunc('fastcgi_finish_request')) {
fastcgi_finish_request();
} else {
$this->buffersEndFlush();
header('connection: close');
}
} | php | {
"resource": ""
} |
q261472 | Output.gzipOff | test | public function gzipOff()
{
if (headers_sent()) {
throw $this->c::issue('Headers already sent!');
}
@ini_set('zlib.output_compression', 'off');
if ($this->c::canCallFunc('apache_setenv')) {
@apache_setenv('no-gzip', '1');
}
} | php | {
"resource": ""
} |
q261473 | DirectionsWaypoint.setLocation | test | public function setLocation()
{
$args = func_get_args();
if (isset($args[0]) && is_string($args[0])) {
$this->location = $args[0];
} elseif (isset($args[0]) && ($args[0] instanceof Coordinate)) {
$this->location = $args[0];
} elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
if ($this->location === null) {
$this->location = new Coordinate();
}
$this->location->setLatitude($args[0]);
$this->location->setLongitude($args[1]);
if (isset($args[2]) && is_bool($args[2])) {
$this->location->setNoWrap($args[2]);
}
} else {
throw DirectionsException::invalidDirectionsWaypointLocation();
}
} | php | {
"resource": ""
} |
q261474 | DirectionsWaypoint.setStopover | test | public function setStopover($stopover = null)
{
if (!is_bool($stopover) && ($stopover !== null)) {
throw DirectionsException::invalidDirectionsWaypointStopover();
}
$this->stopover = $stopover;
} | php | {
"resource": ""
} |
q261475 | FileUpload.errorReason | test | public function errorReason(int $code): string
{
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
return __('Exceeds `upload_max_filesize` directive in `php.ini`.');
case UPLOAD_ERR_FORM_SIZE:
return __('Exceeds `MAX_FILE_SIZE` directive in the HTML form.');
case UPLOAD_ERR_PARTIAL:
return __('Data missing; partial.');
case UPLOAD_ERR_NO_FILE:
return __('Missing file.');
case UPLOAD_ERR_NO_TMP_DIR:
return __('Missing temp dir.');
case UPLOAD_ERR_CANT_WRITE:
return __('Failed to write file to disk.');
case UPLOAD_ERR_EXTENSION:
return __('A PHP extension stopped the file upload.');
default: // Unknown error code.
return __('Unknown error.');
}
} | php | {
"resource": ""
} |
q261476 | FileExt.set | test | public function set(string $file, string $ext): string
{
if (!$file || !$ext) {
return $file; // Not possible.
}
return $file = preg_replace('/\.[^.]+$/ui', '', $file).'.'.$ext;
} | php | {
"resource": ""
} |
q261477 | FileExt.change | test | public function change(string $file, string $ext): string
{
if (!$file || !$ext) {
return $file; // Not possible.
}
return $file = preg_replace('/\.[^.]+$/ui', '.'.$ext, $file);
} | php | {
"resource": ""
} |
q261478 | AbstractOptionsAsset.hasOption | test | public function hasOption($option)
{
if (!is_string($option)) {
throw AssetException::invalidOption();
}
return isset($this->options[$option]);
} | php | {
"resource": ""
} |
q261479 | AbstractOptionsAsset.getOption | test | public function getOption($option)
{
if (!$this->hasOption($option)) {
throw AssetException::optionDoesNotExist($option);
}
return $this->options[$option];
} | php | {
"resource": ""
} |
q261480 | AbstractOptionsAsset.setOption | test | public function setOption($option, $value)
{
if (!is_string($option)) {
throw AssetException::invalidOption();
}
$this->options[$option] = $value;
} | php | {
"resource": ""
} |
q261481 | AbstractOptionsAsset.removeOption | test | public function removeOption($option)
{
if (!$this->hasOption($option)) {
throw AssetException::optionDoesNotExist($option);
}
unset($this->options[$option]);
} | php | {
"resource": ""
} |
q261482 | RoutingMiddleware.modifyRequestAttributes | test | private function modifyRequestAttributes(RouteMatchInterface $routeMatch, ServerRequestInterface $request): ServerRequestInterface
{
if ($routeMatch->isMethodFailure() === true) {
return $request
->withAttribute('actionName', self::METHOD_NOT_ALLOWED_ACTION)
->withAttribute('allowedMethods', $routeMatch->getAllowedMethods());
}
if ($routeMatch->isFailure() === true) {
return $request->withAttribute('actionName', self::ROUTE_NOT_FOUND_ACTION);
}
return $request
->withAttribute('actionName', $routeMatch->getAction())
->withAttribute('parameters', $routeMatch->getParameters());
} | php | {
"resource": ""
} |
q261483 | ZoomControl.setZoomControlStyle | test | public function setZoomControlStyle($zoomControlStyle)
{
if (!in_array($zoomControlStyle, ZoomControlStyle::getZoomControlStyles())) {
throw ControlException::invalidZoomControlStyle();
}
$this->zoomControlStyle = $zoomControlStyle;
} | php | {
"resource": ""
} |
q261484 | HashIds.decodeOne | test | public function decodeOne(string $hash_id): int
{
$ids = $this->Parser->decode($hash_id);
return $id = (int) ($ids[0] ?? 0);
} | php | {
"resource": ""
} |
q261485 | GeocoderResponse.setResults | test | public function setResults(array $results)
{
$this->results = array();
foreach ($results as $result) {
$this->addResult($result);
}
} | php | {
"resource": ""
} |
q261486 | GeocoderResponse.setStatus | test | public function setStatus($status)
{
if (!in_array($status, GeocoderStatus::getGeocoderStatus())) {
throw GeocodingException::invalidGeocoderResponseStatus();
}
$this->status = $status;
} | php | {
"resource": ""
} |
q261487 | Utf8.isValid | test | public function isValid(string $string): bool
{
if (!isset($string[0])) {
return true; // Nothing to do.
}
return (bool) preg_match('/^./us', $string);
} | php | {
"resource": ""
} |
q261488 | UserAgent.isEngine | test | public function isEngine(): bool
{
if (($is = &$this->cacheKey(__FUNCTION__)) !== null) {
return $is; // Cached this already.
}
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
return $is = $user_agent && preg_match('/(?:blink|gecko|konqueror|msie|opera|playstation|presto|trident|webkit)/ui', $user_agent);
} | php | {
"resource": ""
} |
q261489 | DirPath.normalize | test | public function normalize($value, bool $allow_trailing_slash = false)
{
if (is_array($value) || is_object($value)) {
foreach ($value as $_key => &$_value) {
$_value = $this->normalize($_value);
} // unset($_key, $_value);
return $value;
}
if (!($string = (string) $value)) {
return $string; // Nothing to do.
}
$stream_wrapper_regex = '/^(?<stream_wrapper>'.$this::FS_REGEX_FRAG_STREAM_WRAPPER.')/uS';
$drive_prefix_regex = '/^(?<drive_letter>'.$this::FS_REGEX_FRAG_DRIVE_PREFIX.')/uS';
if (mb_strpos($string, '://') !== false && preg_match($stream_wrapper_regex, $string, $stream_wrapper)) {
$string = preg_replace($stream_wrapper_regex, '', $string);
}
if (mb_strpos($string, ':') !== false && preg_match($drive_prefix_regex, $stringm, $drive_prefix)) {
$string = preg_replace($stream_wrapper_regex, '', $string);
}
$string = str_replace([DIRECTORY_SEPARATOR, '\\', '/'], '/', $string);
$string = preg_replace('/\/+/u', '/', $string); // Remove extra slashes.
$string = $allow_trailing_slash ? $string : $this->c::mbRTrim($string, '/');
if (!empty($drive_prefix[0])) {
$string = mb_strtoupper($drive_prefix[0]).$string;
}
if (!empty($stream_wrapper[0])) {
$string = mb_strtolower($stream_wrapper[0]).$string;
}
return $string;
} | php | {
"resource": ""
} |
q261490 | Paginator.pageUrl | test | protected function pageUrl(int $page): string
{
if ($this->page_url_callback && is_callable($this->page_url_callback)) {
return str_replace($this->page_replacement_code, $page, (string) $this->page_url_callback($page));
}
return str_replace($this->page_replacement_code, $page, $this->page_url);
} | php | {
"resource": ""
} |
q261491 | DistanceMatrixRequest.setAvoidHighways | test | public function setAvoidHighways($avoidHighways = null)
{
if (!is_bool($avoidHighways) && ($avoidHighways !== null)) {
throw DistanceMatrixException::invalidDistanceMatrixRequestAvoidHighways();
}
$this->avoidHighways = $avoidHighways;
} | php | {
"resource": ""
} |
q261492 | DistanceMatrixRequest.setAvoidTolls | test | public function setAvoidTolls($avoidTolls = null)
{
if (!is_bool($avoidTolls) && ($avoidTolls !== null)) {
throw DistanceMatrixException::invalidDistanceMatrixRequestAvoidTolls();
}
$this->avoidTolls = $avoidTolls;
} | php | {
"resource": ""
} |
q261493 | DistanceMatrixRequest.setDestinations | test | public function setDestinations(array $destinations = array())
{
$this->destinations = array();
foreach ($destinations as $destination) {
$this->addDestination($destination);
}
} | php | {
"resource": ""
} |
q261494 | DistanceMatrixRequest.addDestination | test | public function addDestination()
{
$args = func_get_args();
if (isset($args[0]) && is_string($args[0])) {
$this->destinations[] = $args[0];
} elseif (isset($args[0]) && ($args[0] instanceof Coordinate)) {
$this->destinations[] = $args[0];
} elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
$destination = new Coordinate();
$destination->setLatitude($args[0]);
$destination->setLongitude($args[1]);
if (isset($args[2]) && is_bool($args[2])) {
$destination->setNoWrap($args[2]);
}
$this->destinations[] = $destination;
} else {
throw DistanceMatrixException::invalidDistanceMatrixRequestDestination();
}
} | php | {
"resource": ""
} |
q261495 | DistanceMatrixRequest.addOrigin | test | public function addOrigin()
{
$args = func_get_args();
if (isset($args[0]) && is_string($args[0])) {
$this->origins[] = $args[0];
} elseif (isset($args[0]) && ($args[0] instanceof Coordinate)) {
$this->origins[] = $args[0];
} elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
$origin = new Coordinate();
$origin->setLatitude($args[0]);
$origin->setLongitude($args[1]);
if (isset($args[2]) && is_bool($args[2])) {
$origin->setNoWrap($args[2]);
}
$this->origins[] = $origin;
} else {
throw DistanceMatrixException::invalidDistanceMatrixRequestOrigin();
}
} | php | {
"resource": ""
} |
q261496 | DistanceMatrixRequest.setRegion | test | public function setRegion($region = null)
{
if ((!is_string($region) || (strlen($region) !== 2)) && ($region !== null)) {
throw DistanceMatrixException::invalidDistanceMatrixRequestRegion();
}
$this->region = $region;
} | php | {
"resource": ""
} |
q261497 | DistanceMatrixRequest.setLanguage | test | public function setLanguage($language = null)
{
if ((!is_string($language) || ((strlen($language) !== 2) && (strlen($language) !== 5))) && ($language !== null)) {
throw DistanceMatrixException::invalidDistanceMatrixRequestLanguage();
}
$this->language = $language;
} | php | {
"resource": ""
} |
q261498 | DistanceMatrixRequest.setTravelMode | test | public function setTravelMode($travelMode = null)
{
$travelModes = array_diff(TravelMode::getTravelModes(), array(TravelMode::TRANSIT));
if (!in_array($travelMode, $travelModes) && ($travelMode !== null)) {
throw DistanceMatrixException::invalidDistanceMatrixRequestTravelMode();
}
$this->travelMode = $travelMode;
} | php | {
"resource": ""
} |
q261499 | DistanceMatrixRequest.setUnitSystem | test | public function setUnitSystem($unitSystem = null)
{
if (!in_array($unitSystem, UnitSystem::getUnitSystems()) && ($unitSystem !== null)) {
throw DistanceMatrixException::invalidDistanceMatrixRequestUnitSystem();
}
$this->unitSystem = $unitSystem;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.