_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q252400 | Plugin.getApiRequest | validation | protected function getApiRequest($url, Event $event, Queue $queue)
{
$self = $this;
$request = new HttpRequest(array(
'url' => $url,
'resolveCallback' => function($data) use ($self, $url, $event, $queue) {
$self->resolve($url, $data, $event, $queue);
},
'rejectCallback' => function($error) use ($self, $url) {
$self->reject($url, $error);
}
));
return $request;
} | php | {
"resource": ""
} |
q252401 | Plugin.resolve | validation | public function resolve($url, \GuzzleHttp\Message\Response $data, Event $event, Queue $queue)
{
$logger = $this->getLogger();
$json = json_decode($data->getBody());
$logger->info('resolve', array('url' => $url, 'json' => $json));
if (isset($json->error)) {
return $logger->warning(
'Query response contained an error',
array(
'url' => $url,
'error' => $json->error,
)
);
}
$entries = $json->items;
if (!is_array($entries) || !$entries) {
return $logger->warning(
'Query returned no results',
array('url' => $url)
);
}
$entry = reset($entries);
$replacements = $this->getReplacements($entry);
$message = str_replace(
array_keys($replacements),
array_values($replacements),
$this->responseFormat
);
$queue->ircPrivmsg($event->getSource(), $message);
} | php | {
"resource": ""
} |
q252402 | Plugin.getReplacements | validation | protected function getReplacements($entry)
{
$link = 'https://youtu.be/' . $entry->id;
$title = $entry->snippet->title;
$author = $entry->snippet->channelTitle;
$published = date($this->publishedFormat, strtotime($entry->snippet->publishedAt));
$views = number_format($entry->statistics->viewCount, 0);
$likes = number_format($entry->statistics->likeCount, 0);
$dislikes = number_format($entry->statistics->dislikeCount, 0);
$favorites = number_format($entry->statistics->favoriteCount, 0);
$comments = number_format($entry->statistics->commentCount, 0);
$durationInterval = new \DateInterval($entry->contentDetails->duration);
$duration = $durationInterval->format($this->durationFormat);
return array(
'%link%' => $link,
'%title%' => $title,
'%author%' => $author,
'%published%' => $published,
'%views%' => $views,
'%likes%' => $likes,
'%dislikes%' => $dislikes,
'%favorites%' => $favorites,
'%comments%' => $comments,
'%duration%' => $duration,
);
} | php | {
"resource": ""
} |
q252403 | Plugin.getKey | validation | protected function getKey(array $config)
{
if (!isset($config['key']) || !is_string($config['key'])) {
throw new \DomainException(
'key must reference a string',
self::ERR_INVALID_KEY
);
}
return $config['key'];
} | php | {
"resource": ""
} |
q252404 | Plugin.getResponseFormat | validation | protected function getResponseFormat(array $config)
{
if (isset($config['responseFormat'])) {
if (!is_string($config['responseFormat'])) {
throw new \DomainException(
'responseFormat must reference a string',
self::ERR_INVALID_RESPONSEFORMAT
);
}
return $config['responseFormat'];
}
return '[ %link% ] "%title%" by %author%'
. '; Length %duration%'
. '; Published %published%'
. '; Views %views%'
. '; Likes %likes%';
} | php | {
"resource": ""
} |
q252405 | Plugin.getPublishedFormat | validation | protected function getPublishedFormat(array $config)
{
if (isset($config['publishedFormat'])) {
if (!is_string($config['publishedFormat'])) {
throw new \DomainException(
'publishedFormat must reference a string',
self::ERR_INVALID_PUBLISHEDFORMAT
);
}
return $config['publishedFormat'];
}
return 'n/j/y g:i A';
} | php | {
"resource": ""
} |
q252406 | Plugin.getDurationFormat | validation | protected function getDurationFormat(array $config)
{
if (isset($config['durationFormat'])) {
if (!is_string($config['durationFormat'])) {
throw new \DomainException(
'durationFormat must reference a string',
self::ERR_INVALID_DURATIONFORMAT
);
}
return $config['durationFormat'];
}
return '%im%ss';
} | php | {
"resource": ""
} |
q252407 | ExtDirectApi.buildHeader | validation | protected function buildHeader()
{
if ($this->getExtNamespace() === null) {
throw new ExtDirectException("Ext js Namespace not set");
}
// Example: 'Ext.ns("Ext.app"); Ext.app.REMOTING_API = ';
$var = 'Ext.ns("' . $this->getNameSpace() . '"); ' . $this->getNameSpace() . "." . Keys::EXT_HEADER . ' = ';
return $var;
} | php | {
"resource": ""
} |
q252408 | ExtDirectApi.generateApi | validation | protected function generateApi()
{
$api = array();
$api["url"] = $this->getUrl();
$api["type"] = "remoting";
$actionsArray = array();
/** @var DirectCollection $actions */
$actions = $this->getActions();
/** @var ClassInterface $class */
foreach ($actions as $class) {
$methodArray = array();
/** @var MethodInterface $method */
foreach ($class->getMethods() as $method) {
$methodArray[] = array("name" => $method->getAnnotatedName(), "len" => $method->getLen());
}
$actionsArray[$class->getAnnotatedName()] = $methodArray;
}
$api["actions"] = $actionsArray;
return $api;
} | php | {
"resource": ""
} |
q252409 | ExtDirectApi.getApiAsArray | validation | public function getApiAsArray()
{
if ($this->useCache()) {
if ($this->getExtCache()->isApiCached()) {
return $this->getExtCache()->getApi();
}
}
$api = $this->generateApi();
if ($this->useCache()) {
$this->getExtCache()->cacheApi($api);
}
return $api;
} | php | {
"resource": ""
} |
q252410 | StripeObject.boot | validation | public static function boot()
{
parent::boot();
static::addGlobalScope('type', function ($query) {
return $query->when(static::class !== StripeObject::class, function ($query) {
$query->where('type', class_basename((new static())->objectClass));
});
});
static::created(function (StripeObject $object) {
if ($object->relatesWith) {
list($related, $tag) = $object->relatesWith;
$object->relations(get_class($related))->attach($related->id, ['tag' => $tag]);
}
});
} | php | {
"resource": ""
} |
q252411 | Neuron_GameServer_Player_Updates.refreshSession | validation | private function refreshSession ()
{
$mapper = Neuron_GameServer_Mappers_UpdateMapper::getInstance ();
// First check if we have a last id
if (!isset ($_SESSION['ngpu_lastlog']))
{
// New session, can't have updates. No flags set.
$_SESSION['ngpu_lastlog'] = $mapper->getLastLogId ($this->objProfile);
$_SESSION['ngpu_data'] = array ();
}
else
{
$lastLogId = $_SESSION['ngpu_lastlog'];
// Check for updates
$updates = $mapper->getUpdates ($this->objProfile, $lastLogId);
// Process these updates
foreach ($updates as $v)
{
$_SESSION['ngpu_data'][$v['key']] = $v['value'];
$lastLogId = max ($v['id'], $lastLogId);
}
$_SESSION['ngpu_lastlog'] = $lastLogId;
}
} | php | {
"resource": ""
} |
q252412 | Paginate.getFilters | validation | public function getFilters($columnDescriptions = [], $activeFieldName = false)
{
$filters = [];
if (count($this->filtersArray) > 0) {
foreach ($this->filtersArray as $key => $value) {
if (isset($this->filters[$key])) {
// Filters are active on the active data column
$activeFieldName = $activeFieldName?: $this->filtersArray['orderBy'];
// There may optionally be passed in a more human friendly name for the active field.
$friendlyFieldName = isset($columnDescriptions[$activeFieldName]) ? $columnDescriptions[$activeFieldName] : $activeFieldName;
$filters[] = sprintf($this->filters[$key], $friendlyFieldName, $value);
//$filters[] = call_user_func_array("sprintf", [$this->filters[$key], ]);
}
}
}
return $filters;
} | php | {
"resource": ""
} |
q252413 | Str.encrypt | validation | public static function encrypt($data, $key, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC)
{
$data = serialize($data);
$key = hash('sha256', $key, true);
$iv_size = mcrypt_get_iv_size($cipher, $mode);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return base64_encode(serialize(array($iv, mcrypt_encrypt($cipher, $key, $data, $mode, $iv))));
} | php | {
"resource": ""
} |
q252414 | Str.decrypt | validation | public static function decrypt($data, $key, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC)
{
$key = hash('sha256', $key, true);
@ list($iv, $encrypted) = (array) unserialize(base64_decode($data));
return unserialize(trim(mcrypt_decrypt($cipher, $key, $encrypted, $mode, $iv)));
} | php | {
"resource": ""
} |
q252415 | Str.hash | validation | public static function hash($string, $algorithm = 'blowfish')
{
switch( strtolower($algorithm) ):
case('md5'):
$salt = '$1$'.(static::rand(12)).'$';
break;
case('sha256'):
$salt = '$5$rounds=5000$'.(static::rand(16)).'$';
break;
case('sha512'):
$salt = '$6$rounds=5000$'.(static::rand(16)).'$';
break;
case('blowfish'):
default:
$salt = '$2a$09$'.(static::rand(22)).'$';
break;
endswitch;
return base64_encode(crypt($string, $salt));
} | php | {
"resource": ""
} |
q252416 | Str.verify | validation | public static function verify($real, $hash)
{
$hash = base64_decode($hash);
return crypt($real, $hash) == $hash;
} | php | {
"resource": ""
} |
q252417 | Str.rand | validation | public static function rand($length = 10, $special = false)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$special && ($characters .= '!@#$%^&*()+=>:;*-~`{}[],');
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
} | php | {
"resource": ""
} |
q252418 | Creator.create | validation | public function create(?string $name = null)
{
Whois::print($this->getNotify());
$this->creator->create($this->filesystem, $name);
} | php | {
"resource": ""
} |
q252419 | ExtCache.getApi | validation | public function getApi()
{
$api = $this->get(Keys::EXT_API);
if (is_array($api)) {
return $api;
}
return false;
} | php | {
"resource": ""
} |
q252420 | ExtCache.get | validation | protected function get($key)
{
$cache = apc_fetch($this->getKey());
if (!is_array($cache)) {
return false;
} else {
if (isset($cache[$key])) {
return $cache[$key];
}
return false;
}
} | php | {
"resource": ""
} |
q252421 | ExtCache.set | validation | protected function set($key, $value)
{
$cache = apc_fetch($this->getKey());
$cache[$key] = $value;
apc_store($this->getKey(), $cache);
} | php | {
"resource": ""
} |
q252422 | ExtCache.getActions | validation | public function getActions()
{
$result = $this->get(Keys::EXT_ACTION);
if (is_string($result)) {
return unserialize($result);
}
return array();
} | php | {
"resource": ""
} |
q252423 | ExtCache.cacheActions | validation | public function cacheActions(DirectCollection $collection)
{
$serializedCollection = serialize($collection);
$this->set(Keys::EXT_ACTION, $serializedCollection);
} | php | {
"resource": ""
} |
q252424 | AbstractExtDirect.getActions | validation | public function getActions()
{
if ($this->useCache()) {
if ($this->getExtCache()->isCached()) {
return $this->getExtCache()->getActions();
}
}
$actions = $this->generateActions();
if ($this->useCache()) {
$this->getExtCache()->cacheActions($actions);
}
return $actions;
} | php | {
"resource": ""
} |
q252425 | AbstractExtDirect.generateActions | validation | protected function generateActions()
{
$parser = new Parser();
$parser->setPath($this->getApplicationPath());
$parser->setNameSpace($this->getApplicationNameSpace());
$list = $parser->run();
return $list;
} | php | {
"resource": ""
} |
q252426 | Route.addMatch | validation | public function addMatch(string $method, string $uri, $next)
{
$method = strtoupper($method);
if (!in_array($method, $this->supported_methods)) {
throw new Exception("Method " . $method . " is not supported.");
}
if (!is_string($uri)) {
throw new Exception("Uri " . $uri . " is not valid.");
}
if (is_callable($next)) {
$new_match = array(
$this->ARRAY_METHOD_KEY => $method,
$this->ARRAY_URI_KEY => $uri,
$this->ARRAY_CALLABLE_BOOL_KEY => true,
$this->ARRAY_CALLABLE_KEY => $next
);
} elseif (is_string($next)) {
if (file_exists($next)) {
$new_match = array(
$this->ARRAY_METHOD_KEY => $method,
$this->ARRAY_URI_KEY => $uri,
$this->ARRAY_CALLABLE_BOOL_KEY => false,
$this->ARRAY_FILE_KEY => $next
);
} else {
$dir_next = __DIR__ . "/" . $next;
if (file_exists($dir_next)) {
$new_match = array(
$this->ARRAY_METHOD_KEY => $method,
$this->ARRAY_URI_KEY => $uri,
$this->ARRAY_CALLABLE_BOOL_KEY => false,
$this->ARRAY_FILE_KEY => $dir_next
);
} else {
throw new Exception("File " . $next . " not found.");
}
}
} else {
throw new Exception("Invalid third parameter. Expecting callable or file.");
}
array_push($this->match_list, $new_match);
} | php | {
"resource": ""
} |
q252427 | Neuron_GameServer_Mappers_ChatMapper.setPrivateChatUpdateRead | validation | public function setPrivateChatUpdateRead (Neuron_GameServer_Player $from, Neuron_GameServer_Player $target)
{
$db = Neuron_DB_Database::getInstance ();
$db->query
("
UPDATE
n_privatechat_updates
SET
pu_read = '1'
WHERE
pu_to = {$target->getId ()} AND
pu_from = {$from->getId ()}
");
} | php | {
"resource": ""
} |
q252428 | Arr.get | validation | public static function get(array $arr, $k, $default=null)
{
if ( isset($arr[$k]) ) return $arr[$k];
$nested = explode('.',$k);
foreach ( $nested as $part ) {
if (isset($arr[$part])) {
$arr = $arr[$part];
continue;
} else {
$arr = $default;
break;
}
}
return $arr;
} | php | {
"resource": ""
} |
q252429 | Arr.set | validation | public static function set(array $arr, $k, $v)
{
$nested = !is_array($k) ? explode('.',$k) : $k;
$count = count($nested);
if ($count == 1){
return $arr[$k] = $v;
}
elseif ($count > 1)
{
$prev = '';
$loop = 1;
$unshift = $nested;
foreach ($nested as $part)
{
if (isset($arr[$part]) && $count > $loop)
{
$prev = $part;
array_shift($unshift);
$loop++;
continue;
}
else
{
if ( $loop > 1 && $loop < $count )
{
if( !isset($arr[$prev][$part]) ) $arr[$prev][$part] = [];
$arr[$prev] = static::set($arr[$prev], $unshift, $v);
$loop++; break;
}
elseif ( $loop >= 1 && $loop == $count )
{
if ( !is_array($arr[$prev]) ) $arr[$prev] = [];
if ($part == '')
$arr[$prev][] = $v;
else
$arr[$prev][$part] = $v;
}else{
$arr[$part] = [];
$prev = $part;
array_shift($unshift);
$loop++;
}
}
}
}
return $arr;
} | php | {
"resource": ""
} |
q252430 | Arr.json | validation | public static function json($jsonStr, $k=null, $default=null){
$json = json_decode($jsonStr, true);
if($k && $json){
return self::get($json, $k, $default);
}
return $json;
} | php | {
"resource": ""
} |
q252431 | CompletePurchaseRequest.getData | validation | public function getData()
{
$reference = new FluidXml(false);
$reference->add($this->getTransactionReference());
return [
'password' => $this->getPassword(),
'userId' => $this->getUserId(),
'merchantId' => $this->getMerchantId(),
'transactionReference' => $reference
];
} | php | {
"resource": ""
} |
q252432 | Route.routeProcess | validation | public function routeProcess($uri = false, $httpMethod = false)
{
// Set Request type.
if (!$httpMethod) $httpMethod = $_SERVER['REQUEST_METHOD'];
$this->httpMethod = $httpMethod;
// Set PATH info.
if (!$uri) $uri = $_SERVER['REQUEST_URI'];
$this->setPath($uri);
// BIG IDEA: routeFind() must be called to populate needed Controller and Method variables.
//
// If a custom route is found, routeFind() still needs to be called to populate
// data member variables and complete the mapping from URI to a Controller file.
//
// If custom route is not set, but automatic routing is enabled, also call routeFind
// to see if an automatic route exists.
$customPathSearch = $this->customFind();
if ($customPathSearch || (!$customPathSearch && $this->config['automatic_routing'])) {
$this->routeFind();
}
// If a route was found, but access was denied via the preExec callback...
else if ($customPathSearch == -1) {
$this->error('403');
}
// ELSE
// Do nothing if there's no match. When and if routeExec is called user will be
// directed to 404. But until then, developers can use the exists() method to
// check different routes and possibly redirect the user somewhere else.
} | php | {
"resource": ""
} |
q252433 | Route.exists | validation | public function exists($uri = false, $httpMethod = false)
{
// If wanting to check if a passed in uri and method have a path mapping
if ($uri && $httpMethod) {
$this->routeProcess($uri, $httpMethod);
}
// After a URI is processed, it should result in a controller path being set if a
// matching one exists. If not set, that means there was no matching controller to given URI.
if (!isset($this->controllerPath)) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q252434 | Route.setPath | validation | protected function setPath($url)
{
// Removes any GET data from the url.
// Makes 'mysite.com/websites/build/?somevalue=test' INTO '/websites/build'
$cleanURI = str_replace('?'.$_SERVER['QUERY_STRING'], '', $url);
// Removes the 'mysite.com' from 'mysite.com/controller/method/id/'
// Resulting pathString will be 'controller/method/id/'
$this->pathString = explode($this->config['site_url'], $cleanURI, 2)[1];
// If config option to make url lowercase is true
if ($this->config['lowercase_url']) {
$this->pathString = strtolower($this->pathString);
}
// Setup Path array
$this->path = explode('/', $this->pathString);
} | php | {
"resource": ""
} |
q252435 | Tree.fixTree | validation | protected function fixTree(array $data)/*# : array */
{
$result = [];
foreach ($data as $k => $v) {
$res = &$this->searchNode($k, $result);
if (is_array($v) && is_array($res)) {
$res = array_replace_recursive($res, $this->fixTree($v));
} else {
$res = $v;
}
}
return $result;
} | php | {
"resource": ""
} |
q252436 | ResponseCollection.asArray | validation | public function asArray()
{
$result = array();
/** @var ExtDirectResponse $response */
foreach ($this->collection as $response) {
$result[] = $response->getResultAsArray();
}
return $result;
} | php | {
"resource": ""
} |
q252437 | Collection.__isset | validation | public function __isset($name)
{
$value = $this->find($name);
if ($value !== null && !($value instanceof \Exception)) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q252438 | Collection.add | validation | public function add($item, $key = false, $dataKey = false)
{
// If the data should be sorted by a property/key on it, but you want to add a prefix to
// the result. Example: If $item->month is a numeric value between 1 and 12, but there may be
// missing months in the data. Trying to access $collection->{'1'} will fetch OFFSET 1 which if
// January data is missing, could be another month. No Bueno. By passing in a prefix you can use
// $collection->month1 which will either be set or not and won't resort to returning first offset as result.
$keyPrefix = '';
if (is_array($dataKey)) {
$keyPrefix = $dataKey[1];
$dataKey = $dataKey[0];
}
if (is_object($item)) {
if ($key) {
if (!isset($this->key)) { $this->size += 1; }
$this->singleton->$key = $item;
}
else if ($dataKey && isset($item->$dataKey)) {
$key = $item->$dataKey;
if (!isset($this->key)) {
$this->size += 1;
}
$this->singleton->{$keyPrefix.$key} = $item;
}
else {
$offset = '_item'.$this->size;
$this->size += 1;
$this->singleton->{"$offset"} = $item;
}
}
else if (is_array($item)) {
if ($key) {
if (!isset($this->key)) { $this->size += 1; }
$this->singleton->$key = $item;
}
else if ($dataKey && isset($item[$dataKey])) {
$key = $item[$dataKey];
if (!isset($this->key)) { $this->size += 1; }
$this->singleton->{$keyPrefix.$key} = $item;
}
else {
$offset = '_item'.$this->size;
$this->size += 1;
$this->singleton->{"$offset"} = $item;
}
}
else {
if ($key) {
if (!$this->__isset($key)) { $this->size += 1; }
$this->singleton->$key = $item;
}
else {
$offset = '_item'.$this->size;
$this->size += 1;
$this->singleton->{"$offset"} = $item;
}
}
$this->contentModified = true;
return $this;
} | php | {
"resource": ""
} |
q252439 | Collection.delete | validation | public function delete($name)
{
// Get actual name. If "off0" translates to just 0.
$name = $this->getName($name);
// Figure out the key of the object we want to delete.
// (if numeric value was passed in, turn that into actual key)
$resourceKey = $name;
if (is_numeric($name)) {
$resourceKey = $this->fetchOffsetKey($name);
}
// Only mark the content as modified and change count if the delete call found
// a resource to remove.
if ($this->processDelete($resourceKey)) {
$this->contentModified = true;
$this->size -= 1;
}
} | php | {
"resource": ""
} |
q252440 | Collection.processDelete | validation | public function processDelete($name, $container = false)
{
// Handle if recursive call or not.
if (!$container) {
$container = $this;
}
// If a single object is meant to be returned.
if (isset($container->singleton->$name)) {
unset($container->singleton->$name);
return true;
}
// else look for a Closure.
if (isset($container->signature->$name)) {
unset($container->signature->$name);
return true;
}
// Else check any parents.
elseif ($container->parent) {
return $container->processDelete($name, $container->parent);
}
return false;
} | php | {
"resource": ""
} |
q252441 | Collection.checkIfSingleton | validation | public function checkIfSingleton($name, $item)
{
// If the closure is marked as needing to be saved as a singleton, store result.
if (isset($this->signaturesToSingletons->$name) and $this->signaturesToSingletons->$name) {
$this->$name = $item;
$this->signaturesToSingletons = false;
}
} | php | {
"resource": ""
} |
q252442 | Collection.fetchOffset | validation | public function fetchOffset($num)
{
// If the content has been modified, regenerate $this->content.
// and $this->contentKeys.
if ($this->contentModified) {
$this->generateContent();
}
// If the offset exists, return the data.
$key = $this->fetchOffsetKey($num);
if ($key != null) {
return $this->content[$key];
}
return null;
} | php | {
"resource": ""
} |
q252443 | Collection.toArray | validation | public function toArray()
{
$collection = $this->getIterator();
$plainArray = [];
foreach($collection as $prop => $result) {
if (is_object($result) && method_exists($result, 'toArray')) {
$plainArray[] = $result->toArray();
} else {
$plainArray[] = $result;
}
}
return $plainArray;
} | php | {
"resource": ""
} |
q252444 | Collection.max | validation | public function max($key = false)
{
$collection = $this->getIterator();
$max = 0;
$valueToReturn = 0;
foreach ($collection as $result) {
if ($key && isset($result->$key)) {
if ($result->$key > $max) {
$max = $result->$key;
$valueToReturn = $result;
}
}
else if ($key && isset($result[$key])) {
if ($result[$key] > $max) {
$max = $result[$key];
$valueToReturn = $result;
}
}
else {
if ($result > $max) {
$max = $result;
$valueToReturn = $result;
}
}
}
return $valueToReturn;
} | php | {
"resource": ""
} |
q252445 | Collection.where | validation | public function where($key = false, $desiredValue, $op = "==")
{
$collection = $this->getIterator();
$subset = new Collection();
foreach($collection as $prop => $result) {
// Grab resource value
$realValue = $result;
if (is_object($result)) {
$realValue = $result->$key;
}
else if (is_array($result)) {
$realValue = $result[$key];
}
// Check value against operator given
$add = false;
if ($op == '==' && $realValue == $desiredValue) {
$add = true;
}
else if ($op == '>=' && $realValue >= $desiredValue) {
$add = true;
}
else if ($op == '<=' && $realValue <= $desiredValue) {
$add = true;
}
else if ($op == '>' && $realValue > $desiredValue) {
$add = true;
}
else if ($op == '<' && $realValue < $desiredValue) {
$add = true;
}
else if ($op == '===' && $realValue === $desiredValue) {
$add = true;
}
else if ($op == '!=' && $realValue != $desiredValue) {
$add = true;
}
// Add the resource to the subset if valid
if ($add) {
$subset->add($result, $prop);
}
}
return $subset;
} | php | {
"resource": ""
} |
q252446 | Collection.merge | validation | public function merge($data, $key = false, $dataKey = false)
{
if ($data != false && (is_array($data) || is_object($data))) {
foreach ($data as $item) {
$this->add($item, $key, $dataKey, true);
}
}
else {
$this->add($data, $key, $dataKey);
}
return $this;
} | php | {
"resource": ""
} |
q252447 | Collection.map | validation | public function map($callback, $data = false)
{
$collection = $this->getIterator();
$mutatedCollection = new Collection();
foreach($collection as $prop => $result) {
// Prep data to pass to closure
$funcArgs = is_array($data) ? $data : [$data];
array_unshift($funcArgs, $prop);
array_unshift($funcArgs, $result);
$aValue = call_user_func_array($callback, $funcArgs);
$mutatedCollection->add($aValue);
}
return $mutatedCollection;
} | php | {
"resource": ""
} |
q252448 | Collection.getIterator | validation | public function getIterator() {
if (!$this->content || $this->contentModified) {
$this->generateContent();
}
return new \ArrayIterator($this->content);
} | php | {
"resource": ""
} |
q252449 | Collection.getValue | validation | protected function getValue($data, $key = false)
{
$returnValue = $data;
if ($key && is_object($data)) {
$returnValue = $data->$key;
}
else if ($key && is_array($data)) {
$returnValue = $data[$key];
}
return $returnValue;
} | php | {
"resource": ""
} |
q252450 | SessionAuth.login | validation | public function login($subject)
{
/** @var HasLoginToken */
$caller = $this->identifier->identify($subject);
if ($this->authenticator->authenticate($subject, $caller)) {
$this->driver->setLoginToken($caller->getLoginToken());
$this->currentCaller = $caller;
return true;
}
return false;
} | php | {
"resource": ""
} |
q252451 | DelegatorTrait.addRegistry | validation | protected function addRegistry($registry)
{
// remove it if exists already
$this->removeFromLookup($registry);
// set delegator in registry
if ($registry instanceof DelegatorAwareInterface) {
$registry->setDelegator($this);
}
// append to the pool
$this->lookup_pool[] = $registry;
return $this;
} | php | {
"resource": ""
} |
q252452 | DelegatorTrait.hasInLookup | validation | protected function hasInLookup(/*# string */ $key)/*# : bool */
{
foreach ($this->lookup_pool as $registry) {
if ($this->hasInRegistry($registry, $key)) {
$this->cache_key = $key;
$this->cache_reg = $registry;
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q252453 | DelegatorTrait.getFromLookup | validation | protected function getFromLookup(/*# string */ $key)
{
// found already ? or try find
if ($key === $this->cache_key || $this->hasInLookup($key)) {
return $this->getFromRegistry($this->cache_reg, $key);
}
// not found
return null;
} | php | {
"resource": ""
} |
q252454 | DelegatorTrait.removeFromLookup | validation | protected function removeFromLookup($registry)
{
foreach ($this->lookup_pool as $idx => $reg) {
if ($registry === $reg) {
if ($reg instanceof DelegatorAwareInterface) {
$reg->setDelegator();
}
unset($this->lookup_pool[$idx]);
}
}
return $this;
} | php | {
"resource": ""
} |
q252455 | Repository.count | validation | public function count($coraDbQuery = false)
{
// If no query builder object was passed in, then grab the gateway's.
if (!$coraDbQuery) {
$coraDbQuery = $this->gateway->getDb();
}
$coraDbQuery = $this->model::model_constraints($coraDbQuery);
return $this->gateway->count($coraDbQuery);
} | php | {
"resource": ""
} |
q252456 | Router.__callstatic | validation | public static function __callstatic($method, $params)
{
$uri = $params[0];
$callback = $params[1];
array_push(self::$routes, $uri);
array_push(self::$methods, strtoupper($method));
array_push(self::$callbacks, $callback);
} | php | {
"resource": ""
} |
q252457 | Router.setSingletonName | validation | public static function setSingletonName($method)
{
if (! is_string($method) || empty($method)) {
return false;
}
self::$singleton = $method;
return true;
} | php | {
"resource": ""
} |
q252458 | Router.getMethod | validation | public static function getMethod($route)
{
$route = Url::addBackSlash($route);
return isset(self::$routes[$route]) ? self::$routes[$route] : null;
} | php | {
"resource": ""
} |
q252459 | Router.dispatch | validation | public static function dispatch()
{
self::routeValidator();
self::$routes = str_replace('//', '/', self::$routes);
if (in_array(self::$uri, self::$routes, true)) {
return self::checkRoutes();
}
if (self::checkRegexRoutes() !== false) {
return self::checkRegexRoutes();
}
return self::getErrorCallback();
} | php | {
"resource": ""
} |
q252460 | Router.invokeObject | validation | protected static function invokeObject($callback, $matched = null)
{
$last = explode('/', $callback);
$last = end($last);
$segments = explode('@', $last);
$class = $segments[0];
$method = $segments[1];
$matched = $matched ? $matched : [];
if (method_exists($class, self::$singleton)) {
$instance = call_user_func([$class, self::$singleton]);
return call_user_func_array([$instance, $method], $matched);
}
if (class_exists($class)) {
$instance = new $class;
return call_user_func_array([$instance, $method], $matched);
}
return false;
} | php | {
"resource": ""
} |
q252461 | Router.cleanResources | validation | private static function cleanResources()
{
self::$callbacks = [];
self::$methods = [];
self::$halts = false;
self::$response = false;
} | php | {
"resource": ""
} |
q252462 | Router.routeValidator | validation | private static function routeValidator()
{
self::$uri = Url::getUriMethods();
self::$uri = Url::setUrlParams(self::$uri);
self::$uri = Url::addBackSlash(self::$uri);
self::cleanResources();
if (self::getMethod(self::$uri)) {
self::any(self::$uri, self::$routes[self::$uri]);
}
} | php | {
"resource": ""
} |
q252463 | Router.checkRoutes | validation | private static function checkRoutes()
{
$method = $_SERVER['REQUEST_METHOD'];
$route_pos = array_keys(self::$routes, self::$uri, true);
foreach ($route_pos as $route) {
$methodRoute = self::$methods[$route];
if ($methodRoute == $method || $methodRoute == 'ANY') {
if (! is_object($callback = self::$callbacks[$route])) {
self::$response = self::invokeObject($callback);
} else {
self::$response = call_user_func($callback);
}
if (! self::$halts) {
return self::$response;
}
self::$halts--;
}
}
return self::$response;
} | php | {
"resource": ""
} |
q252464 | Router.checkRegexRoutes | validation | private static function checkRegexRoutes()
{
$pos = 0;
self::getRegexRoutes();
$method = $_SERVER['REQUEST_METHOD'];
$searches = array_keys(self::$patterns);
$replaces = array_values(self::$patterns);
foreach (self::$routes as $route) {
$segments = explode('/', str_replace($searches, '', $route));
$route = str_replace($searches, $replaces, $route);
$route = Url::addBackSlash($route);
if (preg_match('#^' . $route . '$#', self::$uri, $matched)) {
$methodRoute = self::$methods[$pos];
if ($methodRoute == $method || $methodRoute == 'ANY') {
$matched = explode('/', trim($matched[0], '/'));
$matched = array_diff($matched, $segments);
if (! is_object(self::$callbacks[$pos])) {
self::$response = self::invokeObject(
self::$callbacks[$pos],
$matched
);
} else {
self::$response = call_user_func_array(
self::$callbacks[$pos],
$matched
);
}
if (! self::$halts) {
return self::$response;
}
self::$halts--;
}
}
$pos++;
}
return self::$response;
} | php | {
"resource": ""
} |
q252465 | Router.getRegexRoutes | validation | private static function getRegexRoutes()
{
foreach (self::$routes as $key => $value) {
unset(self::$routes[$key]);
if (strpos($key, ':') !== false) {
self::any($key, $value);
}
}
} | php | {
"resource": ""
} |
q252466 | Router.getErrorCallback | validation | private static function getErrorCallback()
{
$errorCallback = self::$errorCallback;
self::$errorCallback = false;
if (! $errorCallback) {
return false;
}
if (! is_object($errorCallback)) {
return self::invokeObject($errorCallback);
}
return call_user_func($errorCallback);
} | php | {
"resource": ""
} |
q252467 | ClassNameTrait.getShortName | validation | final public static function getShortName(
$className = ''
)/*# : string */ {
$base = strrchr(static::getRealClassName($className), '\\');
return $base ? substr($base, 1) : $className;
} | php | {
"resource": ""
} |
q252468 | ClassNameTrait.setProperties | validation | final public function setProperties(array $properties = [])
{
foreach ($properties as $name => $value) {
if (property_exists($this, $name)) {
$this->$name = $value;
} else {
trigger_error(
Message::get(
Message::MSG_PROPERTY_UNKNOWN,
$name,
get_class($this)
),
E_USER_WARNING
);
}
}
} | php | {
"resource": ""
} |
q252469 | Client.getUrl | validation | protected function getUrl($section, array $uriParams = [])
{
$endpoint = rtrim($this->getEndpoint(), '/');
$section = ltrim($section, '/');
$params = http_build_query($uriParams);
if ($params) {
return sprintf("%s/%s?%s", $endpoint, $section, $params);
} else {
return sprintf("%s/%s", $endpoint, $section);
}
} | php | {
"resource": ""
} |
q252470 | Client.init | validation | public function init()
{
$this->pluginClient = new PluginClient(
$this->httpClient ?: HttpClientDiscovery::find(),
$this->plugins
);
$this->client = new HttpMethodsClient(
$this->pluginClient,
$this->messageFactory ?: MessageFactoryDiscovery::find()
);
} | php | {
"resource": ""
} |
q252471 | Client.get | validation | public function get($section, array $params = [], $headers = [])
{
$params = array_merge($this->parameters, $params, $this->defaultParameters);
return $this->client->get($this->getUrl($section, $params), $headers);
} | php | {
"resource": ""
} |
q252472 | Client.post | validation | public function post($section, $body = null, array $headers = [])
{
if (is_array($body)) {
$body = array_merge($this->parameters, $body, $this->defaultParameters);
$body = http_build_query($body);
}
return $this->client->post($this->getUrl($section), $headers, $body);
} | php | {
"resource": ""
} |
q252473 | GeoPlugin.getLocation | validation | public function getLocation($ip = '', $baseCurrency = '', $renameArrayKeys = false)
{
$params = [
'ip' => !$ip ? $_SERVER['REMOTE_ADDR'] : $ip,
'base_currency' => $baseCurrency,
];
$response = $this->client->get('json.gp', $params);
$data = $this->handleResponseContent($response, 'json');
if ($renameArrayKeys) {
$tmpData = [];
foreach ($data as $key => $value) {
$tmpData[str_replace('geoplugin_', '', $key)] = $value;
}
$data = $tmpData;
}
return $data;
} | php | {
"resource": ""
} |
q252474 | Command.run | validation | public function run($argument, Message $message, ApiClient $apiClient)
{
$this->setApiClient($apiClient);
$this->execute($argument, $message);
} | php | {
"resource": ""
} |
q252475 | ReferenceTrait.checkValue | validation | protected function checkValue(
$value,
/*# string */ $subject,
/*# string */ $reference
) {
// unknown reference found, leave it alone
if (is_null($value)) {
// exception thrown in resolveUnknown() already if wanted to
return $subject;
// malformed partial match, partial string, partial non-scalar
} elseif ($subject != $reference) {
throw new RuntimeException(
Message::get(Message::MSG_REF_MALFORMED, $reference),
Message::MSG_REF_MALFORMED
);
// full match, array or object
} else {
return $value;
}
} | php | {
"resource": ""
} |
q252476 | ReferenceTrait.checkReferenceLoop | validation | protected function checkReferenceLoop(
/*# int */ $loop,
/*# string */ $name
) {
if ($loop > 20) {
throw new RuntimeException(
Message::get(Message::MSG_REF_LOOP, $name),
Message::MSG_REF_LOOP
);
}
} | php | {
"resource": ""
} |
q252477 | Redirect.url | validation | public function url($url = null, $append = '')
{
unset($_POST);
unset($_FILES);
header('location: '.$this->getRedirect($url).$append);
exit;
} | php | {
"resource": ""
} |
q252478 | Redirect.saveUrl | validation | public function saveUrl($url = false, $append = '')
{
// If no URL is specified, then save the current URL.
if ($url == false) {
$url = '//'.$this->config['base_url'].$_SERVER['REQUEST_URI'];
}
// Set saved URL
$this->saved = $this->getRedirect($url).$append;
// Also save URL to session, in-case it won't be used until next request.
$this->session->savedUrl = $this->saved;
} | php | {
"resource": ""
} |
q252479 | Redirect.getRedirect | validation | public function getRedirect($url = null)
{
// If a url to redirect to was specified
if ($url) {
// If the redirect is being specified as an offset such as "-2"
if (is_numeric($url)) {
// Just clarifying that the URL (in this case) is steps to take backwards in the history array, not an actual URL.
$steps = $url;
// If you want to send the user back 2 steps, you would pass in -2 as the steps.
// Adding this negative number to the number of items in the history array gives the desired URL offset.
$offset = count($_SESSION['redirect']['history']) + $steps;
// Check if such an offset exists.
if (isset($_SESSION['redirect']['history'][$offset])) {
$redirect = $_SESSION['redirect']['history'][$offset];
if (!empty($redirect)) {
return $redirect;
} else {
return BASE_URL;
}
}
// Otherwise redirect to homepage as fallback.
else {
return $this->config['site_url'];
}
}
// If the URL is an actual URL.
else {
// If the URL is specified as a relative URL, then include the 'site_url' setting at beginning.
if (substr($url, 0, 1) == '/') {
return $this->config['site_url'].substr($url, 1);
}
else {
return $url;
}
}
}
// Redirect to home page.
else {
return $this->config['site_url'];
}
} | php | {
"resource": ""
} |
q252480 | Validate.run | validation | public function run()
{
if (count($this->errors) == 0) {
return true;
}
else {
$this->controller->setData('errors', $this->errors);
return false;
}
} | php | {
"resource": ""
} |
q252481 | Validate.def | validation | public function def ($checkName, $class, $method, $errorMessage, $passing = true, $arguments = false)
{
$this->customChecks->$checkName = ['_call', $class, $method, $passing, $arguments];
$this->lang->$checkName = $errorMessage;
} | php | {
"resource": ""
} |
q252482 | Validate.rule | validation | public function rule($fieldName, $checks, $humanName = false)
{
$checkFailures = 0;
// Default human readable name of form field to the field name.
if ($humanName == false) {
$humanName = ucfirst($fieldName);
}
// Grab data from array or leave as false if no data exists.
$fieldData = $this->getValue($fieldName);
if (!is_array($checks)) {
$checks = explode('|', $checks);
}
// Run checks
foreach ($checks as $check) {
$checkName = $check;
if (isset($this->customChecks->$check)) {
// Grab this custom check's definition.
$customCheckDef = $this->customChecks->$check;
// Grab custom check type. Ex. "call"
//$checkName = $check;
$customType = $customCheckDef[0];
// Define the arguments that will be passed to the custom check.
$arguments = array($fieldData, $customCheckDef[1], $customCheckDef[2], $customCheckDef[3], $customCheckDef[4]);
// Call the custom check.
$checkResult = call_user_func_array(array($this, $customType), $arguments);
}
else {
// See if validation check needs additional argument. E.g "matches[password]"
$checkArgs = explode('[', $check, 2);
if (count($checkArgs)>1) {
// Set corrected method check name to call. E.g. "matches[password]" calls "matches"
$check = $checkArgs[0];
$checkName = $checkArgs[0];
// explode strips out the leading '[' from '[value]' so we are just restoring it.
$checkArgs[1] = '['.$checkArgs[1];
// Grab arguments that need to be passed to Check. E.g. "matches[password][title]" would
// return "array('password', 'title')"
$args = array();
preg_match_all("/\[([^\]]*)\]/", $checkArgs[1], $args);
$this->matchedArg = $args[1][0];
// Append underscore to the check method's name.
$check = '_'.$checkName;
// Call a built-in check that's part of this Validation class.
$checkResult = $this->$check($fieldData, $args[1]);
}
else {
// Append underscore to the check method's name.
$check = '_'.$checkName;
// Call a built-in check that's part of this Validation class.
$checkResult = $this->$check($fieldData);
}
}
// If the result of the called check is anything other than true, set a validation error.
if ($checkResult == false) {
$this->errors[] = sprintf($this->lang->$checkName, $humanName, $this->matchedArg);
$this->matchedArg = false;
$checkFailures++;
}
}
// After all checks for this data field have been run, return if Validation passed (TRUE) or failed (FALSE);
return $checkFailures == 0 ? true : false;
} | php | {
"resource": ""
} |
q252483 | Validate._call | validation | protected function _call($fieldData, $controller, $method, $passing, $arguments)
{
// If data to be passed to the method isn't an array, put it in array format.
$fieldData = array($fieldData, $arguments);
// Call custom controller->method and pass the data to it.
$result = call_user_func_array(array($controller, $method), $fieldData);
// If the returned result meets expections, pass test (return false) otherwise return message.
return $result == $passing ? true : false;
} | php | {
"resource": ""
} |
q252484 | Neuron_GameServer_Map_Movement.setDirection | validation | public function setDirection (Neuron_GameServer_Map_Vector3 $start, Neuron_GameServer_Map_Vector3 $end)
{
$this->startRotation = $start;
$this->endRotation = $end;
} | php | {
"resource": ""
} |
q252485 | Neuron_GameServer_Map_Movement.setUp | validation | public function setUp (Neuron_GameServer_Map_Vector3 $start, Neuron_GameServer_Map_Vector3 $end)
{
$this->startUp = $start->normalize ();
$this->endUp = $end->normalize ();
} | php | {
"resource": ""
} |
q252486 | SqlMigrationRepository.getRan | validation | public function getRan(): array
{
$stmt = $this->pdo->query("select migration from {$this->table} order by batch, migration");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_COLUMN);
return $results;
} | php | {
"resource": ""
} |
q252487 | SqlMigrationRepository.getMigrations | validation | public function getMigrations(int $steps): array
{
$sql = "select migration from {$this->table}
where batch >= 1
order by batch, migration desc
limit ?";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(1, $steps, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_COLUMN);
} | php | {
"resource": ""
} |
q252488 | SqlMigrationRepository.getLast | validation | public function getLast(): array
{
$sql = "select migration from {$this->table} as b
where exists (select max(batch) from {$this->table} as a where b.batch = a.batch)
order by migration desc";
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_COLUMN);
} | php | {
"resource": ""
} |
q252489 | SqlMigrationRepository.getMigrationBatches | validation | public function getMigrationBatches(): array
{
$stmt = $this->pdo->prepare("select * from {$this->table} order by batch, migration");
$stmt->execute();
$array = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $item) {
$array[$item['migration']] = $item['batch'];
}
return $array;
} | php | {
"resource": ""
} |
q252490 | SqlMigrationRepository.log | validation | public function log(string $file, int $batch): void
{
$stmt = $this->pdo->prepare("insert into {$this->table} (migration, batch) values (?, ?)");
$stmt->bindParam(1, $file);
$stmt->bindParam(2, $batch, PDO::PARAM_INT);
$stmt->execute();
} | php | {
"resource": ""
} |
q252491 | SqlMigrationRepository.delete | validation | public function delete(string $migration): void
{
$stmt = $this->pdo->prepare("delete from {$this->table} where migration = ?");
$stmt->bindParam(1, $migration);
$stmt->execute();
} | php | {
"resource": ""
} |
q252492 | SqlMigrationRepository.getLastBatchNumber | validation | public function getLastBatchNumber(): int
{
$stmt = $this->pdo->query("select max(batch) from {$this->table}");
$stmt->execute();
return (int) $stmt->fetch(PDO::FETCH_ASSOC)['max'];
} | php | {
"resource": ""
} |
q252493 | SqlMigrationRepository.repositoryExists | validation | public function repositoryExists(): bool
{
switch ($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) {
case 'pgsql':
$sql = 'select count(*) from information_schema.tables
where table_schema = current_schema()
and table_name = ?';
break;
case 'mysql':
$sql = 'select count(*) from information_schema.tables
where table_schema = database()
and table_name = ?';
break;
case 'sqlsrv':
$sql = "select count(*) from sysobjects where type = 'U' and name = ?";
break;
case 'sqlite':
$sql = "select count(*) from sqlite_master where type = 'table' and name = ?";
break;
default:
throw InvalidArgumentException::forDatabaseNotSupported();
}
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(1, $this->table);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_COLUMN) > 0;
} | php | {
"resource": ""
} |
q252494 | SqlMigrationRepository.transaction | validation | public function transaction(callable $callback): void
{
$this->pdo->beginTransaction();
$callback($this);
$this->pdo->commit();
} | php | {
"resource": ""
} |
q252495 | SqlMigrationRepository.drop | validation | public function drop(): array
{
$touched = [];
$this->pdo->beginTransaction();
foreach ($this->getViews() as $view) {
$this->pdo->exec("drop view if exists {$view} cascade");
$touched[] = ['view', $view];
}
foreach ($this->getTables() as $table) {
$this->pdo->exec("drop table if exists {$table} cascade");
$touched[] = ['table', $table];
}
$this->pdo->commit();
return $touched;
} | php | {
"resource": ""
} |
q252496 | Seeder.call | validation | public function call(string $class): void
{
$files = $this->all($class);
if (count($files) < 1) {
throw InvalidArgumentException::forNotFoundSeeder();
}
foreach ($files as [$file, $content]) {
$this->load($content);
$this->resolve($file['filename'])->run();
}
} | php | {
"resource": ""
} |
q252497 | Seeder.resolve | validation | private function resolve(string $class): AbstractSeed
{
/** @var $instance \Roquie\Database\Seed\AbstractSeed */
$instance = $this->autowire($class);
$instance->setDatabase($this->database);
$instance->setSeeder($this);
if (! is_null($this->container)) {
$instance->setContainer($this->container);
}
return $instance;
} | php | {
"resource": ""
} |
q252498 | Seeder.all | validation | private function all(?string $name): array
{
$array = [];
foreach ($this->filesystem->listContents() as $file) {
if (is_null($name)) {
$array[] = [$file, $this->filesystem->read($file['path'])];
} else {
if ($file['filename'] === ($name ?: Seed::DEFAULT_SEED)) {
$array[] = [$file, $this->filesystem->read($file['path'])];
break;
}
}
}
return $array;
} | php | {
"resource": ""
} |
q252499 | Seeder.invoker | validation | private function invoker(ContainerInterface $container)
{
$resolvers = new ResolverChain([
new ParameterNameContainerResolver($container),
new DefaultValueResolver(),
]);
$invoker = new Invoker($resolvers, $container);
return $invoker;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.