_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q268000 | Migration.truncateTable | test | public function truncateTable($table)
{
$cmdPromise = $this->createCommand()->truncateTable($table)->execute();
return $this->execPromise($cmdPromise, "truncate table $table");
} | php | {
"resource": ""
} |
q268001 | Migration.dropColumn | test | public function dropColumn($table, $column)
{
$cmdPromise = $this->createCommand()->dropColumn($table, $column)->execute();
return $this->execPromise($cmdPromise, "drop column $column from table $table");
} | php | {
"resource": ""
} |
q268002 | Migration.renameColumn | test | public function renameColumn($table, $name, $newName)
{
$cmdPromise = $this->createCommand()->renameColumn($table, $name, $newName)->execute();
return $this->execPromise($cmdPromise, "rename column $name in table $table to $newName");
} | php | {
"resource": ""
} |
q268003 | Migration.alterColumn | test | public function alterColumn($table, $column, $type)
{
$promises = [];
$promises[] = $this->createCommand()->alterColumn($table, $column, $type)->execute();
if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
$promises[] = $this->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
}
return $this->execPromise($promises, "alter column $column in table $table to $type");
} | php | {
"resource": ""
} |
q268004 | Migration.addPrimaryKey | test | public function addPrimaryKey($name, $table, $columns)
{
$description = "add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ')';
$cmdPromise = $this->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
return $this->execPromise($cmdPromise, $description);
} | php | {
"resource": ""
} |
q268005 | Migration.dropPrimaryKey | test | public function dropPrimaryKey($name, $table)
{
$cmdPromise = $this->createCommand()->dropPrimaryKey($name, $table)->execute();
return $this->execPromise($cmdPromise, "drop primary key $name");
} | php | {
"resource": ""
} |
q268006 | Migration.addForeignKey | test | public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$description = "add foreign key $name: $table (" . implode(',', (array)$columns) . ") references $refTable (" . implode(',', (array)$refColumns) . ')';
$cmdPromise = $this->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
return $this->execPromise($cmdPromise, $description);
} | php | {
"resource": ""
} |
q268007 | Migration.dropForeignKey | test | public function dropForeignKey($name, $table)
{
$cmdPromise = $this->createCommand()->dropForeignKey($name, $table)->execute();
return $this->execPromise($cmdPromise, "drop foreign key $name from table $table");
} | php | {
"resource": ""
} |
q268008 | Migration.createIndex | test | public function createIndex($name, $table, $columns, $unique = false)
{
$description = 'create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array)$columns) . ')';
$cmdPromise = $this->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
return $this->execPromise($cmdPromise, $description);
} | php | {
"resource": ""
} |
q268009 | Migration.dropIndex | test | public function dropIndex($name, $table)
{
$cmdPromise = $this->createCommand()->dropIndex($name, $table)->execute();
return $this->execPromise($cmdPromise, "drop index $name on $table");
} | php | {
"resource": ""
} |
q268010 | Migration.addCommentOnColumn | test | public function addCommentOnColumn($table, $column, $comment)
{
$cmdPromise = $this->createCommand()->addCommentOnColumn($table, $column, $comment)->execute();
return $this->execPromise($cmdPromise, "add comment on column $column");
} | php | {
"resource": ""
} |
q268011 | Migration.addCommentOnTable | test | public function addCommentOnTable($table, $comment)
{
$cmdPromise = $this->createCommand()->addCommentOnTable($table, $comment)->execute();
return $this->execPromise($cmdPromise, "add comment on table $table");
} | php | {
"resource": ""
} |
q268012 | Migration.dropCommentFromColumn | test | public function dropCommentFromColumn($table, $column)
{
$cmdPromise = $this->createCommand()->dropCommentFromColumn($table, $column)->execute();
return $this->execPromise($cmdPromise, "drop comment from column $column");
} | php | {
"resource": ""
} |
q268013 | Migration.dropCommentFromTable | test | public function dropCommentFromTable($table)
{
$cmdPromise = $this->createCommand()->dropCommentFromTable($table)->execute();
return $this->execPromise($cmdPromise, "drop comment from table $table");
} | php | {
"resource": ""
} |
q268014 | Migration.execPromise | test | protected function execPromise($cmdPromise, $description)
{
return $this->beginCommandLazy($description)->thenLazy(
function($time) use ($cmdPromise) {
if (is_array($cmdPromise)) {
$cmdPromise = allInOrder($cmdPromise);
}
return $cmdPromise->always(function() use ($time) {
return $this->endCommand($time);
});
}
);
} | php | {
"resource": ""
} |
q268015 | LogProxy.log | test | public static function log(string $message, string $level = self::LEVEL_INFO, ?string $category = null, $dump = null)
{
$message = Text::crop($message, 255);
return static::getAdapter()->log($message, $level, $category, $dump);
} | php | {
"resource": ""
} |
q268016 | Regex.validate | test | private function validate($regex): void {
if(@preg_match($regex, '') === false) {
throw new InvalidArgumentException('Expected regex, but got [' . var_export($regex, true) . '] instead');
}
} | php | {
"resource": ""
} |
q268017 | Regex.capture | test | public function capture(Text $text): array {
preg_match_all($this->raw, (string)$text, $matches, PREG_SET_ORDER);
foreach($matches as &$match) {
array_shift($match);
$match = $text->fromArray($match);
}
return $matches;
} | php | {
"resource": ""
} |
q268018 | Regex.split | test | public function split(Text $text): array {
return $text->fromArray(preg_split($this->raw, (string)$text));
} | php | {
"resource": ""
} |
q268019 | Regex.replace | test | public function replace(Text $text, Text $replace): Text {
return new Text(preg_replace($this->raw, $replace->raw, $text->raw));
} | php | {
"resource": ""
} |
q268020 | FormController.configAction | test | public function configAction()
{
$response = new Response(
json_encode($this->container->getParameter('ekyna_core.form_js'))
);
$response
->setPublic()
->setMaxAge(3600*6)
->setSharedMaxAge(3600*6)
->headers->add(['Content-Type' => 'application/json'])
;
return $response;
} | php | {
"resource": ""
} |
q268021 | SimpleCaptcha.securimageUrl | test | public function securimageUrl()
{
$reflector = new \ReflectionClass('Securimage');
$securimageUrl = dirname($reflector->getFileName());
$securimageUrl = preg_replace('#^.*(\\'. DIRECTORY_SEPARATOR .'vendor\\'. DIRECTORY_SEPARATOR .'.+)$#', '$1', $securimageUrl);
$securimageUrl = str_replace(DIRECTORY_SEPARATOR, '/', $securimageUrl);
return $securimageUrl . '/securimage_show.php';
} | php | {
"resource": ""
} |
q268022 | Repository.get | test | public function get($id)
{
try {
$model = $this->connection
->select()
->from($this->dummy->getTableName())
->where($this->dummy->getIdField(), '=', $id)
->getOneClass($this->getModelClass());
} catch (QueryBuilderException $e) {
throw new MappingException($e->getMessage());
}
return $model;
} | php | {
"resource": ""
} |
q268023 | Repository.getOrNew | test | public function getOrNew($id = null)
{
try {
$model = $this->get($id);
} catch (MappingException $e) {
$modelClass = $this->getModelClass();
$model = new $modelClass();
}
return $model;
} | php | {
"resource": ""
} |
q268024 | Repository.getList | test | public function getList()
{
return $this->connection
->select()
->from($this->dummy->getTableName())
->orderBy($this->dummy->getIdField(), static::DEFAULT_ORDER)
->getAsClasses($this->getModelClass());
} | php | {
"resource": ""
} |
q268025 | Repository.save | test | public function save(Model $model)
{
$model->validate();
if ($model->exists()) {
if ($model->isModified()) {
$this->connection
->update($this->dummy->getTableName())
->where($model::getIdField(), '=', $model->getId())
->set($model->getSaveableProperties())
->execute();
}
} else {
$this->connection
->insert($model->getSaveableProperties())
->into($this->dummy->getTableName())
->execute();
$model->setId($this->connection->getPdo()->lastInsertId());
}
} | php | {
"resource": ""
} |
q268026 | Repository.delete | test | public function delete(Model $model)
{
$this->connection
->delete()
->from($this->dummy->getTableName())
->where($model::getIdField(), '=', $model->getId())
->execute();
} | php | {
"resource": ""
} |
q268027 | Repository.getWhereIdIn | test | public function getWhereIdIn(array $ids)
{
return $this->connection
->select()
->from($this->dummy->getTableName())
->whereIn($this->dummy->getIdField(), $ids)
->getAsClasses($this->getModelClass());
} | php | {
"resource": ""
} |
q268028 | Repository.getWhereIdInWithKeys | test | public function getWhereIdInWithKeys(array $ids)
{
$models = $this->getWhereIdIn($ids);
$returning = [];
foreach ($models as $model) {
$returning[$model->getId()] = $model;
}
return $returning;
} | php | {
"resource": ""
} |
q268029 | Cookie.setrawcookie | test | final public static function setrawcookie(
$name, $value, $expire = 0, $path = null,
$domain = null, $secure = false, $httponly = false
) {
$cookie = new http\Cookie();
$cookie->addCookie($name, $value);
$cookie->setExpires($expire);
$cookie->setPath($path);
$cookie->setDomain($domain);
$flags = 0;
if ($secure) {
$flags = Cookie::SECURE;
}
if ($httponly) {
$flags = $flags | Cookie::HTTPONLY;
}
$cookie->setFlags($flags);
Header::header(sprintf('Set-Cookie: %s', $cookie), false);
return true;
} | php | {
"resource": ""
} |
q268030 | HTTP_Request2_SOCKS5.connect | test | public function connect($remoteHost, $remotePort)
{
$request = pack('C5', 0x05, 0x01, 0x00, 0x03, strlen($remoteHost))
. $remoteHost . pack('n', $remotePort);
$this->write($request);
$response = unpack('Cversion/Creply/Creserved', $this->read(1024));
if (5 != $response['version'] || 0 != $response['reserved']) {
throw new HTTP_Request2_MessageException(
'Invalid response received from SOCKS5 proxy',
HTTP_Request2_Exception::MALFORMED_RESPONSE
);
} elseif (0 != $response['reply']) {
throw new HTTP_Request2_ConnectionException(
"Unable to connect to {$remoteHost}:{$remotePort} through SOCKS5 proxy",
0, $response['reply']
);
}
} | php | {
"resource": ""
} |
q268031 | Record.save | test | public function save($validate_datatype = false)
{
$state = $this->getState();
if ($state == self::STATE_DELETED) {
throw new Exception\LogicException(__METHOD__ . "Record has already been deleted in database.");
}
switch ($state) {
case self::STATE_NEW:
// Means insert
$new_record = $this->getTable()->insert($this->toArray(), $validate_datatype);
break;
case self::STATE_CLEAN:
case self::STATE_DIRTY:
// Means update
$predicate = $this->getRecordPrimaryKeyPredicate();
$this->getTable()->update($this->toArray(), $predicate, $combination = Predicate\PredicateSet::OP_AND, $validate_datatype);
$new_record = $this->getTable()->findOneBy($predicate);
break;
//@codeCoverageIgnoreStart
default:
throw new Exception\LogicException(__METHOD__ . ": Record is not on manageable state.");
//@codeCoverageIgnoreEnd
}
/*
if ($state == self::STATE_NEW) {
// Means insert
$new_record = $this->getTable()->insert($data, $validate_datatype);
} elseif ($state == self::STATE_CLEAN || $state == self::STATE_DIRTY) {
// Means update
$predicate = $this->getRecordPrimaryKeyPredicate();
$this->getTable()->update($data, $predicate, $combination=Predicate\PredicateSet::OP_AND, $validate_datatype);
$new_record = $this->getTable()->findOneBy($predicate);
} else {
//@codeCoverageIgnoreStart
throw new Exception\LogicException(__METHOD__ . ": Record is not on manageable state.");
//@codeCoverageIgnoreEnd
}
*/
$this->setData($new_record->toArray());
$this->setState(Record::STATE_CLEAN);
unset($new_record);
return $this;
} | php | {
"resource": ""
} |
q268032 | Record.setData | test | public function setData($data)
{
$state = $this->getState();
if ($state == self::STATE_DELETED) {
throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
}
if (is_array($data)) {
$data = new ArrayObject($data);
} elseif (! $data instanceof ArrayObject) {
throw new Exception\InvalidArgumentException(__METHOD__ . ": Data must be an array of an ArrayObject");
}
$this->_securedFieldForArrayAccess['data'] = $data;
$this->setState(self::STATE_DIRTY);
return $this;
} | php | {
"resource": ""
} |
q268033 | Record.toArray | test | public function toArray()
{
if ($this->getState() == self::STATE_DELETED) {
throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
}
return (array) $this->_securedFieldForArrayAccess['data'];
} | php | {
"resource": ""
} |
q268034 | Record.offsetGet | test | public function offsetGet($field)
{
if ($this->getState() == self::STATE_DELETED) {
throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
}
if (!array_key_exists($field, $this->_securedFieldForArrayAccess['data'])) {
throw new Exception\FieldNotFoundException(__METHOD__ . ": Cannot get field value, field '$field' does not exists in record.");
}
return $this->_securedFieldForArrayAccess['data'][$field];
} | php | {
"resource": ""
} |
q268035 | Record.offsetSet | test | public function offsetSet($field, $value)
{
$state = $this->getState();
if ($state == self::STATE_DELETED) {
throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
}
$this->_securedFieldForArrayAccess['data'][$field] = $value;
if ($state != self::STATE_NEW) {
$this->setState(self::STATE_DIRTY);
}
return $this;
} | php | {
"resource": ""
} |
q268036 | Record.getRecordPrimaryKeyPredicate | test | protected function getRecordPrimaryKeyPredicate()
{
// Get table primary keys
$primary_keys = $this->getTable()->getPrimaryKeys();
$predicate = [];
foreach ($primary_keys as $column) {
$pk_value = $this->offsetGet($column);
if ($pk_value != '') {
$predicate[$column] = $pk_value;
} else {
throw new Exception\UnexpectedValueException(__METHOD__ . ": Cannot find record primary key values. Record has no primary key value set");
}
}
return $predicate;
} | php | {
"resource": ""
} |
q268037 | NativePathParser.parse | test | public function parse(string $path): array
{
// Validate the path for opening and closing tags
$this->validatePath($path);
// Split on [ while skipping placeholders
$segments = $this->getSegments($path);
// The current path
$current = '';
// Iterate through the segments
foreach ($segments as $key => $segment) {
// If this is not the first segment then its an optional group
if ($key > 0) {
// Add a non capturing group around this segment
// NOTE: Since the path was originally split into segments on [
// it is safe to do this as there SHOULD be a closing bracket
// before another required group and so there shouldn't
// be any conflicts in mismatching opening and closing
// regex non-capture groups. This assumes the
// developer did their job correctly in
// the amount of opening required
// and optional groups
$segment = '(?:' . $segment;
}
// Check for any non-capturing groups within <> or <*>
// < > groups are normal non-capturing groups
// < *> groups are repeatable non-capturing groups
// NOTE: have to use an alias to avoid breaking @Annotations() usage
// Replace any end brackets with the appropriate group close
// NOTE: This will take care of missing end brackets in
// previous groups because the only way that occurs
// is when a group is nested within another
$segment = str_replace(
[
// Opening non-capture required group
'<',
// Close non-capture repeatable required group
'*>',
// Close non-capture required group
'>',
// Close non-capture repeatable optional group
'*]',
// Close non-capture optional group
']',
],
[
// Non-capture required group regex open
'(?:',
// Non-capture required repeatable group regex close
')*',
// Non-capture required group regex close
')',
// Non-capture repeatable optional group regex close
')*?',
// Non-capture optional group regex close
')?',
],
$segment
);
$current .= $segment;
}
return $this->parsePath($current, $segments);
} | php | {
"resource": ""
} |
q268038 | NativePathParser.validatePath | test | protected function validatePath(string $path): void
{
// The number of opening required non-capture groups <
$requiredGroupsOpen = substr_count($path, '<');
// The number of closing required non-capture groups >
$requiredGroupsClose = substr_count($path, '>');
// The number of opening optional non-capture groups [
$optionalGroupsOpen = substr_count($path, '[');
// The number of closing optional non-capture groups ]
$optionalGroupsClose = substr_count($path, ']');
// If the count of required opening and closing tags doesn't match
if ($requiredGroupsOpen !== $requiredGroupsClose) {
// Throw an error letting the develop know they made a bad path
throw new InvalidArgumentException(
'Mismatch of required groups for path: ' . $path
);
}
// If the count of optional opening and closing tags doesn't match
if ($optionalGroupsOpen !== $optionalGroupsClose) {
// Throw an error letting the develop know they made a bad path
throw new InvalidArgumentException(
'Mismatch of optional groups for path: ' . $path
);
}
} | php | {
"resource": ""
} |
q268039 | NativePathParser.splitSegments | test | protected function splitSegments(array $segments, string $deliminator): array
{
// The final segments to return
$returnSegments = [];
// Iterate through the segments once more
foreach ($segments as $segment) {
// If the segment has the deliminator
if (strpos($segment, $deliminator) !== false) {
$this->splitSegmentsDeliminator(
$returnSegments,
$segment,
$deliminator
);
continue;
}
// Otherwise set the segment normally
$returnSegments[] = $segment;
}
return $returnSegments;
} | php | {
"resource": ""
} |
q268040 | NativePathParser.parsePath | test | protected function parsePath(string $path, array &$segments): array
{
/* @var array[] $params */
// Get all matches for {paramName} and {paramName:regex} in the path
preg_match_all(
'/' . static::VARIABLE_REGEX . '/x',
$path,
$params
);
$regex = $path;
$paramsReturn = [];
// Run through all matches
foreach ($params[0] as $key => $param) {
// Undo replacements made in parse foreach loop (see line 85)
[$params[0][$key], $params[2][$key]] = str_replace(
[')*?', ')?'],
['*]', ']'],
[$params[0][$key], $params[2][$key]]
);
// Get the regex for this param
$paramRegex = $this->getParamReplacement($key, $params);
// Replace the matches with a regex
$regex = str_replace($param, $paramRegex, $regex);
// What to replace in the segment for this item
$replace = '{' . $params[1][$key] . '}';
// Set the param in the array of params to return
$paramsReturn[$params[1][$key]] = [
'replace' => $replace,
'regex' => $paramRegex,
];
// Iterate through the segments
foreach ($segments as $segmentKey => $segment) {
// Replace this match with the replace text thus removing any regex
// in the segment this fixes any regex with brackets from being
// messed up in the splitSegments() method
$segments[$segmentKey] = str_replace(
$params[0][$key],
$replace,
$segment
);
}
}
$regex = str_replace('/', '\/', $regex);
$regex = '/^' . $regex . '$/';
$segmentsReturn = $this->splitSegments($segments, ']');
$segmentsReturn = $this->splitSegments($segmentsReturn, '<');
$segmentsReturn = $this->splitSegments($segmentsReturn, '>');
return [
'regex' => $regex,
'params' => $paramsReturn,
'segments' => $segmentsReturn,
];
} | php | {
"resource": ""
} |
q268041 | NativePathParser.getParamReplacement | test | protected function getParamReplacement(string $key, array $params): string
{
return config()['app']['pathRegexMap'][$params[2][$key]]
?? '(' . ($params[2][$key] ?: $params[1][$key]) . ')';
} | php | {
"resource": ""
} |
q268042 | CacheableTrait.cache | test | public function cache($key, \Closure $value, $ttl = null)
{
// $value可以是callable或是值
if (static::$cacheManager) {
if (!static::$cacheManager->getAssistant()) {
static::$cacheManager = static::$cacheManager->withTags(get_class($this));
}
return static::$cacheManager->remember(
$key,
$value,
$ttl ?: $this->ttl
);
} else {
return $value();
}
} | php | {
"resource": ""
} |
q268043 | CacheableTrait.flushCache | test | public static function flushCache()
{
// $value可以是callable或是值
if (static::$cacheManager) {
if (!static::$cacheManager->getAssistant()) {
static::$cacheManager = static::$cacheManager->withTags(get_called_class());
}
static::$cacheManager->getAssistant()->flushCache();
}
} | php | {
"resource": ""
} |
q268044 | GuzzleResponse.processResponseData | test | protected function processResponseData($raw)
{
$this->body = $raw->getBody()->__toString();
$rawHeaders = $raw->getHeaders();
foreach ($rawHeaders as $key => $value) {
$this->headers[$key] = implode(', ', $value);
}
$this->statusCode = $raw->getStatusCode();
} | php | {
"resource": ""
} |
q268045 | TMethodInvocation.invokeMethod | test | protected function invokeMethod(array $arguments, $action, $object)
{
if (!method_exists($object, $action))
{
$message = get_class($object) . " object has no {$action} method.";
throw new DispatcherException($message);
}
$reflection = new ReflectionMethod($object, $action);
$parameters = [];
foreach ($reflection->getParameters() as $parameter)
{
if (isset($arguments[$parameter->name]))
{
$parameters[] = $arguments[$parameter->name];
}
elseif ($parameter->isDefaultValueAvailable())
{
$parameters[] = $parameter->getDefaultValue();
}
else
{
$message = "{$parameter->name} argument cannot be resolved.";
throw new DispatcherException($message, $arguments, $action, $object);
}
}
return $reflection->invokeArgs($object, $parameters);
} | php | {
"resource": ""
} |
q268046 | Sendfile.getContentType | test | public function getContentType(): string
{
if (empty($this->content_type) && !empty($this->file)) {
$this->content_type = $this->getMimeType($this->file);
}
return $this->content_type;
} | php | {
"resource": ""
} |
q268047 | SessionHandlerAbstract.regenerateId | test | public function regenerateId($idOld, RequestApplicationInterface $app, $deleteOldSession = false)
{
$self = $this;
$dataOld = [];
$promise = $this->read($idOld)->then(
function($data) { return $data; },
function() { return []; }
)->then(function($data) use ($idOld, &$dataOld) {
$dataOld = $data;
return $this->destroy($idOld)->then(null, function() { return true; });
})->then(
function() use ($self, &$app) {
return $self->createId($app);
}
)->then(
function($newId) use ($self, &$dataOld, $deleteOldSession) {
$retCallback = function() use ($newId) { return $newId; };
$dataNew = $deleteOldSession ? [] : $dataOld;
return $self->write($newId, $dataNew)->then($retCallback, $retCallback);
},
function() use ($idOld) {
$message = sprintf('Failed to regenerate session ID for session "%s"', $idOld);
throw new SessionException($message);
}
);
return $promise;
} | php | {
"resource": ""
} |
q268048 | SessionHandlerAbstract.createId | test | public function createId(RequestApplicationInterface $app)
{
$ip = $app->reqHelper->getRemoteIP();
if (empty($ip)) {
$ip = '127.0.0.1';
}
$time = microtime();
try {
$rand = \Reaction::$app->security->generateRandomString(16);
} catch (\Exception $exception) {
$rand = mt_rand(11111, 99999);
}
$id = md5($ip . ':' . $time . ':' . $rand);
$self = $this;
return $this->checkSessionId($id)->then(
function() use($id) { return $id; },
function() use ($self, &$app) { return $self->createId($app); }
);
} | php | {
"resource": ""
} |
q268049 | SessionHandlerAbstract.createGcTimer | test | protected function createGcTimer()
{
if (isset($this->_timer) && $this->_timer instanceof TimerInterface) {
$this->loop->cancelTimer($this->_timer);
}
$this->_timer = $this->loop->addPeriodicTimer($this->timerInterval, [$this, 'gc']);
} | php | {
"resource": ""
} |
q268050 | Modal.setContent | test | public function setContent($content)
{
if ($content instanceof FormView) {
$this->contentType = 'form';
} elseif ($content instanceof TableView) {
$this->contentType = 'table';
} elseif (is_array($content)) {
$this->contentType = 'data';
} else {
$this->contentType = 'html';
}
$this->content = $content;
return $this;
} | php | {
"resource": ""
} |
q268051 | Modal.setButtons | test | public function setButtons(array $buttons)
{
$resolver = static::getButtonOptionsResolver();
$tmp = [];
foreach ($buttons as $options) {
$tmp[] = $resolver->resolve($options);
}
$this->buttons = $tmp;
return $this;
} | php | {
"resource": ""
} |
q268052 | Modal.addButton | test | public function addButton(array $options, $prepend = false)
{
$resolver = static::getButtonOptionsResolver();
$options = $resolver->resolve($options);
if ($prepend) {
array_unshift($this->buttons, $options);
} else {
array_push($this->buttons, $options);
}
return $this;
} | php | {
"resource": ""
} |
q268053 | Modal.validateType | test | static public function validateType($type, $throwException = true)
{
if (in_array($type, [
self::TYPE_DEFAULT,
self::TYPE_INFO,
self::TYPE_PRIMARY,
self::TYPE_SUCCESS,
self::TYPE_WARNING,
self::TYPE_DANGER,
])) {
return true;
}
if ($throwException) {
throw new \InvalidArgumentException(sprintf('Invalid modal type "%s".', $type));
}
return false;
} | php | {
"resource": ""
} |
q268054 | Modal.validateSize | test | static public function validateSize($size, $throwException = true)
{
if (in_array($size, [
self::SIZE_NORMAL,
self::SIZE_SMALL,
self::SIZE_WIDE,
self::SIZE_LARGE,
])) {
return true;
}
if ($throwException) {
throw new \InvalidArgumentException(sprintf('Invalid modal size "%s".', $size));
}
return false;
} | php | {
"resource": ""
} |
q268055 | Application.registerCommands | test | public function registerCommands()
{
$this->add(new DirectoryAddCommand());
$this->add(new DirectoryDeleteCommand());
$this->add(new DownloadCommand());
$this->add(new ExportCommand());
$this->add(new FileAddCommand());
$this->add(new FileDeleteCommand());
$this->add(new FileUpdateCommand());
$this->add(new StatusCommand());
$this->add(new UploadTranslationCommand());
$this->add(new DownSyncCommand());
$this->add(new ExtractCommand());
$this->add(new UpSyncCommand());
} | php | {
"resource": ""
} |
q268056 | Archive_Tar.Archive_Tar | test | function Archive_Tar($p_tarname, $p_compress = null)
{
$this->PEAR();
$this->_compress = false;
$this->_compress_type = 'none';
if (($p_compress === null) || ($p_compress == '')) {
if (@file_exists($p_tarname)) {
if ($fp = @fopen($p_tarname, "rb")) {
// look for gzip magic cookie
$data = fread($fp, 2);
fclose($fp);
if ($data == "\37\213") {
$this->_compress = true;
$this->_compress_type = 'gz';
// No sure it's enought for a magic code ....
} elseif ($data == "BZ") {
$this->_compress = true;
$this->_compress_type = 'bz2';
}
}
} else {
// probably a remote file or some file accessible
// through a stream interface
if (substr($p_tarname, -2) == 'gz') {
$this->_compress = true;
$this->_compress_type = 'gz';
} elseif ((substr($p_tarname, -3) == 'bz2') ||
(substr($p_tarname, -2) == 'bz')) {
$this->_compress = true;
$this->_compress_type = 'bz2';
}
}
} else {
if (($p_compress === true) || ($p_compress == 'gz')) {
$this->_compress = true;
$this->_compress_type = 'gz';
} else if ($p_compress == 'bz2') {
$this->_compress = true;
$this->_compress_type = 'bz2';
} else {
$this->_error("Unsupported compression type '$p_compress'\n".
"Supported types are 'gz' and 'bz2'.\n");
return false;
}
}
$this->_tarname = $p_tarname;
if ($this->_compress) { // assert zlib or bz2 extension support
if ($this->_compress_type == 'gz')
$extname = 'zlib';
else if ($this->_compress_type == 'bz2')
$extname = 'bz2';
if (!extension_loaded($extname)) {
PEAR::loadExtension($extname);
}
if (!extension_loaded($extname)) {
$this->_error("The extension '$extname' couldn't be found.\n".
"Please make sure your version of PHP was built ".
"with '$extname' support.\n");
return false;
}
}
} | php | {
"resource": ""
} |
q268057 | Archive_Tar.addString | test | function addString($p_filename, $p_string, $p_datetime = false)
{
$v_result = true;
if (!$this->_isArchive()) {
if (!$this->_openWrite()) {
return false;
}
$this->_close();
}
if (!$this->_openAppend())
return false;
// Need to check the get back to the temporary file ? ....
$v_result = $this->_addString($p_filename, $p_string, $p_datetime);
$this->_writeFooter();
$this->_close();
return $v_result;
} | php | {
"resource": ""
} |
q268058 | Archive_Tar._maliciousFilename | test | function _maliciousFilename($file)
{
if (strpos($file, '/../') !== false) {
return true;
}
if (strpos($file, '../') === 0) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q268059 | Plugin.parseCommand | test | public function parseCommand(UserEventInterface $event, EventQueueInterface $queue)
{
// Get the pattern to identify commands
if ($this->nick) {
$nick = $event->getConnection()->getNickname();
$identity = $this->getNickPattern($nick);
} else {
$identity = $this->identityPattern;
}
// Verify this event contains a command and remove the substring
// identifying it as one
$eventParams = $event->getParams();
$target = $event->getCommand() === 'PRIVMSG'
? $eventParams['receivers']
: $eventParams['nickname'];
$message = $eventParams['text'];
if ($identity) {
if (preg_match($identity, $message, $match)) {
$message = preg_replace($identity, '', $message);
} elseif (preg_match($this->channelPattern, $target)) {
return;
}
}
// Parse the command and its parameters
if (!preg_match($this->commandPattern, $message, $match)) {
return;
}
$customCommand = $match['command'];
if (!empty($match['params'])
&& preg_match_all($this->paramsPattern, $match['params'], $matches)) {
$customParams = array_map(
function($param) {
return trim($param, '"');
},
$matches[0]
);
} else {
$customParams = array();
}
// Populate an event object with the parsed data
$commandEvent = $this->getCommandEvent();
$commandEvent->fromEvent($event);
$commandEvent->setCustomCommand($customCommand);
$commandEvent->setCustomParams($customParams);
// Emit the event object to listeners
$customEventName = 'command.' . strtolower($customCommand);
$customEventParams = array($commandEvent, $queue);
$this->getEventEmitter()->emit($customEventName, $customEventParams);
} | php | {
"resource": ""
} |
q268060 | VersionConverter.migrateFrom | test | public function migrateFrom($otherObject)
{
$otherObjectClass = get_class($otherObject);
// same object no migrations needed
if ($otherObjectClass === $this->className) {
return $otherObject;
}
$versionPath = new VersionPathSearch($this->reader);
$migrations = $versionPath->find($otherObjectClass, $this->className);
if (count($migrations) === 0) {
throw new VersionPathNotFoundException($otherObjectClass, $this->className);
}
foreach ($migrations as $migration) {
$otherObject = $migration->action->run($otherObject, $this->options);
}
return $otherObject;
} | php | {
"resource": ""
} |
q268061 | NormalistModels.getUniqueKeys | test | public function getUniqueKeys($table, $include_primary = false)
{
$this->checkTableArgument($table);
return $this->model_definition['tables'][$table]['unique_keys'];
} | php | {
"resource": ""
} |
q268062 | NormalistModels.getPrimaryKey | test | public function getPrimaryKey($table)
{
$this->checkTableArgument($table);
$pks = $this->getPrimaryKeys($table);
if (count($pks) > 1) {
$keys = implode(',', $pks);
throw new Exception\MultiplePrimaryKeyException(__METHOD__ . ". Multiple primary keys found on table '$table': $keys");
}
return $pks[0];
} | php | {
"resource": ""
} |
q268063 | NormalistModels.getPrimaryKeys | test | public function getPrimaryKeys($table)
{
$this->checkTableArgument($table);
$pks = $this->model_definition['tables'][$table]['primary_keys'];
if (count($pks) == 0) {
throw new Exception\NoPrimaryKeyException(__METHOD__ . ". No primary keys found on table '$table'.");
}
return $pks;
} | php | {
"resource": ""
} |
q268064 | PriorityFilter.getPriority | test | protected function getPriority(): PriorityInterface
{
if ($this->priority === null) {
$this->priority = new CriticalPriority();
}
return $this->priority;
} | php | {
"resource": ""
} |
q268065 | PriorityFilter.getValidator | test | protected function getValidator(): ValidatorInterface
{
if ($this->validator === null) {
$this->validator = new GreaterThanValidator(
$this->getPriority()->getValue()
);
}
return $this->validator;
} | php | {
"resource": ""
} |
q268066 | FileHelper.loadMimeTypes | test | protected static function loadMimeTypes($magicFile)
{
if ($magicFile === null) {
$magicFile = static::$mimeMagicFile;
}
$magicFile = \Reaction::$app->getAlias($magicFile);
if (!isset(self::$_mimeTypes[$magicFile])) {
self::$_mimeTypes[$magicFile] = require $magicFile;
}
return self::$_mimeTypes[$magicFile];
} | php | {
"resource": ""
} |
q268067 | FileHelper.loadMimeAliases | test | protected static function loadMimeAliases($aliasesFile)
{
if ($aliasesFile === null) {
$aliasesFile = static::$mimeAliasesFile;
}
$aliasesFile = \Reaction::$app->getAlias($aliasesFile);
if (!isset(self::$_mimeAliases[$aliasesFile])) {
self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
}
return self::$_mimeAliases[$aliasesFile];
} | php | {
"resource": ""
} |
q268068 | FileHelper.unlink | test | public static function unlink($path)
{
$isWindows = DIRECTORY_SEPARATOR === '\\';
if (!$isWindows) {
return unlink($path);
}
if (is_link($path) && is_dir($path)) {
return rmdir($path);
}
try {
return unlink($path);
} catch (ErrorException $e) {
// last resort measure for Windows
$lines = [];
exec('DEL /F/Q ' . escapeshellarg($path), $lines, $deleteError);
return $deleteError !== 0;
}
} | php | {
"resource": ""
} |
q268069 | FileHelper.permissionsAsString | test | public static function permissionsAsString($modeOctal) {
$modeStr = '';
foreach (static::$_permissionsByteMap as $bytes => $flag) {
$modeStr .= (($modeOctal & $bytes) ? $flag : '-');
}
return $modeStr;
} | php | {
"resource": ""
} |
q268070 | FileHelper.permissionsAsOctal | test | public static function permissionsAsOctal($modeStr) {
$modeStr = str_pad($modeStr, 9, '-', STR_PAD_RIGHT);
$modeOctal = 0x0;
$num = 0;
foreach (static::$_permissionsByteMap as $bytes => $flag) {
$modeOctal += (($modeStr[$num] === $flag) ? $bytes : 0x0);
$num++;
}
return $modeOctal;
} | php | {
"resource": ""
} |
q268071 | Searcher.innerJoin | test | public function innerJoin($table, $alias = null)
{
$join = new \Labi\Database\Utility\Join($this, $table, $alias, null, $this->quoteChar());
$join->typeInner();
$this->joins[] = $join;
return $join;
} | php | {
"resource": ""
} |
q268072 | Searcher.toSql | test | public function toSql()
{
if (is_null($this->table)) {
// brak tabeli
throw new \Exception("Please define table for select.");
}
// usuwam rzeczy zwiazane z przetwarzaniem zapytania
$this->reset(true);
// tworze bazowe zapytanie
$alias = $this->alias;
$table = $this->table;
$quoteChar = $this->quoteChar();
// build select
$sql = "select\n";
// columns
$fields = array();
// wybieram tylko te kolumny ktore nie sa ukryte
foreach (array_keys($this->columns) as $field) {
$column = $this->columns[$field];
if ($column->isHidden()) {
continue;
}else{
$fields[] = $field;
}
}
// zliczam wszystkie kolumny
$ccolumn = count($fields);
$added = false;
for ($i=0; $i < $ccolumn; $i++) {
// pobieram zdefiniowana kolumne
$column = $this->columns[$fields[$i]];
if ($column->isHidden()) {
// pomijam ukryte kolumny
continue;
}
$value = $column->value();
$calias = $column->alias();
if (!is_null($calias)) {
$calias = " as {$quoteChar}{$calias}{$quoteChar}";
}else{
$calias = "";
}
if(is_null($value)){
$value = "null";
}
if ($i == $ccolumn-1) {
// last column
$sql .= " {$value}{$calias}\n";
}else{
$sql .= " {$value}{$calias},\n";
}
$added = true;
}
if ($added === false) {
// jak nie ma kolumn to pobieram wszystkie
$sql .= " *\n";
}
$sql .= "from {$quoteChar}{$table}{$quoteChar} as {$quoteChar}{$alias}{$quoteChar}\n";
// joins
foreach ($this->joins as $join) {
$sql .= $join->toSql()."\n";
}
// condition
$condition = $this->condition->toSql();
if (!is_null($condition)) {
$sql .= "where $condition\n";
}
// orders
if(count($this->orders) > 0){
$sql .= 'order by ';
foreach ($this->orders as $order) {
$column = $order['column'];
$type = $order['type'];
$sql .= "$column $type, ";
}
$sql = rtrim($sql, ", ");
$sql .= "\n";
}
// limit
if (!is_null($this->limit)) {
$offset = $this->limit['offset'];
$limit = $this->limit['limit'];
if($offset > 0){
$sql .= "limit {$limit}, {$offset}";
}else{
$sql .= "limit {$limit}";
}
}
$sql = rtrim($sql, "\n");
return $sql;
} | php | {
"resource": ""
} |
q268073 | Searcher.search | test | public function search($params = array())
{
return $this->adapter->fetch($this->toSql(), array_merge($this->params(), $this->params(true), $params));
} | php | {
"resource": ""
} |
q268074 | SQL.createTable | test | public static function createTable($table, array $specs)
{
$sql = 'CREATE TABLE IF NOT EXISTS ' . static::e($table) . ' (';
foreach($specs as $field => $opts) {
$sql .= "\n" . '`' . $field . '` ' . $opts['type'];
if($opts['primary'] == true) {
$opts['nullable'] = false;
$opts['default'] = null;
$sql .= ' PRIMARY KEY AUTOINCREMENT';
}
if(!$opts['nullable']) {
$sql .= ' NOT NULL';
}
if($opts['default']) {
$sql .= ' DEFAULT ' . $opts['default'];
}
$sql .= ',';
}
$sql = trim($sql, ',') . "\n" . ');';
return $sql;
} | php | {
"resource": ""
} |
q268075 | AppBuilder.loadModules | test | protected function loadModules()
{
$moduleMask = implode(
DIRECTORY_SEPARATOR,
array(
$this->appPath->root()->get(),
'src',
$this->contextName.'Module.php',
)
);
foreach ($this->fileSystem->glob($moduleMask) as $filePath) {
$class = $this->loadModule($filePath);
$class->build($this->containerBuilder);
}
} | php | {
"resource": ""
} |
q268076 | AppBuilder.getContainer | test | protected function getContainer()
{
if (!$this->container) {
$this->container = $this->containerBuilder->build();
}
return $this->container;
} | php | {
"resource": ""
} |
q268077 | SwearJarPlugin.init | test | public function init()
{
$swears = array('fu+ck', 'sh+i+t', 'cu+nt', 'co+ck');
$swear_jar = array();
// Don't say bad words, kids.
$re = '/' . implode('|', $swears) . '/i';
$this->bot->onChannel($re, function(Event $event) use (&$swear_jar) {
$cost = 0.25;
$who = $event->getRequest()->getSendingUser();
if (!isset($swear_jar[$who])) {
$swear_jar[$who] = 0;
}
$price = ($swear_jar[$who] += $cost);
$event->addResponse(
Response::msg(
$event->getRequest()->getSource(),
sprintf("Mind your tongue $who! Now you owe \$%.2f to the swear jar.", $price)
));
});
} | php | {
"resource": ""
} |
q268078 | NativeQueryBuilder.select | test | public function select(array $columns = null): QueryBuilder
{
$this->type = Statement::SELECT;
if (null !== $columns) {
$this->columns = $columns;
} else {
$this->columns[] = '*';
}
return $this;
} | php | {
"resource": ""
} |
q268079 | NativeQueryBuilder.table | test | public function table(string $table, string $alias = null): QueryBuilder
{
$this->table = $table . ($alias !== null ? ' ' . $alias : '');
return $this;
} | php | {
"resource": ""
} |
q268080 | NativeQueryBuilder.set | test | public function set(string $column, string $value): QueryBuilder
{
$this->values[$column] = $value;
return $this;
} | php | {
"resource": ""
} |
q268081 | NativeQueryBuilder.where | test | public function where(string $where): QueryBuilder
{
if (empty($this->where)) {
$this->setWhere($where);
return $this;
}
$this->setWhere($where, Statement::WHERE_AND);
return $this;
} | php | {
"resource": ""
} |
q268082 | NativeQueryBuilder.orWhere | test | public function orWhere(string $where): QueryBuilder
{
if (empty($this->where)) {
return $this->where($where);
}
$this->setWhere($where, Statement::WHERE_OR);
return $this;
} | php | {
"resource": ""
} |
q268083 | NativeQueryBuilder.orderByAsc | test | public function orderByAsc(string $column): QueryBuilder
{
$this->setOrderBy($column, OrderBy::ASC);
return $this;
} | php | {
"resource": ""
} |
q268084 | NativeQueryBuilder.orderByDesc | test | public function orderByDesc(string $column): QueryBuilder
{
$this->setOrderBy($column, OrderBy::DESC);
return $this;
} | php | {
"resource": ""
} |
q268085 | NativeQueryBuilder.getQuery | test | public function getQuery(): string
{
if (null !== $this->query) {
return $this->query;
}
switch ($this->type) {
case Statement::SELECT:
$this->query = $this->getSelectQuery();
break;
case Statement::UPDATE:
$this->query = $this->getUpdateQuery();
break;
case Statement::INSERT:
$this->query = $this->getInsertQuery();
break;
case Statement::DELETE:
$this->query = $this->getDeleteQuery();
break;
}
return $this->query;
} | php | {
"resource": ""
} |
q268086 | NativeQueryBuilder.setWhere | test | protected function setWhere(string $where, string $type = null): void
{
if (null !== $type) {
$where = $type . ' ' . $where;
}
$this->where[] = $where;
} | php | {
"resource": ""
} |
q268087 | NativeQueryBuilder.setOrderBy | test | protected function setOrderBy(string $column, string $order = null): void
{
$orderBy = $column;
if (null !== $order) {
$orderBy .= ' ' . $order;
}
$this->orderBy[] = $orderBy;
} | php | {
"resource": ""
} |
q268088 | NativeQueryBuilder.getSelectQuery | test | protected function getSelectQuery(): string
{
return $this->type
. ' ' . implode(', ', $this->columns)
. ' ' . Statement::FROM
. ' ' . $this->table
. ' ' . $this->getWhereQuery()
. ' ' . $this->getOrderByQuery()
. ' ' . $this->getLimitQuery()
. ' ' . $this->getOffsetQuery();
} | php | {
"resource": ""
} |
q268089 | NativeQueryBuilder.getInsertQuery | test | protected function getInsertQuery(): string
{
return $this->type
. ' ' . Statement::INTO
. ' ' . $this->table
. ' (' . implode(', ', array_keys($this->values)) . ')'
. ' ' . Statement::VALUE
. ' (' . implode(', ', $this->values) . ')';
} | php | {
"resource": ""
} |
q268090 | NativeQueryBuilder.getUpdateQuery | test | protected function getUpdateQuery(): string
{
return $this->type
. ' ' . $this->table
. ' ' . $this->getSetQuery()
. ' ' . $this->getWhereQuery()
. ' ' . $this->getOrderByQuery()
. ' ' . $this->getLimitQuery();
} | php | {
"resource": ""
} |
q268091 | NativeQueryBuilder.getDeleteQuery | test | protected function getDeleteQuery(): string
{
return $this->type
. ' ' . Statement::FROM
. ' ' . $this->table
. ' ' . $this->getWhereQuery()
. ' ' . $this->getOrderByQuery()
. ' ' . $this->getLimitQuery();
} | php | {
"resource": ""
} |
q268092 | NativeQueryBuilder.getSetQuery | test | protected function getSetQuery(): string
{
$query = '';
foreach ($this->values as $column => $value) {
if (! empty($query)) {
$query .= ', ';
}
$query .= $column . ' = ' . $value;
}
return Statement::SET . ' ' . $query;
} | php | {
"resource": ""
} |
q268093 | NativeQueryBuilder.getWhereQuery | test | protected function getWhereQuery(): string
{
if (empty($this->where)) {
return '';
}
return Statement::WHERE . ' ' . implode(' ', $this->where);
} | php | {
"resource": ""
} |
q268094 | NativeQueryBuilder.getOrderByQuery | test | protected function getOrderByQuery(): string
{
if (empty($this->orderBy)) {
return '';
}
return Statement::ORDER_BY . ' ' . implode(', ', $this->orderBy);
} | php | {
"resource": ""
} |
q268095 | ExpressionVisitor.dispatch | test | public function dispatch(Expression $expr, AbstractNode $parentNode = null)
{
if ($parentNode === null) {
$parentNode = $this->queryBuilder->where();
}
switch (true) {
case $expr instanceof Comparison:
return $this->walkComparison($expr, $parentNode);
case $expr instanceof Composite:
return $this->walkComposite($expr, $parentNode);
}
throw new \RuntimeException('Unknown Expression: ' . get_class($expr));
} | php | {
"resource": ""
} |
q268096 | UserService.register | test | public function register(array $post)
{
/* @var $form RegisterForm */
$form = $this->getForm(RegisterForm::class);
$model = $this->getModel();
$model->setRole('registered');
$form->setHydrator($this->getHydrator());
$form->bind($model);
/* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
$inputFilter = $this->getInputFilter();
$form->setInputFilter($inputFilter);
return $this->add($post, $form);
} | php | {
"resource": ""
} |
q268097 | UserService.editUser | test | public function editUser(UserModel $model, array $post)
{
if (!$model instanceof UserModel) {
throw new UthandoUserException('$model must be an instance of UthandoUser\Model\User, ' . get_class($model) . ' given.');
}
$model->setDateModified();
/* @var $form UserEditForm */
$form = $this->getForm(UserEditForm::class);
$form->setHydrator($this->getHydrator());
$form->bind($model);
/* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
$inputFilter = $this->getInputFilter();
// we need to find if this email has changed,
// if not then exclude it from validation,
// if changed then reevaluate it.
$email = ($model->getEmail() === $post['email']) ? $model->getEmail() : null;
$inputFilter->addEmailNoRecordExists($email);
$form->setInputFilter($inputFilter);
$form->setData($post);
$form->setValidationGroup([
'firstname', 'lastname', 'email', 'userId', 'security'
]);
if (!$form->isValid()) {
return $form;
}
$saved = $this->save($form->getData());
$this->updateSession($saved, $model);
return $saved;
} | php | {
"resource": ""
} |
q268098 | Version.get_version | test | public function get_version($asArray=false) {
// trigger_error("Deprecated function called (". __METHOD__ .")", E_USER_NOTICE);
// return self::parse_version_file($this->versionFileLocation, $asArray);
if($asArray) {
$retval = $this->_versionData;
$retval['version_string'] = self::build_full_version_string($this->_versionData);
}
else {
// $retval = self::build_full_version_string($this->_versionData);
$retval = $this->_fullVersionString;
}
return $retval;
} | php | {
"resource": ""
} |
q268099 | RequestApplication.createRoute | test | public function createRoute($routePath = null, $method = null, $params = null, $onlyReturn = false)
{
$withInternalCtrl = $routePath !== null;
$routePath = isset($routePath) ? $routePath : $this->reqHelper->getPathInfo();
$method = isset($method) ? $method : $this->reqHelper->getMethod();
$data = Reaction::$app->router->searchRoute($this, $routePath, $method, $withInternalCtrl);
//Parameters overwrite
if (is_array($params) && count($data) >= 3) {
$data[3] = $params;
}
$route = Reaction::create([
'class' => RouteInterface::class,
'app' => $this,
'dispatchedData' => $data,
]);
if (!$onlyReturn) {
$this->_route = $route;
}
return $route;
} | php | {
"resource": ""
} |