_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 33
8k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q267100
|
File.incrVersion
|
test
|
public function incrVersion($filename)
{
$pat = "|^\d+$|";
$parts = explode(".", $filename);
$partsCount = count($parts);
if ($partsCount == 1) {
return $filename . ".1";
}
if ($partsCount == 2) {
if (preg_match($pat, $parts[1])) {
return $parts[0] . "." . ++$parts[1];
}
return $parts[0] . ".1." . $parts[1];
}
if (preg_match($pat, $parts[$partsCount - 1])) {
return implode(".", array_slice($parts, 0, -1)) . "." . ++$parts[$partsCount - 1];
}
|
php
|
{
"resource": ""
}
|
q267101
|
Response.getBody
|
test
|
public function getBody($format = 'object')
{
if (! $this->isValidBodyFormat($format)) {
return;
}
$method = 'body' .
|
php
|
{
"resource": ""
}
|
q267102
|
Response.bodyArray
|
test
|
protected function bodyArray()
{
if (is_xml($this->body)) {
return xml_decode($this->body, true);
}
|
php
|
{
"resource": ""
}
|
q267103
|
Response.bodyObject
|
test
|
protected function bodyObject()
{
if (is_xml($this->body)) {
return xml_decode($this->body);
}
|
php
|
{
"resource": ""
}
|
q267104
|
QueryService.getResultsFromQuery
|
test
|
public function getResultsFromQuery($query, $limit = 0, $connection='default')
{
try
{
$this->queryValidator->isValidQuery($query, $connection);
$query = $this->queryValidator->getLimitedQuery($query, $limit);
$this->dynamicRepo->setUp($connection);
$res = $this->dynamicRepo->execute($query);
$duration = $this->dynamicRepo->getExecutionDuration();
$duration = number_format($duration, 7, '.', ',');
return [
"results" => $res,
"duration" => $duration
];
}
catch (ParameterNotPassedException $e)
{
throw $e;
}
catch (ValidationFailedException $e)
{
|
php
|
{
"resource": ""
}
|
q267105
|
Response.setDefaults
|
test
|
public function setDefaults()
{
if ( !$this->getResponseCode() ) $this->setResponseCode(200);
if
|
php
|
{
"resource": ""
}
|
q267106
|
Response.setBody
|
test
|
public function setBody(Body $body)
{
parent::setBody($body);
|
php
|
{
"resource": ""
}
|
q267107
|
Response.toArray
|
test
|
public function toArray($default = true)
{
if ( $default ) $this->setDefaults();
return array(
'responseCode' => $this->getResponseCode(),
|
php
|
{
"resource": ""
}
|
q267108
|
Versions.getUniqueValidationRule
|
test
|
protected function getUniqueValidationRule($field) {
$rule = 'unique:' . get_class($this) . ',' . $field . ',' . $this->getHeadId() . ',id';
// ignore other versions of this entity
|
php
|
{
"resource": ""
}
|
q267109
|
Url.fromS3
|
test
|
public function fromS3($key, $expiration = null, $downloadAs = null)
{
$args = array();
if (!empty($downloadAs)) {
if (empty($expiration)) {
throw new \RuntimeException("Unable to set download name on URL without expiration.");
}
$args['ResponseContentDisposition'] = 'attachment;filename='.$downloadAs;
|
php
|
{
"resource": ""
}
|
q267110
|
Adodb.getAdapter
|
test
|
public static function getAdapter(\ADOConnection $adoConnection)
{
$adoConnectionDriver = strtolower(get_class($adoConnection));
switch ($adoConnectionDriver) {
//case 'adodb_mysqlt':
case 'adodb_mysqli':
$connectionId = self::getADOConnectionId($adoConnection);
$adapter = Mysqli::getAdapter($connectionId);
break;
case 'adodb_pdo':
case 'adodb_pdo_mysql':
|
php
|
{
"resource": ""
}
|
q267111
|
Adodb.getADOConnectionId
|
test
|
protected static function getADOConnectionId(\ADOConnection $adoConnection)
{
$connectionId = $adoConnection->_connectionID;
if (!$connectionId) {
throw new Exception\AdoNotConnectedException(__METHOD__ . ".
|
php
|
{
"resource": ""
}
|
q267112
|
ErrorController.actionError
|
test
|
public function actionError(RequestApplicationInterface $app, \Throwable $exception) {
$logMessage = get_class($exception);
if ($exception->getMessage()) {
$logMessage .= "\n" . $exception->getMessage();
}
if ($exception->getFile() || $exception->getLine()) {
|
php
|
{
"resource": ""
}
|
q267113
|
HTTP_Request2_Adapter_Curl.wrapCurlError
|
test
|
protected static function wrapCurlError($ch)
{
$nativeCode = curl_errno($ch);
$message = 'Curl error: ' . curl_error($ch);
if (!isset(self::$errorMap[$nativeCode])) {
return new HTTP_Request2_Exception($message, 0, $nativeCode);
} else {
$class = self::$errorMap[$nativeCode][0];
|
php
|
{
"resource": ""
}
|
q267114
|
HTTP_Request2_Adapter_Curl.callbackReadBody
|
test
|
protected function callbackReadBody($ch, $fd, $length)
{
if (!$this->eventSentHeaders) {
$this->request->setLastEvent(
'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
);
$this->eventSentHeaders = true;
}
if (in_array($this->request->getMethod(), self::$bodyDisallowed)
|| 0 == $this->contentLength || $this->position >= $this->contentLength
) {
return '';
}
if (is_string($this->requestBody)) {
$string = substr($this->requestBody, $this->position, $length);
|
php
|
{
"resource": ""
}
|
q267115
|
HTTP_Request2_Adapter_Curl.callbackWriteHeader
|
test
|
protected function callbackWriteHeader($ch, $string)
{
// we may receive a second set of headers if doing e.g. digest auth
if ($this->eventReceivedHeaders || !$this->eventSentHeaders) {
// don't bother with 100-Continue responses (bug #15785)
if (!$this->eventSentHeaders
|| $this->response->getStatus() >= 200
) {
$this->request->setLastEvent(
'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
);
}
$upload = curl_getinfo($ch, CURLINFO_SIZE_UPLOAD);
// if body wasn't read by a callback, send event with total body size
if ($upload > $this->position) {
$this->request->setLastEvent(
'sentBodyPart', $upload - $this->position
);
$this->position = $upload;
}
if ($upload && (!$this->eventSentHeaders
|| $this->response->getStatus() >= 200)
) {
$this->request->setLastEvent('sentBody', $upload);
}
$this->eventSentHeaders = true;
// we'll need a new response object
if ($this->eventReceivedHeaders) {
$this->eventReceivedHeaders = false;
$this->response = null;
}
}
if (empty($this->response)) {
$this->response = new HTTP_Request2_Response(
$string, false, curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)
);
} else {
$this->response->parseHeaderLine($string);
if ('' == trim($string)) {
// don't bother with 100-Continue responses (bug #15785)
if (200 <= $this->response->getStatus()) {
$this->request->setLastEvent('receivedHeaders', $this->response);
}
if ($this->request->getConfig('follow_redirects') && $this->response->isRedirect()) {
|
php
|
{
"resource": ""
}
|
q267116
|
HTTP_Request2_Adapter_Curl.callbackWriteBody
|
test
|
protected function callbackWriteBody($ch, $string)
{
// cURL calls WRITEFUNCTION callback without calling HEADERFUNCTION if
// response doesn't start with proper HTTP status line (see bug #15716)
if (empty($this->response)) {
throw new HTTP_Request2_MessageException(
|
php
|
{
"resource": ""
}
|
q267117
|
Console.addCommandCollection
|
test
|
public function addCommandCollection(CommandCollection $collection)
{
$collection->setConsole($this);
|
php
|
{
"resource": ""
}
|
q267118
|
Console.printTime
|
test
|
private function printTime(string $text): void
{
$line
|
php
|
{
"resource": ""
}
|
q267119
|
Console.printConsoleHelp
|
test
|
private function printConsoleHelp(ClassType $class): void
{
$this->printLine($class->getDescription());
$this->printLine();
foreach ($this->getMethod($class) as $method) {
$line = $class->getShortName() . ':' . $method->name;
foreach ($method->getParameters() as $param) {
$line .= ' /' . $param->getName();
if ($param->isDefaultValueAvailable()) {
$line .= '=' . $this->getValue($param->getDefaultValue());
}
|
php
|
{
"resource": ""
}
|
q267120
|
Console.printHtmlHelp
|
test
|
private function printHtmlHelp(ClassType $class): void
{
$desc = Html::el('h1');
$desc->setText($class->getDescription());
$this->printLine((string) $desc);
foreach ($this->getMethod($class) as $method) {
$desc = Html::el('pre');
$desc->setStyle('margin-bottom: 0px');
$desc->setText(Strings::replace($method->getDocComment(), '/(\ |\t)+/', ' '));
$el = Html::el('a');
$el->setHtml($method->name);
$args = '';
$params = [];
foreach ($method->getParameters() as $param) {
$p = $param->getName();
if ($param->isDefaultValueAvailable()) {
$value = $param->getDefaultValue();
$p .= '=' . $this->getValue($value);
} else {
$args .= (empty($args) ? '?' : '&') . $param->getName() . '=';
|
php
|
{
"resource": ""
}
|
q267121
|
Console.printLine
|
test
|
public function printLine(string $string = null): void
{
if ($string !== null) {
echo $string;
|
php
|
{
"resource": ""
}
|
q267122
|
Application.__async_upload
|
test
|
public function __async_upload()
{
/** @var array $result Asynchronous result array */
$result = array('status' => false);
/** @var \samsonphp\upload\Upload $upload Pointer to uploader object */
$upload = null;
// If file was uploaded
|
php
|
{
"resource": ""
}
|
q267123
|
Application.__async_clearHtml
|
test
|
public function __async_clearHtml()
{
// Tags that do not change
$allowed_tags = '<b><i><sup><sub><em><strong><u><br><p><table><tr><td><tbody><thead><h1><h2><h3><h4><img><a>';
// Getting html value
$html = json_decode(file_get_contents('php://input'), true);
// Replace tags class
$html = strip_tags($html['html'], $allowed_tags);
// Replace tags class
$html = preg_replace("/<([^>]*)(class)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
// Replace tags lang
$html = preg_replace("/<([^>]*)(lang)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
// Replace tags style
$html = preg_replace("/<([^>]*)(style)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
// Replace tags size
$html = preg_replace("/<([^>]*)(size)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
// Replace all
|
php
|
{
"resource": ""
}
|
q267124
|
JsonAttributeBehavior.beforeSave
|
test
|
public function beforeSave($event)
{
foreach ($this->attributes as $name) {
if (!empty($this->owner->$name)) {
$this->owner->$name
|
php
|
{
"resource": ""
}
|
q267125
|
JsonAttributeBehavior.afterFind
|
test
|
public function afterFind($event)
{
foreach ($this->attributes as
|
php
|
{
"resource": ""
}
|
q267126
|
JsonAttributeBehavior.jsonDecodeAttribute
|
test
|
public function jsonDecodeAttribute($name, $assoc = true, $depth = 512)
{
$string = json_decode($this->owner->$name, $assoc, $depth);
if (json_last_error() !== JSON_ERROR_NONE) {
|
php
|
{
"resource": ""
}
|
q267127
|
Factory.create
|
test
|
public static function create(Bank $bank, $type)
{
if (!isset(self::$allowedTypes[$type])) {
throw new \Exception('Type is not allowed!');
}
$class = __NAMESPACE__ . '\\' . $bank->getParser();
|
php
|
{
"resource": ""
}
|
q267128
|
Zend_Filter_Boolean.setLocale
|
test
|
public function setLocale($locale = null)
{
if (is_string($locale)) {
$locale = array($locale);
} elseif ($locale instanceof Zend_Locale) {
$locale = array($locale->toString());
} elseif (!is_array($locale)) {
|
php
|
{
"resource": ""
}
|
q267129
|
Zend_Filter_Boolean._getLocalizedQuestion
|
test
|
protected function _getLocalizedQuestion($value, $yes, $locale)
{
if ($yes == true) {
$question = 'yes';
$return = true;
} else {
$question = 'no';
$return = false;
}
$str = Zend_Locale::getTranslation($question, 'question', $locale);
$str = explode(':', $str);
|
php
|
{
"resource": ""
}
|
q267130
|
HTTP_Request2_Adapter_Socket.establishTunnel
|
test
|
protected function establishTunnel()
{
$donor = new self;
$connect = new HTTP_Request2(
$this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
array_merge($this->request->getConfig(), array('adapter' => $donor))
);
$response = $connect->send();
|
php
|
{
"resource": ""
}
|
q267131
|
HTTP_Request2_Adapter_Socket.canKeepAlive
|
test
|
protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
{
// Do not close socket on successful CONNECT request
if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod()
&& 200 <= $response->getStatus() && 300 > $response->getStatus()
) {
return true;
}
$lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding'))
|| null !== $response->getHeader('content-length')
// no body possible for such responses, see also request #17031
|
php
|
{
"resource": ""
}
|
q267132
|
HTTP_Request2_Adapter_Socket.disconnect
|
test
|
protected function disconnect()
{
if (!empty($this->socket)) {
$this->socket = null;
|
php
|
{
"resource": ""
}
|
q267133
|
HTTP_Request2_Adapter_Socket.handleRedirect
|
test
|
protected function handleRedirect(
HTTP_Request2 $request, HTTP_Request2_Response $response
) {
if (is_null($this->redirectCountdown)) {
$this->redirectCountdown = $request->getConfig('max_redirects');
}
if (0 == $this->redirectCountdown) {
$this->redirectCountdown = null;
// Copying cURL behaviour
throw new HTTP_Request2_MessageException(
'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed',
HTTP_Request2_Exception::TOO_MANY_REDIRECTS
);
}
$redirectUrl = new Net_URL2(
$response->getHeader('location'),
array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
);
// refuse non-HTTP redirect
if ($redirectUrl->isAbsolute()
&& !in_array($redirectUrl->getScheme(), array('http', 'https'))
) {
$this->redirectCountdown = null;
throw new HTTP_Request2_MessageException(
'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(),
HTTP_Request2_Exception::NON_HTTP_REDIRECT
);
}
// Theoretically URL should be
|
php
|
{
"resource": ""
}
|
q267134
|
HTTP_Request2_Adapter_Socket.shouldUseServerDigestAuth
|
test
|
protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
{
// no sense repeating a request if we don't have credentials
if (401 != $response->getStatus() || !$this->request->getAuth()) {
return false;
}
if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
return false;
}
$url = $this->request->getUrl();
$scheme = $url->getScheme();
$host = $scheme . '://' . $url->getHost();
if ($port = $url->getPort()) {
if ((0 == strcasecmp($scheme, 'http') && 80 != $port)
|| (0 == strcasecmp($scheme, 'https') && 443 != $port)
) {
$host .= ':' . $port;
}
}
if (!empty($challenge['domain'])) {
$prefixes = array();
foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
// don't bother with different servers
|
php
|
{
"resource": ""
}
|
q267135
|
HTTP_Request2_Adapter_Socket.shouldUseProxyDigestAuth
|
test
|
protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
{
if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
return false;
}
if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
return false;
}
$key = 'proxy://' . $this->request->getConfig('proxy_host') .
':' . $this->request->getConfig('proxy_port');
if (!empty(self::$challenges[$key])
|
php
|
{
"resource": ""
}
|
q267136
|
HTTP_Request2_Adapter_Socket.writeBody
|
test
|
protected function writeBody()
{
if (in_array($this->request->getMethod(), self::$bodyDisallowed)
|| 0 == $this->contentLength
) {
return;
}
$position = 0;
$bufferSize = $this->request->getConfig('buffer_size');
$headers = $this->request->getHeaders();
$chunked = isset($headers['transfer-encoding']);
while ($position < $this->contentLength) {
if (is_string($this->requestBody)) {
$str = substr($this->requestBody, $position, $bufferSize);
} elseif (is_resource($this->requestBody)) {
$str = fread($this->requestBody, $bufferSize);
} else {
$str = $this->requestBody->read($bufferSize);
}
if (!$chunked) {
$this->socket->write($str);
} else {
|
php
|
{
"resource": ""
}
|
q267137
|
HTTP_Request2_Adapter_Socket.readChunked
|
test
|
protected function readChunked($bufferSize)
{
// at start of the next chunk?
if (0 == $this->chunkLength) {
$line = $this->socket->readLine($bufferSize);
if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
throw new HTTP_Request2_MessageException(
"Cannot decode chunked response, invalid chunk length '{$line}'",
HTTP_Request2_Exception::DECODE_ERROR
|
php
|
{
"resource": ""
}
|
q267138
|
grid.sqlBuildSelect
|
test
|
public static function sqlBuildSelect($arrSelect, $addSelect = false)
{
$select = null;
if (is_array($arrSelect))
{
foreach ($arrSelect as $f => $v)
{
if ($select) $select .= ', ';
if (preg_match('/^(.+?):(literal)$/i', $f, $arrMatch))
$select .= $v;
else
|
php
|
{
"resource": ""
}
|
q267139
|
grid.sqlBuildWhere
|
test
|
public static function sqlBuildWhere($arrWhere, $whereClause = true)
{
$where = null;
if (is_array($arrWhere))
{
if ($whereClause)
$where = ' WHERE 1 ';
foreach ($arrWhere as $f => $v)
{
if ($where)
$where .= ' AND ';
$field = $f;
// special suff?
if (preg_match('/^(.+?):(literal|int|string)$/i', $f, $arrMatch))
{
$type = array_pop($arrMatch);
$f = self::getDSN()->escape(array_pop($arrMatch));
// literal - becareful with these!!!!
if ($type == 'literal')
{
// make sure this literal was not passed in the URL (GET!!)
if (!empty($_GET['where'][$field]))
unset($_GET['where'][$field]);
else if (!empty($_POST['where'][$field]))
unset($_POST['where'][$field]);
else
{
$where .= $v;
}
|
php
|
{
"resource": ""
}
|
q267140
|
grid.sqlBuildJoin
|
test
|
public static function sqlBuildJoin($arrJoin)
{
$joins = null;
if (is_array($arrJoin))
{
foreach ($arrJoin as $v)
{
|
php
|
{
"resource": ""
}
|
q267141
|
grid.sqlBuildGroupBy
|
test
|
public static function sqlBuildGroupBy($arrGroup, $addGroup = false)
{
$groupBy = $group = null;
if (is_array($arrGroup))
{
$group = '';
foreach ($arrGroup as
|
php
|
{
"resource": ""
}
|
q267142
|
grid.prepareDependencyHandler
|
test
|
public static function prepareDependencyHandler($handleType, $field, &$arrField, &$arrGridPrepare, &$arrFormData)
{
// select fields?
if (isset($arrField['dependency']['selectField']) && is_array($arrField['dependency']['selectField']))
{
foreach($arrField['dependency']['selectField'] as $f => $v)
{
$arrGridPrepare['selectField'][$f] = $v;
}
}
// total joins
if (isset($arrField['dependency']['joinTotal']) && is_array($arrField['dependency']['joinTotal']))
{
foreach($arrField['dependency']['joinTotal'] as $f => $v)
{
$arrGridPrepare['joinTotal'][$f] = $v;
}
}
// row joins
if (isset($arrField['dependency']['joinRow']) && is_array($arrField['dependency']['joinRow']))
{
foreach($arrField['dependency']['joinRow'] as $f => $v)
{
$arrGridPrepare['joinRow'][$f] = $v;
}
}
// rowFunctions
if (isset($arrField['dependency']['rowFunctions']) && is_array($arrField['dependency']['rowFunctions']))
{
foreach ($arrField['dependency']['rowFunctions'] as $f => $v)
{
$arrGridPrepare['rowFunctions'][$f] = $v;
|
php
|
{
"resource": ""
}
|
q267143
|
grid.getDataFunctionMergeMapping
|
test
|
public static function getDataFunctionMergeMapping(&$arrRows, &$arrResults, &$arrMapping, $arrRowsAdditonalKey = null)
{
if (is_array($arrResults))
{
foreach($arrResults as $mapId => $arrResult)
{
if (isset($arrMapping[$mapId]) && is_array($arrMapping[$mapId]))
{
foreach($arrMapping[$mapId] as $rowId)
{
if (isset($arrRows[$rowId]))
{
if (isset($arrRowsAdditonalKey))
|
php
|
{
"resource": ""
}
|
q267144
|
grid.cleanString
|
test
|
public static function cleanString($string)
{
$string = str_replace(array(' ', '<br/>', '<br>'), ' ', $string);
$string = strip_tags($string);
|
php
|
{
"resource": ""
}
|
q267145
|
CallPrediction.check
|
test
|
public function check(array $calls, FunctionProphecy $prophecy)
{
if (count($calls)) {
return;
}
$methodCalls = $prophecy->getNamespace()->findCalls($prophecy->getName(), new ArgumentsWildcard([new AnyValuesToken()]));
if (count($methodCalls)) {
throw new NoCallsException(sprintf(
"No calls have been made that match:\n".
" %s(%s)\n".
"but expected at least one.\n".
"Recorded `%s(...)` calls:\n%s",
|
php
|
{
"resource": ""
}
|
q267146
|
Zend_Config_Yaml._decodeYaml
|
test
|
protected static function _decodeYaml($currentIndent, &$lines)
{
$config = array();
$inIndent = false;
while (list($n, $line) = each($lines)) {
$lineno = $n + 1;
$line = rtrim(preg_replace("/#.*$/", "", $line));
if (strlen($line) == 0) {
continue;
}
$indent = strspn($line, " ");
// line without the spaces
$line = trim($line);
if (strlen($line) == 0) {
continue;
}
if ($indent < $currentIndent) {
// this level is done
prev($lines);
return $config;
}
if (!$inIndent) {
$currentIndent = $indent;
$inIndent = true;
}
if (preg_match("/(?!-)([\w\-]+):\s*(.*)/", $line, $m)) {
// key: value
if (strlen($m[2])) {
// simple key: value
$value = preg_replace("/#.*$/", "", $m[2]);
$value = self::_parseValue($value);
} else {
// key: and then values on new lines
$value = self::_decodeYaml($currentIndent + 1, $lines);
if (is_array($value) && !count($value)) {
$value = "";
}
}
|
php
|
{
"resource": ""
}
|
q267147
|
PEAR_Task_Replace.startSession
|
test
|
function startSession($pkg, $contents, $dest)
{
$subst_from = $subst_to = array();
foreach ($this->_replacements as $a) {
$a = $a['attribs'];
$to = '';
if ($a['type'] == 'pear-config') {
if ($this->installphase == PEAR_TASK_PACKAGE) {
return false;
}
if ($a['to'] == 'master_server') {
$chan = $this->registry->getChannel($pkg->getChannel());
if (!PEAR::isError($chan)) {
$to = $chan->getServer();
} else {
$this->logger->log(0, "$dest: invalid pear-config replacement: $a[to]");
return false;
}
} else {
if ($this->config->isDefinedLayer('ftp')) {
// try the remote config file first
$to = $this->config->get($a['to'], 'ftp', $pkg->getChannel());
if (is_null($to)) {
// then default to local
$to = $this->config->get($a['to'], null, $pkg->getChannel());
}
} else {
$to = $this->config->get($a['to'], null, $pkg->getChannel());
}
}
if (is_null($to)) {
$this->logger->log(0, "$dest: invalid pear-config replacement: $a[to]");
return false;
}
} elseif ($a['type'] == 'php-const') {
if ($this->installphase == PEAR_TASK_PACKAGE) {
|
php
|
{
"resource": ""
}
|
q267148
|
Component.exec
|
test
|
public function exec($query, $values = array())
{
if ($stmt = $this->prepare($query)) {
$result = $this->execute($stmt, $values);
|
php
|
{
"resource": ""
}
|
q267149
|
Component.insert
|
test
|
public function insert($table, array $data, $and = '')
{
if (isset($this->prepared[$table])) {
return $this->execute($table, $data);
}
$single = (count(array_filter(array_keys($data), 'is_string')) > 0) ? $data : false;
if ($single) {
$data = array_keys($data);
}
if (stripos($table, ' INTO ') !== false) { // eg. 'OR IGNORE INTO table'
$query = "INSERT {$table} ";
} else {
$query = "INSERT INTO {$table} ";
}
|
php
|
{
"resource": ""
}
|
q267150
|
Component.update
|
test
|
public function update($table, $id, array $data, $and = '')
{
if (isset($this->prepared[$table])) {
$data[] = $id;
return $this->execute($table, $data);
}
$first = each($data);
$single = (is_array($first['value'])) ? $first['value'] : false;
if ($single) {
$data = array_keys($single);
}
if (stripos($table, ' SET ') !== false) { // eg. 'table SET date = NOW(),'
$query = "UPDATE {$table} ";
} else {
$query
|
php
|
{
"resource": ""
}
|
q267151
|
Component.upsert
|
test
|
public function upsert($table, $id, array $data)
{
if (isset($this->prepared[$table]['ref']) && $this->execute($table, $id)) {
$data[] = $id;
if ($row = $this->fetch($table)) {
return ($this->execute($this->prepared[$table]['ref']['update'], $data)) ? array_shift($row) : false;
} else {
return $this->execute($this->prepared[$table]['ref']['insert'], $data);
}
}
$first = each($data);
$single = (is_array($first['value'])) ? $first['value'] : false;
if ($single) {
$data = array_keys($single);
}
|
php
|
{
"resource": ""
}
|
q267152
|
Component.query
|
test
|
public function query($select, $values = array(), $fetch = 'row')
{
if ($stmt = $this->prepare($select, $fetch)) {
if ($this->prepared[$stmt]['type'] == 'SELECT' && $this->execute($stmt, $values)) {
|
php
|
{
"resource": ""
}
|
q267153
|
Component.all
|
test
|
public function all($select, $values = array(), $fetch = 'row')
{
$rows = array();
if ($stmt = $this->query($select, $values, $fetch)) {
while ($row = $this->fetch($stmt)) {
|
php
|
{
"resource": ""
}
|
q267154
|
Component.ids
|
test
|
public function ids($select, $values = array())
{
$ids = array();
if ($stmt = $this->query($select, $values, 'row')) {
while ($row = $this->fetch($stmt)) {
$ids[] = (int)
|
php
|
{
"resource": ""
}
|
q267155
|
Component.row
|
test
|
public function row($select, $values = array(), $fetch = 'row')
{
if ($stmt = $this->query($select, $values, $fetch)) {
$row = $this->fetch($stmt);
|
php
|
{
"resource": ""
}
|
q267156
|
Component.value
|
test
|
public function value($select, $values = array())
{
|
php
|
{
"resource": ""
}
|
q267157
|
Component.prepare
|
test
|
public function prepare($query, $fetch = null)
{
$query = (is_array($query)) ? trim(implode("\n", $query)) : trim($query);
$stmt = count(static::$logs[$this->id]) + 1;
$start = microtime(true);
$this->prepared[$stmt]['obj'] = $this->dbPrepare($query);
static::$logs[$this->id][$stmt] = array(
'sql' => $query,
'count' => 0,
'prepared' => microtime(true) - $start,
'executed' => 0,
);
$this->prepared[$stmt]['params'] = substr_count($query, '?');
$this->prepared[$stmt]['type'] = strtoupper(strtok($query, " \r\n\t"));
if ($this->prepared[$stmt]['type'] == 'SELECT') {
|
php
|
{
"resource": ""
}
|
q267158
|
Component.execute
|
test
|
public function execute($stmt, $values = null)
{
if (isset($this->prepared[$stmt])) {
if (!is_array($values)) {
$values = ($this->prepared[$stmt]['params'] == 1) ? array($values) : array();
}
$start = microtime(true);
if ($this->dbExecute($this->prepared[$stmt]['obj'], array_values($values), $stmt)) {
static::$logs[$this->id][$stmt]['executed'] += microtime(true) - $start;
static::$logs[$this->id][$stmt]['count']++;
switch ($this->prepared[$stmt]['type']) {
case 'SELECT':
return true;
break;
case 'INSERT':
|
php
|
{
"resource": ""
}
|
q267159
|
Component.fetch
|
test
|
public function fetch($stmt)
{
if (isset($this->prepared[$stmt]) && $this->prepared[$stmt]['type'] ==
|
php
|
{
"resource": ""
}
|
q267160
|
Component.log
|
test
|
public function log($value = null)
{
$log = (is_numeric($value)) ? static::$logs[$this->id][$value] : end(static::$logs[$this->id]);
if (isset($log['errors'])) {
$log['errors'] = array_count_values($log['errors']);
}
$log['average'] = ($log['count'] > 0) ? $log['executed'] / $log['count'] : 0;
$log['total'] = $log['prepared'] + $log['executed'];
$log['time'] = round($log['total'] * 1000).' ms';
|
php
|
{
"resource": ""
}
|
q267161
|
ValueFactory.parseValue
|
test
|
public function parseValue($value)
{
foreach ($this->mappings as $mapping => $replace) {
if (is_callable($replace)) {
$value = preg_replace_callback($mapping, $replace, $value);
} else {
|
php
|
{
"resource": ""
}
|
q267162
|
Zend_Filter_PregReplace.filter
|
test
|
public function filter($value)
{
if ($this->_matchPattern == null) {
throw new Zend_Filter_Exception(get_class($this) . ' does not have a valid MatchPattern set.');
}
|
php
|
{
"resource": ""
}
|
q267163
|
NativeKernel.dispatchRouter
|
test
|
protected function dispatchRouter(Request $request): Response
{
// Set the request object in the container
$this->app->container()->singleton(Request::class, $request);
// Dispatch the before request handled middleware
$middlewareReturn = $this->requestMiddleware($request);
// If the middleware returned a response
|
php
|
{
"resource": ""
}
|
q267164
|
NativeKernel.terminateRouteMiddleware
|
test
|
protected function terminateRouteMiddleware(Request $request, Response $response): void
{
// Ensure a route exists
if (! $this->app->container()->isSingleton(Route::class)) {
return;
}
/* @var Route $route */
$route = $this->app->container()->getSingleton(Route::class);
// If the dispatched route has middleware
|
php
|
{
"resource": ""
}
|
q267165
|
PEAR_XMLParser.startHandler
|
test
|
function startHandler($parser, $element, $attribs)
{
$this->_depth++;
$this->_dataStack[$this->_depth] = null;
$val = array(
'name' => $element,
'value' => null,
'type' => 'string',
'childrenKeys' => array(),
'aggregKeys' => array()
);
if (count($attribs) > 0)
|
php
|
{
"resource": ""
}
|
q267166
|
PEAR_XMLParser.endHandler
|
test
|
function endHandler($parser, $element)
{
$value = array_pop($this->_valStack);
$data = $this->postProcess($this->_dataStack[$this->_depth], $element);
// adjust type of the value
switch (strtolower($value['type'])) {
// unserialize an array
case 'array':
if ($data !== '') {
$value['children']['_content'] = $data;
}
$value['value'] = isset($value['children']) ? $value['children'] : array();
break;
/*
* unserialize a null value
*/
case 'null':
$data = null;
break;
/*
* unserialize any scalar value
*/
default:
settype($data, $value['type']);
$value['value'] = $data;
break;
}
$parent = array_pop($this->_valStack);
if ($parent === null) {
$this->_unserializedData = &$value['value'];
|
php
|
{
"resource": ""
}
|
q267167
|
AssetConverter.runCommand
|
test
|
protected function runCommand($command, $basePath, $asset, $result)
{
$command = Reaction::$app->getAlias($command);
$command = strtr($command, [
'{from}' => escapeshellarg("$basePath/$asset"),
'{to}' => escapeshellarg("$basePath/$result"),
]);
$descriptor = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$pipes = [];
$proc = proc_open($command, $descriptor, $pipes, $basePath);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
foreach ($pipes as $pipe) {
fclose($pipe);
}
$status = proc_close($proc);
|
php
|
{
"resource": ""
}
|
q267168
|
NotifyViaSlackJob.process
|
test
|
public function process()
{
// $this->channel evaluates to blank in the following if, so store it as a variable
$channel = $this->channel;
$client = new Client($this->webhookURL);
if (empty($channel)) {
$client->send($this->message);
} else {
|
php
|
{
"resource": ""
}
|
q267169
|
CroppableBehavior.modifyUploadableBehavior
|
test
|
protected function modifyUploadableBehavior()
{
$table = $this->getTable();
if ($table->hasBehavior('uploadable')) {
$uploadable = $table->getBehavior('uploadable');
$parameters = $uploadable->getParameters();
$up_columns = explode(',', $parameters['columns']);
foreach (array_keys($this->getColumns()) as $column) {
foreach ($up_columns as $up_column) {
if (trim($up_column) == $column) {
continue 2;
}
}
$up_columns[] = $column;
}
$parameters['columns'] = implode(',', $up_columns);
|
php
|
{
"resource": ""
}
|
q267170
|
Request.fromJSON
|
test
|
public static function fromJSON($json)
{
$request = new static();
print_r($json);
$data = json_decode($json, true);
print_r($data);
if (!$data) {
throw new UnexpectedValueException(sprintf(
'Unexpected message, invalid JSON from nginx: "%s"', $json
));
}
if (isset($data['id'])) {
$request->setId($data['id']);
}
if
|
php
|
{
"resource": ""
}
|
q267171
|
Database.open
|
test
|
public function open($savePath, $name)
{
$this->sessionSavePath = $savePath;
|
php
|
{
"resource": ""
}
|
q267172
|
Database.read
|
test
|
public function read($id)
{
$idColumn = $this->options->getIdColumn();
$nameColumn = $this->options->getNameColumn();
$adapter = $this->getAdapter();
$sessionData = [
$idColumn => $id,
$nameColumn => $this->sessionName
];
$session = $adapter->select($sessionData);
|
php
|
{
"resource": ""
}
|
q267173
|
Database.destroy
|
test
|
public function destroy($id)
{
$idColumn = $this->options->getIdColumn();
$nameColumn = $this->options->getNameColumn();
$adapter = $this->getAdapter();
$sessionData = [
$idColumn => $id,
$nameColumn =>
|
php
|
{
"resource": ""
}
|
q267174
|
Database.write
|
test
|
public function write($id, $data)
{
$idColumn = $this->options->getIdColumn();
$nameColumn = $this->options->getNameColumn();
$dataColumn = $this->options->getDataColumn();
$modifiedColumn = $this->options->getModifiedColumn();
$createdColumn = $this->options->getCreatedColumn();
$lifetimeColumn = $this->options->getLifetimeColumn();
$adapter = $this->getAdapter();
$sessionData = [
$idColumn => $id,
$nameColumn => $this->sessionName
];
$session = $adapter->select($sessionData);
|
php
|
{
"resource": ""
}
|
q267175
|
Widget.widget
|
test
|
public static function widget($config = [])
{
ob_start();
ob_implicit_flush(false);
try {
/* @var $widget Widget */
$config['class'] = get_called_class();
$widget = Reaction::create($config);
$out = '';
if ($widget->beforeRun()) {
$result = $widget->run();
$out = $widget->afterRun($result);
}
} catch (\Exception
|
php
|
{
"resource": ""
}
|
q267176
|
Widget.getId
|
test
|
public function getId($autoGenerate = true)
{
if ($autoGenerate && $this->_id === null) {
$this->_id = static::$autoIdPrefix
|
php
|
{
"resource": ""
}
|
q267177
|
Widget.beforeRun
|
test
|
public function beforeRun()
{
$isValid = true;
|
php
|
{
"resource": ""
}
|
q267178
|
Widget.checkAppPersistence
|
test
|
protected function checkAppPersistence()
{
if (!isset($this->app) || !$this->app instanceof Reaction\RequestApplicationInterface) {
$message = sprintf("You must specify \$app (RequestApplicationInterface) parameter for widget
|
php
|
{
"resource": ""
}
|
q267179
|
Model.where
|
test
|
public static function where($field, $value, $dbConn = NULL)
{
$table = Backbone::getTable(get_called_class(), $dbConn);
if (is_null($dbConn)) {
$dbConn = Backbone::makeDbConn();
}
try {
$query = $dbConn->prepare('SELECT * FROM ' . $table . ' WHERE ' . $field . ' = ?');
$query->execute([$value]);
} catch (PDOException $e) {
return $e->getMessage();
} finally {
$dbConn = null;
}
|
php
|
{
"resource": ""
}
|
q267180
|
Model.destroy
|
test
|
public static function destroy($record, $dbConn = NULL)
{
$table = Backbone::getTable(get_called_class(), $dbConn);
if (is_null($dbConn)) {
$dbConn = Backbone::makeDbConn();
}
try {
$query = $dbConn->prepare('DELETE FROM
|
php
|
{
"resource": ""
}
|
q267181
|
Model.getAll
|
test
|
public static function getAll($dbConn = NULL)
{
$table = Backbone::getTable(get_called_class(), $dbConn);
if (is_null($dbConn)) {
$dbConn = Backbone::makeDbConn();
}
try {
$query = $dbConn->prepare('SELECT
|
php
|
{
"resource": ""
}
|
q267182
|
Model.save
|
test
|
public function save($dbConn = NULL)
{
$table = Backbone::getTable(get_called_class(), $dbConn);
if (is_null($dbConn)) {
$dbConn = Backbone::makeDbConn();
}
try {
if (isset($this->record['dbData']) && is_array($this->record['dbData'])) {
$sql = 'UPDATE ' . $table . ' SET ' . Backbone::tokenize(implode(',', Backbone::joinKeysAndValuesOfArray($this->record)), ',') . ' WHERE id=' . $this->record['dbData']['id'];
$query = $dbConn->prepare($sql);
$query->execute();
} else {
$sql = 'INSERT INTO ' .
|
php
|
{
"resource": ""
}
|
q267183
|
Budget.index
|
test
|
public function index()
{
//~ Breadcrumb
$this->breadcrumb->add((new BreadcrumbItem('List'))->setIcon('list')->setIsActive(true));
$get = Get::getInstance();
$params = $this->route->getParameterCollection();
$account = null;
$date = new \DateTimeImmutable(date('Y-m-01'));
if ($params->hasByName('id')) {
$account = $this->verifyAccount((int) $params->getByName('id')->getValue());
if ($get->has('date_start')) {
$date = new \DateTimeImmutable($get->get('date_start'));
$date = $date->setDate($date->format('Y'), $date->format('m'), 1);
}
|
php
|
{
"resource": ""
}
|
q267184
|
Budget.ajaxList
|
test
|
public function ajaxList()
{
if (!Server::getInstance()->isAjax()) {
throw new \RuntimeException();
}
$get = Get::getInstance();
$accountId = (int) $this->route->getParameterCollection()->getByName('id')->getValue();
//~ Retrieve user account / account
$account = $this->verifyAccount($accountId);
if ($get->has('date_start')) {
$dateStart = new \DateTimeImmutable($get->get('date_start'));
} else {
$dateStart = new \DateTimeImmutable(date('Y-m-01'));
}
$budgetMapper = new BudgetMapper(Database::get('money'));
$budgets = $budgetMapper->findAllByDate($account, $dateStart);
$this->dataCollection->add('account', $account);
|
php
|
{
"resource": ""
}
|
q267185
|
Budget.verifyAccount
|
test
|
protected function verifyAccount($accountId)
{
//~ Verify if account is for current user, else throw error 500
$mapper = new AccountUserMapper(Database::get('money'));
|
php
|
{
"resource": ""
}
|
q267186
|
Budget.loadNavBar
|
test
|
protected function loadNavBar()
{
$this->breadcrumb->add((new BreadcrumbItem('Budget'))
->setIcon('money')
->setUri('#'));
$bankMapper = new BankMapper(Database::get('money'));
$banks = $bankMapper->select();
$accountUserMapper = new AccountUserMapper(Database::get('money'));
$userAccounts = $accountUserMapper->findByUserId((int) Session::getInstance()->get('id'));
$accounts = array();
foreach ($userAccounts as $userAccount) {
$account = $userAccount->getAccount();
if ($account->isVirtual()) {
continue;
}
if (!isset($accounts[$account->getBankId()])) {
|
php
|
{
"resource": ""
}
|
q267187
|
Budget.checkMonth
|
test
|
protected function checkMonth($accountId, \DateTimeImmutable $date)
{
$mapper = new BudgetMapper(Database::get('money'));
$budgetMonthMapper
|
php
|
{
"resource": ""
}
|
q267188
|
PEAR_Installer_Role_Cfg.setup
|
test
|
function setup(&$installer, $pkg, $atts, $file)
{
$this->installer = &$installer;
$reg = &$this->installer->config->getRegistry();
$package = $reg->getPackage($pkg->getPackage(), $pkg->getChannel());
if ($package) {
$filelist = $package->getFilelist();
|
php
|
{
"resource": ""
}
|
q267189
|
Route.execute
|
test
|
public function execute(...$constructParameters)
{
$class = $this->class;
$method = $this->method;
$parameters = array_values($this->parameters);
|
php
|
{
"resource": ""
}
|
q267190
|
User.name
|
test
|
public function name()
{
if(isset($this->first_name) && isset($this->surname))
return $this->first_name . ' ' . $this->surname;
elseif(isset($this->first_name))
|
php
|
{
"resource": ""
}
|
q267191
|
User.save
|
test
|
public function save()
{
$reflection = new \ReflectionObject($this);
$properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
foreach($properties as $prop)
|
php
|
{
"resource": ""
}
|
q267192
|
User.changePass
|
test
|
public function changePass($old, $new1, $new2)
{
if(!$this->auth->authUser($this->user, $old))
return False;
elseif($new1 != $new2)
return False;
else
|
php
|
{
"resource": ""
}
|
q267193
|
BindingsBuilder.give
|
test
|
public function give( $implementation )
{
$this->container->addContextualBindings(
|
php
|
{
"resource": ""
}
|
q267194
|
LoggerFactory.getWriter
|
test
|
protected function getWriter(ServiceLocatorInterface $serviceLocator, string $name,
|
php
|
{
"resource": ""
}
|
q267195
|
Version.parseVersion
|
test
|
private function parseVersion()
{
if (StaticStringy::startsWith($this->versionString, 'v')) {
$this->versionString = StaticStringy::substr($this->versionString, 1);
}
if (strstr($this->versionString, '-')) {
if (sscanf(
$this->versionString,
'%d.%d.%d-%s',
$this->major,
$this->minor,
$this->release,
$this->suffix
)
|
php
|
{
"resource": ""
}
|
q267196
|
Version.compare
|
test
|
public function compare(VersionInterface $version)
{
if ($this->getMajorVersion() < $version->getMajorVersion()) {
return -1;
} elseif ($this->getMajorVersion() > $version->getMajorVersion()) {
return 1;
} else {
if ($this->getMinorVersion() < $version->getMinorVersion()) {
return -1;
} elseif ($this->getMinorVersion() > $version->getMinorVersion()) {
return 1;
} else {
|
php
|
{
"resource": ""
}
|
q267197
|
ClosureTreeBehavior.getBranch
|
test
|
public function getBranch($parentId)
{
$criteria = new CDbCriteria();
$criteria->index = 'descendantId';
$criteria->addCondition('ancestorId=:parentId AND depth=1');
$criteria->params[':parentId'] = $parentId;
|
php
|
{
"resource": ""
}
|
q267198
|
ClosureTreeBehavior.getParent
|
test
|
public function getParent()
{
// Load the "current" level from the tree
$currentLevel = CActiveRecord::model($this->treeClass)->findByAttributes(
array('descendantId' => $this->owner->{$this->idAttribute}, 'depth' => 1)
);
if ($currentLevel->ancestorId > 0) {
|
php
|
{
"resource": ""
}
|
q267199
|
ClosureTreeBehavior.getParents
|
test
|
public function getParents($includeSelf = true)
{
$parents = array();
if ($includeSelf) {
$parents[$this->owner->{$this->idAttribute}] = $this->owner;
}
// Try and find a parent
$parent = $this->getParent();
if ($parent instanceof CActiveRecord) {
$parents[$parent->{$this->idAttribute}] = $parent;
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.