_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| 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];
}
if (preg_match($pat, $parts[$partsCount - 2])) {
return implode(
".",
array_slice($parts, 0, -2)
)
. "." . ++$parts[$partsCount - 2]
. "." . $parts[$partsCount - 1];
}
return implode(".", array_slice($parts, 0, -1)) . ".1." . $parts[$partsCount - 1];
} | php | {
"resource": ""
} |
q267101 | Response.getBody | test | public function getBody($format = 'object')
{
if (! $this->isValidBodyFormat($format)) {
return;
}
$method = 'body' . ucfirst($format);
return call_user_func_array([$this, $method], [null]);
} | php | {
"resource": ""
} |
q267102 | Response.bodyArray | test | protected function bodyArray()
{
if (is_xml($this->body)) {
return xml_decode($this->body, true);
}
if (is_json($this->body)) {
return json_decode($this->body, true);
}
} | php | {
"resource": ""
} |
q267103 | Response.bodyObject | test | protected function bodyObject()
{
if (is_xml($this->body)) {
return xml_decode($this->body);
}
if (is_json($this->body)) {
return json_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)
{
throw $e;
}
catch (TypeNotValidException $e)
{
throw $e;
}
catch (DBALException $e)
{
$exceptionText = "There was an error when executing the query, your database's message:\n\n{$e->getPrevious()->getMessage()}";
throw new DatabaseException($exceptionText, 500, $e);
}
} | php | {
"resource": ""
} |
q267105 | Response.setDefaults | test | public function setDefaults()
{
if ( !$this->getResponseCode() ) $this->setResponseCode(200);
if ( !$this->getContentType() ) $this->setContentType('text/html');
if ( !$this->getServer() ) $this->setServer('Skeetr 0.0.1');
} | php | {
"resource": ""
} |
q267106 | Response.setBody | test | public function setBody(Body $body)
{
parent::setBody($body);
return $this->addHeaders(array(
'Content-Length' => (string) strlen($this->body)
), true);
} | php | {
"resource": ""
} |
q267107 | Response.toArray | test | public function toArray($default = true)
{
if ( $default ) $this->setDefaults();
return array(
'responseCode' => $this->getResponseCode(),
'body' => $this->getBody()->toString(),
'headers' => $this->getHeaders()
);
} | 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
if($this->getHeadId()) {
$rule .= ',headVersion,!=,' . $this->getHeadId();
}
return $rule;
} | 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;
}
return $this->getServiceLocator()->get('FzyCommon\Service\Aws\S3')->getObjectUrl($this->getServiceLocator()->get('FzyCommon\Service\Aws\S3\Config')->get('bucket'), $key, $expiration, $args);
} | 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':
$connectionId = self::getADOConnectionId($adoConnection);
$adapter = PDO::getAdapter($connectionId);
break;
default:
throw new Exception\UnsupportedDriverException(__METHOD__ . ". Driver '$adoConnectionDriver' not supported");
}
return $adapter;
} | php | {
"resource": ""
} |
q267111 | Adodb.getADOConnectionId | test | protected static function getADOConnectionId(\ADOConnection $adoConnection)
{
$connectionId = $adoConnection->_connectionID;
if (!$connectionId) {
throw new Exception\AdoNotConnectedException(__METHOD__ . ". Error: Invalid usage, adodb connection must be connected before use (see connect(), pconnect()");
}
return $connectionId;
} | 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()) {
$logMessage .= "\n" . $exception->getFile() . ":" . $exception->getLine();
}
\Reaction::$app->logger->logRaw($logMessage);
} | 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];
$code = empty(self::$errorMap[$nativeCode][1])
? 0 : self::$errorMap[$nativeCode][1];
return new $class($message, $code, $nativeCode);
}
} | 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);
} elseif (is_resource($this->requestBody)) {
$string = fread($this->requestBody, $length);
} else {
$string = $this->requestBody->read($length);
}
$this->request->setLastEvent('sentBodyPart', strlen($string));
$this->position += strlen($string);
return $string;
} | 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()) {
$redirectUrl = new Net_URL2($this->response->getHeader('location'));
// for versions lower than 5.2.10, check the redirection URL protocol
if (!defined('CURLOPT_REDIR_PROTOCOLS') && $redirectUrl->isAbsolute()
&& !in_array($redirectUrl->getScheme(), array('http', 'https'))
) {
return -1;
}
if ($jar = $this->request->getCookieJar()) {
$jar->addCookiesFromResponse($this->response, $this->request->getUrl());
if (!$redirectUrl->isAbsolute()) {
$redirectUrl = $this->request->getUrl()->resolve($redirectUrl);
}
if ($cookies = $jar->getMatching($redirectUrl, true)) {
curl_setopt($ch, CURLOPT_COOKIE, $cookies);
}
}
}
$this->eventReceivedHeaders = true;
}
}
return strlen($string);
} | 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(
"Malformed response: {$string}",
HTTP_Request2_Exception::MALFORMED_RESPONSE
);
}
if ($this->request->getConfig('store_body')) {
$this->response->appendBody($string);
}
$this->request->setLastEvent('receivedBodyPart', $string);
return strlen($string);
} | php | {
"resource": ""
} |
q267117 | Console.addCommandCollection | test | public function addCommandCollection(CommandCollection $collection)
{
$collection->setConsole($this);
$class = new ClassType($collection);
$this->collections[Strings::lower($class->getShortName())] = $collection;
} | php | {
"resource": ""
} |
q267118 | Console.printTime | test | private function printTime(string $text): void
{
$line = '[' . date('d.m.Y H:i:s', time()) . '] ' . $text;
$this->printLine($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());
}
}
$description = $method->getDescription();
if (!empty($description)) {
$line .= "\t\t(" . Strings::replace($description, '/\ +/', ' ') . ')';
}
$this->printLine($line);
}
$this->printLine();
} | 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() . '=';
}
$params[] = $p;
}
$link = Strings::lower(str_replace(':', '/', $this->prefix . '/' . $class->getShortName()) . '/' . $method->name);
$el->href('/' . $link . $args);
$line = $desc . $el;
if (!empty($params)) {
$line .= ' (' . implode(', ', $params) . ')';
}
$this->printLine($line);
}
} | php | {
"resource": ""
} |
q267121 | Console.printLine | test | public function printLine(string $string = null): void
{
if ($string !== null) {
echo $string;
}
if ($this->isConsole) {
echo "\n";
} else {
echo '<br/>';
}
} | 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
if (uploadFile($upload)) {
$result['status'] = true;
$result['tag'] = '<img src="' . $upload->fullPath() . '">';
}
// Return result
return $result;
} | 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 transfers and
$html = str_replace(array("\r\n", "\r", "\n", ' '), ' ', $html);
// Replace empty tags p and b
$html = str_replace(array("<p> </p>", "<p></p>", "<b> </b>", "<b></b>"), '', $html);
// Added border to table
$html = str_replace(array("<table"), '<table border="1"', $html);
return array('status' => 1, 'data' => $html);
} | php | {
"resource": ""
} |
q267124 | JsonAttributeBehavior.beforeSave | test | public function beforeSave($event)
{
foreach ($this->attributes as $name) {
if (!empty($this->owner->$name)) {
$this->owner->$name = $this->jsonEncodeAttribute($name);
} else {
$this->owner->$name = null;
}
}
} | php | {
"resource": ""
} |
q267125 | JsonAttributeBehavior.afterFind | test | public function afterFind($event)
{
foreach ($this->attributes as $name) {
$this->owner->$name = $this->jsonDecodeAttribute($name);
}
} | 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) {
throw new CException(sprintf('Failed to decode JSON attribute "%s".', $name));
}
return $string;
} | 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();
if (!class_exists($class)) {
throw new \Exception();
}
return new $class();
} | 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)) {
throw new Zend_Filter_Exception('Locale has to be string, array or an instance of Zend_Locale');
}
foreach ($locale as $single) {
if (!Zend_Locale::isLocale($single)) {
throw new Zend_Filter_Exception("Unknown locale '$single'");
}
}
$this->_locale = $locale;
return $this;
} | 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);
if (!empty($str)) {
foreach($str as $no) {
if (($no == $value) || (strtolower($no) == strtolower($value))) {
return $return;
}
}
}
} | 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();
// Need any successful (2XX) response
if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
throw new HTTP_Request2_ConnectionException(
'Failed to connect via HTTPS proxy. Proxy response: ' .
$response->getStatus() . ' ' . $response->getReasonPhrase()
);
}
$this->socket = $donor->socket;
$this->socket->enableCrypto();
} | 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
|| HTTP_Request2::METHOD_HEAD == $this->request->getMethod()
|| in_array($response->getStatus(), array(204, 304));
$persistent = 'keep-alive' == strtolower($response->getHeader('connection')) ||
(null === $response->getHeader('connection') &&
'1.1' == $response->getVersion());
return $requestKeepAlive && $lengthKnown && $persistent;
} | php | {
"resource": ""
} |
q267132 | HTTP_Request2_Adapter_Socket.disconnect | test | protected function disconnect()
{
if (!empty($this->socket)) {
$this->socket = null;
$this->request->setLastEvent('disconnect');
}
} | 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 absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
// but in practice it is often not
if (!$redirectUrl->isAbsolute()) {
$redirectUrl = $request->getUrl()->resolve($redirectUrl);
}
$redirect = clone $request;
$redirect->setUrl($redirectUrl);
if (303 == $response->getStatus()
|| (!$request->getConfig('strict_redirects')
&& in_array($response->getStatus(), array(301, 302)))
) {
$redirect->setMethod(HTTP_Request2::METHOD_GET);
$redirect->setBody('');
}
if (0 < $this->redirectCountdown) {
$this->redirectCountdown--;
}
return $this->sendRequest($redirect);
} | 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
if ('/' == substr($prefix, 0, 1)) {
$prefixes[] = $host . $prefix;
}
}
}
if (empty($prefixes)) {
$prefixes = array($host . '/');
}
$ret = true;
foreach ($prefixes as $prefix) {
if (!empty(self::$challenges[$prefix])
&& (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
) {
// probably credentials are invalid
$ret = false;
}
self::$challenges[$prefix] =& $challenge;
}
return $ret;
} | 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])
&& (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
) {
$ret = false;
} else {
$ret = true;
}
self::$challenges[$key] = $challenge;
return $ret;
} | 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 {
$this->socket->write(dechex(strlen($str)) . "\r\n{$str}\r\n");
}
// Provide the length of written string to the observer, request #7630
$this->request->setLastEvent('sentBodyPart', strlen($str));
$position += strlen($str);
}
// write zero-length chunk
if ($chunked) {
$this->socket->write("0\r\n\r\n");
}
$this->request->setLastEvent('sentBody', $this->contentLength);
} | 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
);
} else {
$this->chunkLength = hexdec($matches[1]);
// Chunk with zero length indicates the end
if (0 == $this->chunkLength) {
$this->socket->readLine($bufferSize);
return '';
}
}
}
$data = $this->socket->read(min($this->chunkLength, $bufferSize));
$this->chunkLength -= strlen($data);
if (0 == $this->chunkLength) {
$this->socket->readLine($bufferSize); // Trailing CRLF
}
return $data;
} | 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
$select .= self::getDSN()->escape($v);
}
}
if ($addSelect && $select)
$addSelect = ' SELECT ' . $addSelect;
return $select;
} | 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;
}
}
else if ($type == 'int')
$where .= $f .' IN ('. self::getDSN()->escape($v) .') ';
else if ($type == 'string')
$where .= $f . self::sqlWhereSmartLike($v);
else
$where .= $f .' = "'. self::getDSN()->escape($v) .'" ';
}
else
$where .= $f .' = "' . self::getDSN()->escape($v) . '" ';
}
}
return $where;
} | php | {
"resource": ""
} |
q267140 | grid.sqlBuildJoin | test | public static function sqlBuildJoin($arrJoin)
{
$joins = null;
if (is_array($arrJoin))
{
foreach ($arrJoin as $v)
{
$joins .= $v . " \n";
}
$joins = " \n" . $joins;
}
return $joins;
} | php | {
"resource": ""
} |
q267141 | grid.sqlBuildGroupBy | test | public static function sqlBuildGroupBy($arrGroup, $addGroup = false)
{
$groupBy = $group = null;
if (is_array($arrGroup))
{
$group = '';
foreach ($arrGroup as $k)
{
if ($group) $group .= ', ';
$group .= self::getDSN()->escape($k);
}
}
if ($addGroup && $group)
$groupBy = ' GROUP BY ' . $group;
return $groupBy;
} | 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;
}
}
// total groups
if (isset($arrField['dependency']['groupTotal']) && is_array($arrField['dependency']['groupTotal']))
{
foreach ($arrField['dependency']['groupTotal'] as $f => $v)
{
$arrGridPrepare['groupTotal'][$f] = $v;
}
}
// row groups
if (isset($arrField['dependency']['groupRow']) && is_array($arrField['dependency']['groupRow']))
{
foreach ($arrField['dependency']['groupRow'] as $f => $v)
{
$arrGridPrepare['groupRow'][$f] = $v;
}
}
// dataFunctions
if (isset($arrField['dependency']['dataFunctions']) && is_array($arrField['dependency']['dataFunctions']))
{
foreach ($arrField['dependency']['dataFunctions'] as $f => $v)
{
$arrGridPrepare['dataFunctions'][$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))
$arrRows[$rowId][$arrRowsAdditonalKey] = $arrResult;
else
$arrRows[$rowId] = array_merge($arrResult, $arrRows[$rowId]);
}
}
}
}
}
} | php | {
"resource": ""
} |
q267144 | grid.cleanString | test | public static function cleanString($string)
{
$string = str_replace(array(' ', '<br/>', '<br>'), ' ', $string);
$string = strip_tags($string);
$string = str_replace(' ', ' ', $string);
return $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",
$prophecy->getName(),
$prophecy->getArgumentsWildcard(),
$prophecy->getName(),
$this->util->stringifyCalls($methodCalls)
));
}
throw new NoCallsException(sprintf(
"No calls have been made that match:\n".
" %s(%s)\n".
'but expected at least one.',
$prophecy->getName(),
$prophecy->getArgumentsWildcard()
));
} | 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 = "";
}
}
$config[$m[1]] = $value;
} elseif ($line[0] == "-") {
// item in the list:
// - FOO
if (strlen($line) > 2) {
$value = substr($line, 2);
$config[] = self::_parseValue($value);
} else {
$config[] = self::_decodeYaml($currentIndent + 1, $lines);
}
} else {
throw new Zend_Config_Exception(sprintf(
'Error parsing YAML at line %d - unsupported syntax: "%s"',
$lineno, $line
));
}
}
return $config;
} | 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) {
return false;
}
if (defined($a['to'])) {
$to = constant($a['to']);
} else {
$this->logger->log(0, "$dest: invalid php-const replacement: $a[to]");
return false;
}
} else {
if ($t = $pkg->packageInfo($a['to'])) {
$to = $t;
} else {
$this->logger->log(0, "$dest: invalid package-info replacement: $a[to]");
return false;
}
}
if (!is_null($to)) {
$subst_from[] = $a['from'];
$subst_to[] = $to;
}
}
$this->logger->log(3, "doing " . sizeof($subst_from) .
" substitution(s) for $dest");
if (sizeof($subst_from)) {
$contents = str_replace($subst_from, $subst_to, $contents);
}
return $contents;
} | php | {
"resource": ""
} |
q267148 | Component.exec | test | public function exec($query, $values = array())
{
if ($stmt = $this->prepare($query)) {
$result = $this->execute($stmt, $values);
$this->close($stmt);
}
return (isset($result)) ? $result : false;
} | 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} ";
}
$query .= '('.implode(', ', $data).') VALUES ('.implode(', ', array_fill(0, count($data), '?')).') '.$and;
$stmt = $this->prepare($query);
if ($single && $stmt) {
$id = $this->insert($stmt, array_values($single));
$this->close($stmt);
return $id;
}
return $stmt;
} | 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 = "UPDATE {$table} SET ";
}
$query .= implode(' = ?, ', $data).' = ? WHERE '.$id.' = ? '.$and;
$stmt = $this->prepare($query);
if ($single && $stmt) {
$affected = $this->update($stmt, $first['key'], array_values($single));
$this->close($stmt);
return $affected;
}
return $stmt;
} | 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);
}
if ($stmt = $this->prepare("SELECT {$id} FROM {$table} WHERE {$id} = ?", 'row')) {
$this->prepared[$stmt]['ref']['update'] = $this->update($table, $id, $data);
$this->prepared[$stmt]['ref']['insert'] = $this->insert($table, array_merge($data, array($id)));
}
if ($single && $stmt) {
$id = $this->upsert($stmt, $first['key'], array_values($single));
$this->close($stmt);
return $id;
}
return $stmt;
} | 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)) {
return $stmt;
}
$this->close($stmt);
}
return false;
} | 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)) {
$rows[] = $row;
}
$this->close($stmt);
}
return $rows;
} | 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) array_shift($row);
}
$this->close($stmt);
}
return (!empty($ids)) ? $ids : false;
} | 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);
$this->close($stmt);
}
return (isset($row) && !empty($row)) ? $row : false;
} | php | {
"resource": ""
} |
q267156 | Component.value | test | public function value($select, $values = array())
{
return ($row = $this->row($select, $values, 'row')) ? array_shift($row) : false;
} | 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') {
$this->prepared[$stmt]['style'] = $this->dbStyle(strtolower((string) $fetch));
}
if ($this->prepared[$stmt]['obj'] === false) {
unset($this->prepared[$stmt]);
if ($error = $this->dbPrepareError()) {
static::$logs[$this->id][$stmt]['errors'][] = $error;
}
return false;
}
return $stmt;
} | 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':
return $this->dbInserted();
default:
return $this->dbAffected($this->prepared[$stmt]['obj']);
}
} elseif ($error = $this->dbExecuteError($this->prepared[$stmt]['obj'])) {
static::$logs[$this->id][$stmt]['errors'][] = $error;
}
}
return false;
} | php | {
"resource": ""
} |
q267159 | Component.fetch | test | public function fetch($stmt)
{
if (isset($this->prepared[$stmt]) && $this->prepared[$stmt]['type'] == 'SELECT') {
return $this->dbFetch($this->prepared[$stmt]['obj'], $this->prepared[$stmt]['style'], $stmt);
}
return false;
} | 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';
if ($log['count'] > 1) {
$log['time'] .= ' (~'.round($log['average'] * 1000).' ea)';
}
if (is_null($value) || is_numeric($value)) {
return $log;
}
return (isset($log[$value])) ? $log[$value] : null;
} | 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 {
$value = preg_replace($mapping, $replace, $value);
}
}
return $value;
} | 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.');
}
return preg_replace($this->_matchPattern, $this->_replacement, $value);
} | 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
if ($middlewareReturn instanceof Response) {
// Return the response
return $middlewareReturn;
}
return $this->router->dispatch($request);
} | 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
if (null !== $route->getMiddleware()) {
// Terminate each middleware
$this->terminableMiddleware(
$request,
$response,
$route->getMiddleware()
);
}
} | 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) {
$val['children'] = array();
$val['type'] = 'array';
$val['children']['attribs'] = $attribs;
}
array_push($this->_valStack, $val);
} | 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'];
$this->_root = &$value['name'];
return true;
}
// parent has to be an array
if (!isset($parent['children']) || !is_array($parent['children'])) {
$parent['children'] = array();
if ($parent['type'] != 'array') {
$parent['type'] = 'array';
}
}
if (!empty($value['name'])) {
// there already has been a tag with this name
if (in_array($value['name'], $parent['childrenKeys'])) {
// no aggregate has been created for this tag
if (!in_array($value['name'], $parent['aggregKeys'])) {
if (isset($parent['children'][$value['name']])) {
$parent['children'][$value['name']] = array($parent['children'][$value['name']]);
} else {
$parent['children'][$value['name']] = array();
}
array_push($parent['aggregKeys'], $value['name']);
}
array_push($parent['children'][$value['name']], $value['value']);
} else {
$parent['children'][$value['name']] = &$value['value'];
array_push($parent['childrenKeys'], $value['name']);
}
} else {
array_push($parent['children'],$value['value']);
}
array_push($this->_valStack, $parent);
$this->_depth--;
} | 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);
if ($status === 0) {
Reaction::$app->logger->debug("Converted $asset into $result:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr");
} elseif (Reaction::isDev()) {
throw new Exception("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr");
} else {
Reaction::error("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr");
}
return $status === 0;
} | 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 {
#Send to designated channel
$client->to($this->channel)->send($this->message);
}
// required to terminate the job
$this->isComplete = true;
$this->currentStep = 1;
} | 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);
$uploadable->setParameters($parameters);
} else {
$uploadable = new UploadableBehavior();
$uploadable->setName('uploadable');
$uploadable->setParameters(array(
'columns' => implode(',', array_keys($this->getColumns()))
));
$table->addBehavior($uploadable);
}
} | 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 (isset($data['method'])) {
$request->setMethod($data['method']);
}
if (isset($data['params'])) {
$request->setPrams($data['params']);
}
return $request;
} | php | {
"resource": ""
} |
q267171 | Database.open | test | public function open($savePath, $name)
{
$this->sessionSavePath = $savePath;
$this->sessionName = $name;
return true;
} | 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);
if ($session) {
if ($adapter->isValid($session)) {
return $this->sanitizeDataRead($id, $adapter->getDataValue($session));
}
$this->destroy($id);
}
return '';
} | 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 => $this->sessionName
];
$session = $adapter->select($sessionData);
if ($session) {
return (bool) $this->getAdapter()->delete($session);
}
return false;
} | 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);
$sessionData[$dataColumn] = $this->sanitizeDataWrite($id, $data);
$sessionData[$modifiedColumn] = new DateTime();
if ($session) {
return (bool) $adapter->update($session, $sessionData);
}
$sessionData[$lifetimeColumn] = $this->lifetime;
$sessionData[$createdColumn] = new DateTime();
/** @noinspection PhpUndefinedMethodInspection */
return (bool) $adapter->insert($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 $e) {
// close the output buffer opened above if it has not been closed already
if (ob_get_level() > 0) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean() . $out;
} | php | {
"resource": ""
} |
q267176 | Widget.getId | test | public function getId($autoGenerate = true)
{
if ($autoGenerate && $this->_id === null) {
$this->_id = static::$autoIdPrefix . $this->htmlHlp->counter++;
}
return $this->_id;
} | php | {
"resource": ""
} |
q267177 | Widget.beforeRun | test | public function beforeRun()
{
$isValid = true;
$this->emit(self::EVENT_BEFORE_RUN, [$this, &$isValid]);
return $isValid;
} | 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 '%s'", get_called_class());
throw new Reaction\Exceptions\InvalidConfigException($message);
}
} | 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;
}
if ($query->rowCount()) {
$found = new static;
$found->dbData = $query->fetch(DbConn::FETCH_ASSOC);
return $found;
} else {
throw new RecordNotFoundException;
}
} | 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 ' . $table . ' WHERE id= ' . $record);
$query->execute();
} catch (PDOException $e) {
return $e->getMessage();
} finally {
$dbConn = null;
}
$check = $query->rowCount();
if ($check) {
return $check;
} else {
throw new RecordNotFoundException;
}
} | 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 * FROM ' . $table);
$query->execute();
} catch (PDOException $e) {
return $e->getMessage();
} finally {
$dbConn = null;
}
if ($query->rowCount()) {
return $query->fetchAll(DbConn::FETCH_ASSOC);
} else {
throw new EmptyTableException;
}
} | 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 ' . $table . ' (' . Backbone::tokenize(implode(',', array_keys($this->record)), ',') . ')' . ' VALUES ' . '(' . Backbone::tokenize(implode(',', Backbone::generateUnnamedPlaceholders($this->record)), ',') . ')';
$query = $dbConn->prepare($sql);
$query->execute(array_values($this->record));
}
} catch (PDOException $e) {
return $e->getMessage();
} finally {
$dbConn = null;
}
return $query->rowCount();
} | 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);
}
$this->checkMonth($account->getId(), $date);
}
//~ Content
$this->dataCollection->add('title', 'Budgets');
$this->dataCollection->add('date', $date);
$this->dataCollection->add('account', $account);
return $this->getResponse('Budgets');
} | 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);
$this->dataCollection->add('budgets', $budgets);
$this->dataCollection->add('isMain', true);
$this->dataCollection->add('date', $dateStart);
$this->dataCollection->add('total', array('planned' => 0.0, 'transactions' => 0.0, 'diff' => 0.0));
return $this->getResponse('Partial/Budget', true);
} | 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'));
$accountUser = $mapper->findByKeys(array('user_id' => Session::getInstance()->get('id'), 'account_id' => $accountId));
return $accountUser->getAccount();
} | 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()])) {
$accounts[$account->getBankId()] = array();
}
$accounts[$account->getBankId()][] = $account;
}
$this->dataCollection->add('banks', $banks);
$this->dataCollection->add('accounts', $accounts);
$params = $this->route->getParameterCollection();
$get = Get::getInstance();
try {
$dateStart = new \DateTimeImmutable($get->get('date_start', date('Y-m-01')));
} catch(\Exception $exception) {
$dateStart = new \DateTimeImmutable();
}
$this->navForm->setParams(array(
'banks' => $banks,
'accounts' => $accounts,
'currentAccountId' => ($params->hasByName('id') ? (int) $params->getByName('id')->getValue() : 0),
'dateStart' => $dateStart,
'date' => new \DateTimeImmutable(date('Y-m-01')),
));
$this->navForm->setTemplate($this->appTplPath . '/Partial/NavbarForm');
} | php | {
"resource": ""
} |
q267187 | Budget.checkMonth | test | protected function checkMonth($accountId, \DateTimeImmutable $date)
{
$mapper = new BudgetMapper(Database::get('money'));
$budgetMonthMapper = new BudgetMonthMapper(Database::get('money'));
$budgetMonthMapper->check($mapper->findAllByAccountId($accountId), $date);
} | 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();
if (isset($filelist[$file]) && isset($filelist[$file]['md5sum'])) {
$this->md5 = $filelist[$file]['md5sum'];
}
}
} | php | {
"resource": ""
} |
q267189 | Route.execute | test | public function execute(...$constructParameters)
{
$class = $this->class;
$method = $this->method;
$parameters = array_values($this->parameters);
$instance = new $class(...$constructParameters);
return $instance->$method(...$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))
return $this->first_name;
else
return $this->user;
} | php | {
"resource": ""
} |
q267191 | User.save | test | public function save()
{
$reflection = new \ReflectionObject($this);
$properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
foreach($properties as $prop)
$info[$prop->name] = $this->{$prop->name};
return $this->auth->db->update($this->auth->prefix.'users', $info, ['id' => $this->id]);
} | 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
$hash = password_hash($new1, PASSWORD_BCRYPT);
return $this->auth->db->update($this->auth->prefix.'users', ['pass' => $hash] , ['id' => $this->id]);
} | php | {
"resource": ""
} |
q267193 | BindingsBuilder.give | test | public function give( $implementation )
{
$this->container->addContextualBindings( $this->concrete, $this->needs, $implementation );
} | php | {
"resource": ""
} |
q267194 | LoggerFactory.getWriter | test | protected function getWriter(ServiceLocatorInterface $serviceLocator, string $name, array $options): object
{
return $serviceLocator->getService($name, $options);
} | 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
) != 4
) {
throw new InvalidArgumentException('Invalid version format ' . $this->versionString);
}
} else {
if (sscanf($this->versionString, '%d.%d.%d', $this->major, $this->minor, $this->release) != 3) {
throw new InvalidArgumentException('Invalid version format ' . $this->versionString);
}
}
} | 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 {
if ($this->getReleaseVersion() < $version->getReleaseVersion()) {
return -1;
} elseif ($this->getReleaseVersion() > $version->getReleaseVersion()) {
return 1;
} else {
return 0;
}
}
}
} | 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;
$root = CActiveRecord::model($this->treeClass)->findAll($criteria);
$children = $this->owner->findAllByPk(array_keys($root));
return $children;
} | 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) {
return CActiveRecord::model(get_class($this->owner))->findByPk($currentLevel->ancestorId);
} else {
return null;
}
} | 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;
// Fetch any additional ancestry levels
while ($nextParent = $parent->getParent()) {
$parents[$nextParent->{$this->idAttribute}] = $nextParent;
$parent = $nextParent;
}
}
return array_reverse($parents, true);
} | php | {
"resource": ""
} |
Subsets and Splits