_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3 values | text stringlengths 83 13k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q3200 | DataTablesFactory.parseColumns | train | protected static function parseColumns(array $rawColumns, DataTablesWrapperInterface $wrapper) {
$dtColumns = [];
foreach ($rawColumns as $current) {
$dtColumn = static::parseColumn($current, $wrapper);
if (null === $dtColumn) {
continue;
}
$dtColumns[] = $dtColumn;
}
return $dtColumns;
} | php | {
"resource": ""
} |
q3201 | DataTablesFactory.parseOrder | train | protected static function parseOrder(array $rawOrder) {
$dtOrder = new DataTablesOrder();
if (false === static::isValidRawOrder($rawOrder)) {
return $dtOrder;
}
$dtOrder->setColumn(intval($rawOrder[DataTablesOrderInterface::DATATABLES_PARAMETER_COLUMN]));
$dtOrder->setDir($rawOrder[DataTablesOrderInterface::DATATABLES_PARAMETER_DIR]);
return $dtOrder;
} | php | {
"resource": ""
} |
q3202 | DataTablesFactory.parseOrders | train | protected static function parseOrders(array $rawOrders) {
$dtOrders = [];
foreach ($rawOrders as $current) {
$dtOrders[] = static::parseOrder($current);
}
return $dtOrders;
} | php | {
"resource": ""
} |
q3203 | DataTablesFactory.parseSearch | train | protected static function parseSearch(array $rawSearch) {
$dtSearch = new DataTablesSearch();
if (false === static::isValidRawSearch($rawSearch)) {
return $dtSearch;
}
$dtSearch->setRegex(BooleanHelper::parseString($rawSearch[DataTablesSearchInterface::DATATABLES_PARAMETER_REGEX]));
$dtSearch->setValue($rawSearch[DataTablesSearchInterface::DATATABLES_PARAMETER_VALUE]);
return $dtSearch;
} | php | {
"resource": ""
} |
q3204 | ObjectRegistry.register | train | public function register($nickname, $object)
{
if (isset($this->autoInstantiations[$nickname]))
{
throw new DuplicateObjectException($nickname);
}
$this->autoInstantiations[$nickname] = $object;
} | php | {
"resource": ""
} |
q3205 | ObjectRegistry.get | train | public function get($nickname)
{
if (isset($this->autoInstantiations[$nickname]))
{
return $this->autoInstantiations[$nickname];
}
return null;
} | php | {
"resource": ""
} |
q3206 | MailruResourceOwner.getLocation | train | public function getLocation()
{
$country = $this->getCountry();
$city = $this->getCity();
return (empty($country)) ? $city : $country . ', ' . $city;
} | php | {
"resource": ""
} |
q3207 | WhiteHTMLFilter.loadHTML | train | public function loadHTML($html)
{
$html = str_replace(chr(13), '', $html);
$html = '<?xml version="1.0" encoding="utf-8" ?><' . $this->PARENT_TAG_NAME . '>' . $html . '</' . $this->PARENT_TAG_NAME . '>';
if (defined('LIBXML_HTML_NODEFDTD')) {
return $this->dom->loadHTML($html, LIBXML_HTML_NODEFDTD);
} else {
return $this->dom->loadHTML($html);
}
} | php | {
"resource": ""
} |
q3208 | WhiteHTMLFilter.outputHtml | train | public function outputHtml()
{
$result = '';
if (!is_null($this->dom)) {
//SaveXML : <br/><img/>
//SaveHTML: <br><img>
$result = trim($this->dom->saveXML($this->getRealElement()));
$result = str_replace($this->TEMP_CONTENT, '', $result);
$parentTagNameLength = strlen($this->PARENT_TAG_NAME);
$result = substr($result, $parentTagNameLength + 2, -($parentTagNameLength + 3));
}
return $result;
} | php | {
"resource": ""
} |
q3209 | WhiteHTMLFilter.cleanNodes | train | private function cleanNodes(DOMElement $elem, $isFirstNode = false)
{
$nodeName = strtolower($elem->nodeName);
$textContent = $elem->textContent;
if ($isFirstNode || array_key_exists($nodeName, $this->config->WhiteListTag)) {
if ($elem->hasAttributes()) {
$this->cleanAttributes($elem);
}
/*
* Iterate over the element's children. The reason we go backwards is because
* going forwards will cause indexes to change when elements get removed
*/
if ($elem->hasChildNodes()) {
$children = $elem->childNodes;
$index = $children->length;
while (--$index >= 0) {
$cleanNode = $children->item($index);// DOMElement or DOMText
if ($cleanNode instanceof DOMElement) {
$this->cleanNodes($cleanNode);
}
}
} else {
if (!in_array($nodeName, $this->emptyElementList) && !$this->isValidText($textContent)) {
$elem->nodeValue = $this->TEMP_CONTENT;
}
}
} else {
if ($this->config->KeepText === true && $this->isValidText($textContent)) {
$result = $elem->parentNode->replaceChild($this->dom->createTextNode($textContent), $elem);
} else {
$result = $elem->parentNode->removeChild($elem);
}
if ($result) {
$this->removedTags[] = $nodeName;
} else {
throw new Exception('Failed to remove node from DOM');
}
}
} | php | {
"resource": ""
} |
q3210 | WhiteHTMLFilter.cleanAttributes | train | private function cleanAttributes(DOMElement $elem)
{
$tagName = strtolower($elem->nodeName);
$attributes = $elem->attributes;
$attributesWhiteList = $this->config->WhiteListHtmlGlobalAttributes;
$attributesFilterMap = array();
$allowDataAttribute = in_array("data-*", $attributesWhiteList);
$whiteListAttr = $this->config->getWhiteListAttr($tagName);
foreach ($whiteListAttr as $key => $val) {
if (is_string($val)) {
$attributesWhiteList[] = $val;
}
if ($val instanceof Closure) {
$attributesWhiteList[] = $key;
$attributesFilterMap[$key] = $val;
}
}
$index = $attributes->length;
while (--$index >= 0) {
/*
foreach会有一个严重的的问题:
href="JavaScript:alert("customAttr="xxx"");"
这样嵌套的不合法的属性,会被解析出两个属性:
1. href="JavaScript:alert("
2. customAttr="xxx"
但是foreach只能拿到一个。
foreach ($elem->attributes->item() as $attrName => $domAttr) {
*/
/* @var $domAttr DOMAttr */
$domAttr = $attributes->item($index);
$attrName = strtolower($domAttr->name);
$attrValue = $domAttr->value;
// 如果不在白名单attr中,而且允许data-*,且不是data-*,则删除
if (!in_array($attrName, $attributesWhiteList) && $allowDataAttribute && (stripos($attrName, "data-") !== 0)) {
$elem->removeAttribute($attrName);
} else {
if (isset($attributesFilterMap[$attrName])) {
$filteredAttrValue = $attributesFilterMap[$attrName]($attrValue);
if ($filteredAttrValue === false ) {
$elem->removeAttribute($attrName);
} else {
// https://stackoverflow.com/questions/25475936/updating-domattr-value-with-url-results-in-parameters-being-lost-unless-htmlenti
// Fix ampersands issue: https://github.com/lincanbin/White-HTML-Filter/issues/1
if ($filteredAttrValue !== $attrValue) {
$elem->setAttribute($attrName, $filteredAttrValue);
}
}
} else {
$this->cleanAttrValue($domAttr);
}
}
}
} | php | {
"resource": ""
} |
q3211 | WhiteHTMLFilter.cleanAttrValue | train | private function cleanAttrValue(DOMAttr $domAttr)
{
$attrName = strtolower($domAttr->name);
if ($attrName === 'style' && !empty($this->config->WhiteListStyle)) {
$styles = explode(';', $domAttr->value);
foreach ($styles as $key => &$subStyle) {
$subStyle = array_map("trim", explode(':', strtolower($subStyle), 2));
if (empty($subStyle[0]) || !in_array($subStyle[0], $this->config->WhiteListStyle)) {
unset($styles[$key]);
}
}
$implodeFunc = function ($styleSheet) {
return implode(':', $styleSheet);
};
$domAttr->ownerElement->setAttribute($attrName, implode(';', array_map($implodeFunc, $styles)) . ';');
}
if ($attrName === 'class' && !empty($this->config->WhiteListCssClass)) {
$domAttr->ownerElement->setAttribute($attrName, implode(' ', array_intersect(preg_split('/\s+/', $domAttr->value), $this->config->WhiteListCssClass)));
}
if ($attrName === 'src' || $attrName === 'href') {
if (strtolower(parse_url($domAttr->value, PHP_URL_SCHEME)) === 'javascript') {
$domAttr->ownerElement->removeAttribute($attrName);
} else {
$domAttr->ownerElement->setAttribute($attrName, filter_var($domAttr->value, FILTER_SANITIZE_URL));
}
}
} | php | {
"resource": ""
} |
q3212 | WhiteHTMLFilter.clean | train | public function clean()
{
$this->removedTags = array();
$elem = $this->getRealElement();
if (is_null($elem)) {
return array();
}
$this->cleanNodes($elem, true);
return $this->removedTags;
} | php | {
"resource": ""
} |
q3213 | NGSIAPIv1.getEntities | train | public function getEntities($type = false, $offset = 0, $limit = 1000, $details = "on") {
if ($type) {
$url = $this->url . "contextTypes/" . $type;
} else {
$url = $this->url . "contextEntities/";
}
$ret = $this->restRequest($url . "?offset=$offset&limit=$limit&details=$details", 'GET')->getResponseBody();
$Context = (new Context\Context($ret))->get();
$Entities = [];
if($Context instanceof \stdClass && isset($Context->errorCode)){
switch ((int) $Context->errorCode->code) {
case 404:
case 500:
throw new Exception\GeneralException($Context->errorCode->reasonPhrase,(int)$Context->errorCode->code, null, $ret);
default:
case 200:
break;
}
}else{
throw new Exception\GeneralException("Malformed Orion Response",500, null, $ret);
}
if(isset($Context->contextResponses) && count($Context->contextResponses) > 0){
foreach ($Context->contextResponses as $entity) {
$t = $entity->contextElement->type;
$id = $entity->contextElement->id;
if(!array_key_exists($t, $Entities)){
$Entities[$t] = [];
}
$Entities[$t][$id] = $entity->contextElement->attributes;
}
}
return new Context\Context($Entities);
} | php | {
"resource": ""
} |
q3214 | Util.strEscape | train | public static function strEscape( $str, $escape = 'plain' ) {
switch ( $escape ) {
case 'html' :
case 'htmlspecialchars' :
$str = htmlspecialchars( $str );
break;
case 'htmlentities':
$str = htmlentities( $str, ENT_QUOTES, 'UTF-8' );
break;
// 'plain' or anything else: Do nothing
}
return $str;
} | php | {
"resource": ""
} |
q3215 | Util.tag | train | public static function tag( $str, $wrapTag = 0, $attributes = [] ) {
$selfclose = [ 'link', 'input', 'br', 'img' ];
if ( !is_string( $str ) ) {
return '';
}
if ( !is_string( $wrapTag ) ) {
return $str;
}
$wrapTag = trim( strtolower( $wrapTag ) );
$attrString = '';
if ( is_array( $attributes ) ) {
foreach ( $attributes as $attrKey => $attrVal ) {
$attrKey = htmlspecialchars( trim( strtolower( $attrKey ) ), ENT_QUOTES );
$attrVal = htmlspecialchars( trim( $attrVal ), ENT_QUOTES );
$attrString .= " $attrKey=\"$attrVal\"";
}
}
$return = "<$wrapTag$attrString";
if ( in_array( $wrapTag, $selfclose ) ) {
$return .= '/>';
} else {
$return .= ">" . htmlspecialchars( $str ) . "</$wrapTag>";
}
return $return;
} | php | {
"resource": ""
} |
q3216 | Util.getAcceptableLanguages | train | public static function getAcceptableLanguages( $rawList = false ) {
// Implementation based on MediaWiki 1.21's WebRequest::getAcceptLang
// Which is based on http://www.thefutureoftheweb.com/blog/use-accept-language-header
// @codeCoverageIgnoreStart
if ( $rawList === false ) {
$rawList = isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ?
$_SERVER['HTTP_ACCEPT_LANGUAGE'] :
'';
}
// @codeCoverageIgnoreEnd
// Return the language codes in lower case
$rawList = strtolower( $rawList );
// The list of elements is separated by comma and optional LWS
// Extract the language-range and, if present, the q-value
$lang_parse = null;
preg_match_all(
'/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
$rawList,
$lang_parse
);
if ( !count( $lang_parse[1] ) ) {
return [];
}
$langcodes = $lang_parse[1];
$qvalues = $lang_parse[4];
$indices = range( 0, count( $lang_parse[1] ) - 1 );
// Set default q factor to 1
foreach ( $indices as $index ) {
if ( $qvalues[$index] === '' ) {
$qvalues[$index] = 1;
} elseif ( $qvalues[$index] == 0 ) {
unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
} else {
$qvalues[$index] = floatval( $qvalues[$index] );
}
}
// Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
// Create a list like "en" => 0.8
$langs = array_combine( $langcodes, $qvalues );
return $langs;
} | php | {
"resource": ""
} |
q3217 | Util.parseExternalLinks | train | public static function parseExternalLinks( $text ) {
static $urlProtocols = false;
static $counter = 0;
// @codeCoverageIgnoreStart
if ( !$urlProtocols ) {
if ( function_exists( 'wfUrlProtocols' ) ) {
// Allow custom protocols
$urlProtocols = wfUrlProtocols();
} else {
$urlProtocols = 'https?:\/\/|ftp:\/\/';
}
}
// @codeCoverageIgnoreEnd
$extLinkBracketedRegex = '/(?:(<[^>]*)|' .
'\[(((?i)' . $urlProtocols . ')' .
self::EXT_LINK_URL_CLASS .
'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]|' .
'(((?i)' . $urlProtocols . ')' .
self::EXT_LINK_URL_CLASS .
'+))/Su';
return preg_replace_callback(
$extLinkBracketedRegex,
function ( array $bits ) use ( &$counter ) {
// @codeCoverageIgnoreStart
if ( $bits[1] != '' ) {
return $bits[1];
}
// @codeCoverageIgnoreEnd
if ( isset( $bits[4] ) && $bits[4] != '' ) {
return '<a href="' . $bits[2] . '">' . $bits[4] . '</a>';
} elseif ( isset( $bits[5] ) ) {
return '<a href="' . $bits[5] . '">' . $bits[5] . '</a>';
} else {
return '<a href="' . $bits[2] . '">[' . ++$counter . ']</a>';
}
},
$text
);
} | php | {
"resource": ""
} |
q3218 | Util.parseWikiLinks | train | public static function parseWikiLinks( $text, $articlePath ) {
self::$articlePath = $articlePath;
return preg_replace_callback(
'/\[\[:?([^]|]+)(?:\|([^]]*))?\]\]/',
function ( array $bits ) {
if ( !isset( $bits[2] ) || $bits[2] == '' ) {
$bits[2] = strtr( $bits[1], '_', ' ' );
}
$article = html_entity_decode( $bits[1], ENT_QUOTES, 'UTF-8' );
return '<a href="' . htmlspecialchars(
self::prettyEncodedWikiUrl( self::$articlePath, $article ), ENT_COMPAT, 'UTF-8'
) . '">' . $bits[2] . "</a>";
},
$text
);
} | php | {
"resource": ""
} |
q3219 | Util.prettyEncodedWikiUrl | train | public static function prettyEncodedWikiUrl( $articlePath, $article ) {
$s = strtr( $article, ' ', '_' );
$s = urlencode( $s );
$s = str_ireplace(
[ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%3A' ],
[ ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ],
$s
);
$s = str_replace( '$1', $s, $articlePath );
return $s;
} | php | {
"resource": ""
} |
q3220 | FileUploader.upload | train | public function upload(ApiClientContract $api, $path, $body, array $params = [], $verifyChecksum = true)
{
$response = $api->request('PUT', $path, [
'headers' => $this->convertUploadParamsToHeaders($body, $params, $verifyChecksum),
'body' => $body,
'query' => $this->extractQueryParameters($params),
]);
if ($response->getStatusCode() !== 201) {
throw new UploadFailedException('Unable to upload file.', $response->getStatusCode());
}
return $response->getHeaderLine('ETag');
} | php | {
"resource": ""
} |
q3221 | FileUploader.convertUploadParamsToHeaders | train | protected function convertUploadParamsToHeaders($body = null, array $params = [], $verifyChecksum = true)
{
$headers = [];
if ($verifyChecksum) {
$headers['ETag'] = md5($body);
}
$availableParams = [
'contentType' => 'Content-Type',
'contentDisposition' => 'Content-Disposition',
'deleteAfter' => 'X-Delete-After',
'deleteAt' => 'X-Delete-At',
];
foreach ($availableParams as $key => $header) {
if (isset($params[$key])) {
$headers[$header] = $params[$key];
}
}
return $headers;
} | php | {
"resource": ""
} |
q3222 | FileUploader.extractQueryParameters | train | protected function extractQueryParameters(array $params)
{
$availableParams = ['extract-archive'];
$query = [];
foreach ($params as $key => $value) {
if (in_array($key, $availableParams)) {
$query[$key] = $value;
}
}
return $query;
} | php | {
"resource": ""
} |
q3223 | TokenStorage.getToken | train | public function getToken()
{
$token = $this->cache->get($this->tokenName);
if ($token === false) {
$token = Algorithms::generateRandomToken(20);
$this->storeToken($token);
}
return $token;
} | php | {
"resource": ""
} |
q3224 | DataTablesOrder.setDir | train | public function setDir($dir) {
if (false === in_array($dir, DataTablesEnumerator::enumDirs())) {
$dir = self::DATATABLES_DIR_ASC;
}
$this->dir = strtoupper($dir);
return $this;
} | php | {
"resource": ""
} |
q3225 | ApiClient.getHttpClient | train | public function getHttpClient()
{
if (!is_null($this->httpClient)) {
return $this->httpClient;
}
return $this->httpClient = new Client([
'base_uri' => $this->storageUrl(),
'headers' => [
'X-Auth-Token' => $this->token(),
],
]);
} | php | {
"resource": ""
} |
q3226 | ApiClient.authenticate | train | public function authenticate()
{
if (!is_null($this->token)) {
return;
}
$response = $this->authenticationResponse();
if (!$response->hasHeader('X-Auth-Token')) {
throw new AuthenticationFailedException('Given credentials are wrong.', 403);
}
if (!$response->hasHeader('X-Storage-Url')) {
throw new RuntimeException('Storage URL is missing.', 500);
}
$this->token = $response->getHeaderLine('X-Auth-Token');
$this->storageUrl = $response->getHeaderLine('X-Storage-Url');
} | php | {
"resource": ""
} |
q3227 | ApiClient.authenticationResponse | train | public function authenticationResponse()
{
$client = new Client();
try {
$response = $client->request('GET', static::AUTH_URL, [
'headers' => [
'X-Auth-User' => $this->username,
'X-Auth-Key' => $this->password,
],
]);
} catch (RequestException $e) {
throw new AuthenticationFailedException('Given credentials are wrong.', 403);
}
return $response;
} | php | {
"resource": ""
} |
q3228 | LanguageEo.iconv | train | function iconv( $in, $out, $string ) {
if ( strcasecmp( $in, 'x' ) == 0 && strcasecmp( $out, 'utf-8' ) == 0 ) {
return preg_replace_callback (
'/([cghjsu]x?)((?:xx)*)(?!x)/i',
array( $this, 'strrtxuCallback' ), $string );
} elseif ( strcasecmp( $in, 'UTF-8' ) == 0 && strcasecmp( $out, 'x' ) == 0 ) {
# Double Xs only if they follow cxapelutaj literoj.
return preg_replace_callback(
'/((?:[cghjsu]|\xc4[\x88\x89\x9c\x9d\xa4\xa5\xb4\xb5]|\xc5[\x9c\x9d\xac\xad])x*)/i',
array( $this, 'strrtuxCallback' ), $string );
}
return parent::iconv( $in, $out, $string );
} | php | {
"resource": ""
} |
q3229 | GiroCheckout_SDK_TransactionType_helper.getTransactionTypeByName | train | public static function getTransactionTypeByName($transType) {
switch ($transType) {
//credit card apis
case 'creditCardTransaction':
return new GiroCheckout_SDK_CreditCardTransaction();
case 'creditCardCapture':
return new GiroCheckout_SDK_CreditCardCapture();
case 'creditCardRefund':
return new GiroCheckout_SDK_CreditCardRefund();
case 'creditCardGetPKN':
return new GiroCheckout_SDK_CreditCardGetPKN();
case 'creditCardRecurringTransaction':
return new GiroCheckout_SDK_CreditCardRecurringTransaction();
case 'creditCardVoid':
return new GiroCheckout_SDK_CreditCardVoid();
//direct debit apis
case 'directDebitTransaction':
return new GiroCheckout_SDK_DirectDebitTransaction();
case 'directDebitGetPKN':
return new GiroCheckout_SDK_DirectDebitGetPKN();
case 'directDebitTransactionWithPaymentPage':
return new GiroCheckout_SDK_DirectDebitTransactionWithPaymentPage();
case 'directDebitCapture':
return new GiroCheckout_SDK_DirectDebitCapture();
case 'directDebitRefund':
return new GiroCheckout_SDK_DirectDebitRefund();
case 'directDebitVoid':
return new GiroCheckout_SDK_DirectDebitVoid();
//giropay apis
case 'giropayBankstatus':
return new GiroCheckout_SDK_GiropayBankstatus();
case 'giropayIDCheck':
return new GiroCheckout_SDK_GiropayIDCheck();
case 'giropayTransaction':
return new GiroCheckout_SDK_GiropayTransaction();
case 'giropayIssuerList':
return new GiroCheckout_SDK_GiropayIssuerList();
//iDEAL apis
case 'idealIssuerList':
return new GiroCheckout_SDK_IdealIssuerList();
case 'idealPayment':
return new GiroCheckout_SDK_IdealPayment();
case 'idealRefund':
return new GiroCheckout_SDK_IdealPaymentRefund();
//PayPal apis
case 'paypalTransaction':
return new GiroCheckout_SDK_PaypalTransaction();
//eps apis
case 'epsBankstatus':
return new GiroCheckout_SDK_EpsBankstatus();
case 'epsTransaction':
return new GiroCheckout_SDK_EpsTransaction();
case 'epsIssuerList':
return new GiroCheckout_SDK_EpsIssuerList();
//tools apis
case 'getTransactionTool':
return new GiroCheckout_SDK_Tools_GetTransaction();
//GiroCode apis
case 'giroCodeCreatePayment':
return new GiroCheckout_SDK_GiroCodeCreatePayment();
case 'giroCodeCreateEpc':
return new GiroCheckout_SDK_GiroCodeCreateEpc();
case 'giroCodeGetEpc':
return new GiroCheckout_SDK_GiroCodeGetEpc();
//Paydirekt apis
case 'paydirektTransaction':
return new GiroCheckout_SDK_PaydirektTransaction();
case 'paydirektCapture':
return new GiroCheckout_SDK_PaydirektCapture();
case 'paydirektRefund':
return new GiroCheckout_SDK_PaydirektRefund();
case 'paydirektVoid':
return new GiroCheckout_SDK_PaydirektVoid();
//Sofort apis
case 'sofortuwTransaction':
return new GiroCheckout_SDK_SofortUwTransaction();
//BlueCode apis
case 'blueCodeTransaction':
return new GiroCheckout_SDK_BlueCodeTransaction();
//Payment page apis
case 'paypageTransaction':
return new GiroCheckout_SDK_PaypageTransaction();
case 'paypageProjects':
return new GiroCheckout_SDK_PaypageProjects();
//Maestro apis
case 'maestroTransaction':
return new GiroCheckout_SDK_MaestroTransaction();
case 'maestroCapture':
return new GiroCheckout_SDK_MaestroCapture();
case 'maestroRefund':
return new GiroCheckout_SDK_MaestroRefund();
}
return null;
} | php | {
"resource": ""
} |
q3230 | ControllerInspector.getRoutable | train | public function getRoutable($controller, $prefix)
{
$routable = [];
$reflection = new ReflectionClass($controller);
$methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
// To get the routable methods, we will simply spin through all methods on the
// controller instance checking to see if it belongs to the given class and
// is a publicly routable method. If so, we will add it to this listings.
foreach ($methods as $method) {
if ($this->isRoutable($method)) {
$data = $this->getMethodData($method, $prefix);
$routable[$method->name][] = $data;
// If the routable method is an index method, we will create a special index
// route which is simply the prefix and the verb and does not contain any
// the wildcard place-holders that each "typical" routes would contain.
if ($data['plain'] == $prefix.'/index') {
$routable[$method->name][] = $this->getIndexData($data, $prefix);
}
}
}
return $routable;
} | php | {
"resource": ""
} |
q3231 | ControllerInspector.getMethodData | train | public function getMethodData(ReflectionMethod $method, $prefix)
{
$verb = $this->getVerb($name = $method->name);
$uri = $this->addUriWildcards($plain = $this->getPlainUri($name, $prefix));
return compact('verb', 'plain', 'uri');
} | php | {
"resource": ""
} |
q3232 | Tx_Oelib_Model_BackEndUser.getLanguage | train | public function getLanguage()
{
$configuration = $this->getConfiguration();
$result = !empty($configuration['lang']) ? $configuration['lang'] : $this->getDefaultLanguage();
return ($result !== '') ? $result : 'default';
} | php | {
"resource": ""
} |
q3233 | Tx_Oelib_Model_BackEndUser.getAllGroups | train | public function getAllGroups()
{
$result = new \Tx_Oelib_List();
$groupsToProcess = $this->getGroups();
do {
$groupsForNextStep = new \Tx_Oelib_List();
$result->append($groupsToProcess);
/** @var \Tx_Oelib_Model_BackEndUserGroup $group */
foreach ($groupsToProcess as $group) {
$subgroups = $group->getSubgroups();
/** @var \Tx_Oelib_Model_BackEndUserGroup $subgroup */
foreach ($subgroups as $subgroup) {
if (!$result->hasUid($subgroup->getUid())) {
$groupsForNextStep->add($subgroup);
}
}
}
$groupsToProcess = $groupsForNextStep;
} while (!$groupsToProcess->isEmpty());
return $result;
} | php | {
"resource": ""
} |
q3234 | Tx_Oelib_Model_BackEndUser.getConfiguration | train | private function getConfiguration()
{
if (empty($this->configuration)) {
$this->configuration = unserialize($this->getAsString('uc'));
}
return $this->configuration;
} | php | {
"resource": ""
} |
q3235 | Response.getErrorData | train | public function getErrorData($key = null)
{
if ($this->isSuccessful()) {
return null;
}
// get error data (array in data)
$data = isset($this->getData('data')[0]) ? $this->getData('data')[0] : null;
if ($key) {
return isset($data[$key]) ? $data[$key] : null;
}
return $data;
} | php | {
"resource": ""
} |
q3236 | Response.getMessage | train | public function getMessage()
{
if ($this->getErrorMessage()) {
return $this->getErrorMessage() . ' (' . $this->getErrorFieldName() . ')';
}
if ($this->isSuccessful()) {
return ($this->getStatus()) ? ucfirst($this->getStatus()) : 'Successful';
}
// default to unsuccessful message
return 'The transaction was unsuccessful.';
} | php | {
"resource": ""
} |
q3237 | Response.getHttpResponseCodeText | train | public function getHttpResponseCodeText()
{
$code = $this->getHttpResponseCode();
$statusTexts = \Symfony\Component\HttpFoundation\Response::$statusTexts;
return (isset($statusTexts[$code])) ? $statusTexts[$code] : null;
} | php | {
"resource": ""
} |
q3238 | AbstractController.buildDataTablesResponse | train | protected function buildDataTablesResponse(Request $request, $name, ActionResponse $output) {
if (true === $request->isXmlHttpRequest()) {
return new JsonResponse($output);
}
// Notify the user.
switch ($output->getStatus()) {
case 200:
$this->notifySuccess($output->getNotify());
break;
case 404:
$this->notifyDanger($output->getNotify());
break;
case 500:
$this->notifyWarning($output->getNotify());
break;
}
return $this->redirectToRoute("jquery_datatables_index", ["name" => $name]);
} | php | {
"resource": ""
} |
q3239 | AbstractController.exportDataTablesCallback | train | protected function exportDataTablesCallback(DataTablesProviderInterface $dtProvider, DataTablesRepositoryInterface $repository, DataTablesCSVExporterInterface $dtExporter, $windows) {
$em = $this->getDoctrine()->getManager();
$stream = fopen("php://output", "w+");
// Export the columns.
fputcsv($stream, DataTablesExportHelper::convert($dtExporter->exportColumns(), $windows), ";");
// Paginates.
$total = $repository->dataTablesCountExported($dtProvider);
$pages = PaginateHelper::getPagesCount($total, DataTablesRepositoryInterface::REPOSITORY_LIMIT);
// Handle each page.
for ($i = 0; $i < $pages; ++$i) {
// Get the offset and limit.
list($offset, $limit) = PaginateHelper::getPageOffsetAndLimit($i, DataTablesRepositoryInterface::REPOSITORY_LIMIT, $total);
// Get the export query with offset and limit.
$result = $repository->dataTablesExportAll($dtProvider)
->setFirstResult($offset)
->setMaxResults($limit)
->getQuery()
->iterate();
while (false !== ($row = $result->next())) {
$this->dispatchDataTablesEvent(DataTablesEvents::DATATABLES_PRE_EXPORT, [$row[0]]);
fputcsv($stream, DataTablesExportHelper::convert($dtExporter->exportRow($row[0]), $windows), ";");
// Detach the entity to avoid memory consumption.
$em->detach($row[0]);
$this->dispatchDataTablesEvent(DataTablesEvents::DATATABLES_POST_EXPORT, [$row[0]]);
}
}
// Close the file.
fclose($stream);
} | php | {
"resource": ""
} |
q3240 | AbstractController.getDataTablesColumn | train | protected function getDataTablesColumn(DataTablesProviderInterface $dtProvider, $data) {
$this->getLogger()->debug(sprintf("DataTables controller search for a column with name \"%s\"", $data));
$dtColumn = $this->getDataTablesWrapper($dtProvider)->getColumn($data);
if (null === $dtColumn) {
throw new BadDataTablesColumnException($data);
}
$this->getLogger()->debug(sprintf("DataTables controller found a column with name \"%s\"", $data));
return $dtColumn;
} | php | {
"resource": ""
} |
q3241 | AbstractController.getDataTablesEntityById | train | protected function getDataTablesEntityById(DataTablesProviderInterface $dtProvider, $id) {
$repository = $this->getDataTablesRepository($dtProvider);
$this->getLogger()->debug(sprintf("DataTables controller search for an entity [%s]", $id));
$entity = $repository->find($id);
if (null === $entity) {
throw EntityNotFoundException::fromClassNameAndIdentifier($dtProvider->getEntity(), [$id]);
}
$this->getLogger()->debug(sprintf("DataTables controller found an entity [%s]", $id));
return $entity;
} | php | {
"resource": ""
} |
q3242 | AbstractController.getDataTablesURL | train | protected function getDataTablesURL(DataTablesProviderInterface $dtProvider) {
$this->getLogger()->debug(sprintf("DataTables controller search for an URL with name \"%s\"", $dtProvider->getName()));
if (false === ($dtProvider instanceof DataTablesRouterInterface)) {
return $this->getRouter()->generate("jquery_datatables_index", ["name" => $dtProvider->getName()]);
}
$this->getLogger()->debug(sprintf("DataTables controller found for an URL with name \"%s\"", $dtProvider->getName()));
return $dtProvider->getUrl();
} | php | {
"resource": ""
} |
q3243 | AbstractController.getDataTablesWrapper | train | protected function getDataTablesWrapper(DataTablesProviderInterface $dtProvider) {
$url = $this->getDataTablesURL($dtProvider);
$dtWrapper = DataTablesFactory::newWrapper($url, $dtProvider, $this->getKernelEventListener()->getUser());
foreach ($dtProvider->getColumns() as $dtColumn) {
$this->getLogger()->debug(sprintf("DataTables provider \"%s\" add a column \"%s\"", $dtProvider->getName(), $dtColumn->getData()));
$dtWrapper->addColumn($dtColumn);
}
if (null !== $dtProvider->getOptions()) {
$dtWrapper->setOptions($dtProvider->getOptions());
}
return $dtWrapper;
} | php | {
"resource": ""
} |
q3244 | AbstractController.prepareActionResponse | train | protected function prepareActionResponse($status, $notificationId) {
$response = new ActionResponse();
$response->setStatus($status);
$response->setNotify($this->getDataTablesNotification($notificationId));
return $response;
} | php | {
"resource": ""
} |
q3245 | GalleryHubController.PaginatedGalleries | train | public function PaginatedGalleries()
{
$children = $this->AllChildren();
$limit = $this->ThumbnailsPerPage;
$list = ArrayList::create();
foreach ($children as $child) {
$image = $child->SortedImages()->first();
$child_data = $child->toMap();
$child_data["Link"] = $child->Link();
if ($image) {
$child_data["GalleryThumbnail"] = $this->ScaledImage($image, true);
} else {
$child_data["GalleryThumbnail"] = null;
}
$list->add(ArrayData::create($child_data));
}
$pages = PaginatedList::create($list, $this->getRequest());
$pages->setPageLength($limit);
return $pages;
} | php | {
"resource": ""
} |
q3246 | FluentFilesLoader.setParam | train | protected function setParam($key, $value, $trimLeadingSlashes = true)
{
$this->params[$key] = $trimLeadingSlashes ? ltrim($value, '/') : $value;
return $this;
} | php | {
"resource": ""
} |
q3247 | FluentFilesLoader.limit | train | public function limit($limit, $markerFile = '')
{
return $this->setParam('limit', intval($limit), false)
->setParam('marker', $markerFile, false);
} | php | {
"resource": ""
} |
q3248 | FluentFilesLoader.find | train | public function find($path)
{
$file = $this->findFileAt($path);
if (is_null($file)) {
throw new FileNotFoundException('File "'.$path.'" was not found.');
}
return new File($this->api, $this->containerName(), $file);
} | php | {
"resource": ""
} |
q3249 | FluentFilesLoader.findFileAt | train | protected function findFileAt($path)
{
try {
$files = $this->fromDirectory('')
->withPrefix($path)
->withDelimiter('')
->limit(1)
->get();
} catch (ApiRequestFailedException $e) {
return;
}
return $files->get(0);
} | php | {
"resource": ""
} |
q3250 | FluentFilesLoader.get | train | public function get()
{
$response = $this->api->request('GET', $this->containerUrl, [
'query' => $this->buildParams(),
]);
if ($response->getStatusCode() !== 200) {
throw new ApiRequestFailedException('Unable to list container files.', $response->getStatusCode());
}
$files = json_decode($response->getBody(), true);
if ($this->asFileObjects === true) {
$this->asFileObjects = false;
return $this->getFilesCollectionFromArrays($files);
}
// Add 'filename' attribute to each file, so users
// can pass it to new loader instance as marker,
// if they want to iterate inside a directory.
$files = array_map(function ($file) {
$path = explode('/', $file['name']);
$file['filename'] = array_pop($path);
return $file;
}, $files);
return new Collection($files);
} | php | {
"resource": ""
} |
q3251 | Tx_Oelib_AbstractMailer.formatEmailBody | train | protected function formatEmailBody($rawEmailBody)
{
if (!$this->enableFormatting) {
return $rawEmailBody;
}
$body = str_replace([CRLF, CR], LF, $rawEmailBody);
$body = preg_replace('/\\n{2,}/', LF . LF, $body);
return trim($body);
} | php | {
"resource": ""
} |
q3252 | Tx_Oelib_SalutationSwitcher.getAvailableLanguages | train | private function getAvailableLanguages()
{
if ($this->availableLanguages === null) {
$this->availableLanguages = [];
if (!empty($this->LLkey)) {
$this->availableLanguages[] = $this->LLkey;
}
// The key for English is "default", not "en".
$this->availableLanguages = str_replace(
'en',
'default',
$this->availableLanguages
);
// Remove duplicates in case the default language is the same as the fall-back language.
$this->availableLanguages = array_unique($this->availableLanguages);
// Now check that we only keep languages for which we have
// translations.
foreach ($this->availableLanguages as $index => $code) {
if (!isset($this->LOCAL_LANG[$code])) {
unset($this->availableLanguages[$index]);
}
}
}
return $this->availableLanguages;
} | php | {
"resource": ""
} |
q3253 | Tx_Oelib_SalutationSwitcher.getSuffixesToTry | train | private function getSuffixesToTry()
{
if ($this->suffixesToTry === null) {
$this->suffixesToTry = [];
if (isset($this->conf['salutation'])) {
if ($this->conf['salutation'] === 'informal') {
$this->suffixesToTry[] = '_informal';
}
$this->suffixesToTry[] = '_formal';
}
$this->suffixesToTry[] = '';
}
return $this->suffixesToTry;
} | php | {
"resource": ""
} |
q3254 | Tx_Oelib_Visibility_Tree.buildTreeFromArray | train | private function buildTreeFromArray(
array $treeStructure,
\Tx_Oelib_Visibility_Node $parentNode
) {
foreach ($treeStructure as $nodeKey => $nodeContents) {
/** @var \Tx_Oelib_Visibility_Node $childNode */
$childNode = GeneralUtility::makeInstance(\Tx_Oelib_Visibility_Node::class);
$parentNode->addChild($childNode);
if (is_array($nodeContents)) {
$this->buildTreeFromArray($nodeContents, $childNode);
} elseif ($nodeContents === true) {
$childNode->markAsVisible();
}
$this->nodes[$nodeKey] = $childNode;
}
} | php | {
"resource": ""
} |
q3255 | Tx_Oelib_Visibility_Tree.getKeysOfHiddenSubparts | train | public function getKeysOfHiddenSubparts()
{
$keysToHide = [];
foreach ($this->nodes as $key => $node) {
if (!$node->isVisible()) {
$keysToHide[] = $key;
}
}
return $keysToHide;
} | php | {
"resource": ""
} |
q3256 | Tx_Oelib_Visibility_Tree.makeNodesVisible | train | public function makeNodesVisible(array $nodeKeys)
{
foreach ($nodeKeys as $nodeKey) {
if (isset($this->nodes[$nodeKey])) {
$this->nodes[$nodeKey]->markAsVisible();
}
}
} | php | {
"resource": ""
} |
q3257 | GiroCheckout_SDK_Curl_helper.submit | train | public static function submit($url, $params) {
$Config = GiroCheckout_SDK_Config::getInstance();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
// For Windows environments
if( defined('__GIROSOLUTION_SDK_CERT__') ) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_CAINFO, str_replace('\\', '/', __GIROSOLUTION_SDK_CERT__));
}
// For Windows environments
if( defined('__GIROSOLUTION_SDK_SSL_VERIFY_OFF__') && __GIROSOLUTION_SDK_SSL_VERIFY_OFF__ ) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
}
if ($Config->getConfig('CURLOPT_SSL_VERIFYPEER')) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $Config->getConfig('CURLOPT_SSL_VERIFYPEER'));
}
if ($Config->getConfig('CURLOPT_CAINFO')) {
curl_setopt($ch, CURLOPT_CAINFO, $Config->getConfig('CURLOPT_CAINFO'));
}
if ($Config->getConfig('CURLOPT_SSL_VERIFYHOST')) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $Config->getConfig('CURLOPT_SSL_VERIFYHOST'));
}
if ($Config->getConfig('CURLOPT_CONNECTTIMEOUT')) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $Config->getConfig('CURLOPT_CONNECTTIMEOUT'));
}
// Begin Proxy
if( $Config->getConfig('CURLOPT_PROXY') && $Config->getConfig('CURLOPT_PROXYPORT') ) {
curl_setopt($ch, CURLOPT_PROXY, $Config->getConfig('CURLOPT_PROXY'));
curl_setopt($ch, CURLOPT_PROXYPORT, $Config->getConfig('CURLOPT_PROXYPORT'));
if($Config->getConfig('CURLOPT_PROXYUSERPWD')) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $Config->getConfig('CURLOPT_PROXYUSERPWD'));
}
}
// End Proxy
if ($Config->getConfig('DEBUG_MODE')) {
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
$result = curl_exec($ch);
if($Config->getConfig('DEBUG_MODE')) { GiroCheckout_SDK_Debug_helper::getInstance()->logRequest(curl_getinfo($ch),$params); }
if($Config->getConfig('DEBUG_MODE')) { GiroCheckout_SDK_Debug_helper::getInstance()->logReply($result, curl_error($ch)); }
if($result === false) {
throw new Exception('cURL: submit failed.');
}
curl_close($ch);
return self::getHeaderAndBody($result);
} | php | {
"resource": ""
} |
q3258 | GiroCheckout_SDK_Curl_helper.getJSONResponseToArray | train | public static function getJSONResponseToArray($string) {
$json = json_decode($string,true);
if($json !== NULL) {
return $json;
}
else {
throw new \Exception('Response is not a valid json string.');
}
} | php | {
"resource": ""
} |
q3259 | GiroCheckout_SDK_Curl_helper.getHeaderAndBody | train | private static function getHeaderAndBody($response) {
$header = self::http_parse_headers(substr($response, 0, strrpos($response,"\r\n\r\n")));
$body = substr($response, strrpos($response,"\r\n\r\n")+4);
return array($header,$body);
} | php | {
"resource": ""
} |
q3260 | Tx_Oelib_BackEndLoginManager.getLoggedInUser | train | public function getLoggedInUser($mapperName = \Tx_Oelib_Mapper_BackEndUser::class)
{
if ($mapperName === '') {
throw new \InvalidArgumentException('$mapperName must not be empty.', 1331318483);
}
if (!$this->isLoggedIn()) {
return null;
}
if ($this->loggedInUser) {
return $this->loggedInUser;
}
/** @var \Tx_Oelib_Mapper_BackEndUser $mapper */
$mapper = \Tx_Oelib_MapperRegistry::get($mapperName);
/** @var \Tx_Oelib_Model_BackEndUser $user */
$user = $mapper->find($this->getBackEndUserAuthentication()->user['uid']);
return $user;
} | php | {
"resource": ""
} |
q3261 | Package.boot | train | public function boot(\Neos\Flow\Core\Bootstrap $bootstrap)
{
$dispatcher = $bootstrap->getSignalSlotDispatcher();
$dispatcher->connect(ConfigurationManager::class, 'configurationManagerReady', function (ConfigurationManager $configurationManager) use ($dispatcher) {
$enabled = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'MOC.Varnish.enabled');
if ((boolean)$enabled === true) {
$dispatcher->connect('Neos\Neos\Service\PublishingService', 'nodePublished', 'MOC\Varnish\Service\ContentCacheFlusherService', 'flushForNode');
$dispatcher->connect('Neos\Flow\Mvc\Dispatcher', 'afterControllerInvocation', 'MOC\Varnish\Service\CacheControlService', 'addHeaders');
}
});
} | php | {
"resource": ""
} |
q3262 | Customizer.defaultPanel | train | public static function defaultPanel()
{
$argCount = func_num_args();
$args = func_get_args();
$sections = array();
for ($i = 0; $i < $argCount; ++$i) {
$sections[$args[$i]['id']] = $args[$i];
}
return array(
'sections' => $sections
);
} | php | {
"resource": ""
} |
q3263 | Customizer.panel | train | public static function panel($title, $description)
{
$argCount = func_num_args();
$args = func_get_args();
$sections = array();
for ($i = 2; $i < $argCount; ++$i) {
$sections[$args[$i]['id']] = $args[$i];
}
return array(
'title' => $title,
'description' => $description,
'sections' => $sections
);
} | php | {
"resource": ""
} |
q3264 | NextrasOrmEventsExtension.loadEntityMapping | train | private function loadEntityMapping(): array
{
$mapping = [];
$builder = $this->getContainerBuilder();
$repositories = $builder->findByType(IRepository::class);
foreach ($repositories as $repository) {
/** @var string $repositoryClass */
$repositoryClass = $repository->getEntity();
// Skip invalid repositoryClass name
if (!class_exists($repositoryClass)) {
throw new ServiceCreationException(sprintf("Repository class '%s' not found", $repositoryClass));
}
// Skip invalid subtype ob IRepository
if (!method_exists($repositoryClass, 'getEntityClassNames')) continue;
// Append mapping [repository => [entity1, entity2, entityN]
foreach ($repositoryClass::getEntityClassNames() as $entity) {
$mapping[$entity] = $repositoryClass;
}
}
return $mapping;
} | php | {
"resource": ""
} |
q3265 | GalleryPageController.Gallery | train | public function Gallery()
{
if ($this->Images()->exists()) {
// Create a list of images with generated gallery image and thumbnail
$images = ArrayList::create();
$pages = $this->PaginatedImages();
foreach ($this->PaginatedImages() as $image) {
$image_data = $image->toMap();
$image_data["GalleryImage"] = $this->GalleryImage($image);
$image_data["GalleryThumbnail"] = $this->GalleryThumbnail($image);
$images->add(ArrayData::create($image_data));
}
$vars = [
'PaginatedImages' => $pages,
'Images' => $images,
'Width' => $this->getFullWidth(),
'Height' => $this->getFullHeight()
];
return $this->renderWith(
[
'Gallery',
'ilateral\SilverStripe\Gallery\Includes\Gallery'
],
$vars
);
} else {
return "";
}
} | php | {
"resource": ""
} |
q3266 | GiroCheckout_SDK_Request_Cart.addItem | train | public function addItem($p_strName, $p_iQuantity, $p_iGrossAmt, $p_strEAN = "") {
if (empty($p_strName) || empty($p_iQuantity) || !isset($p_iGrossAmt)) {
throw new GiroCheckout_SDK_Exception_helper('Name, quantity and amount are mandatory for cart items');
}
$aItem = array(
"name" => $p_strName,
"quantity" => $p_iQuantity,
"grossAmount" => $p_iGrossAmt
);
if (!empty($p_strEAN)) {
$aItem["ean"] = $p_strEAN;
}
$this->m_aItems[] = $aItem;
} | php | {
"resource": ""
} |
q3267 | GiroCheckout_SDK_Request_Cart.getAllItems | train | public function getAllItems() {
if (version_compare(phpversion(), '5.3.0', '<')) {
return json_encode($this->m_aItems);
}
else {
return json_encode($this->m_aItems, JSON_UNESCAPED_UNICODE);
}
} | php | {
"resource": ""
} |
q3268 | subscribeContext.notifyConditions | train | public function notifyConditions($type, $condValues = array()) {
if (!is_array($condValues)) {
$condValues = array($condValues);
}
$context = new \Orion\Context\ContextFactory();
$context->put("type", $type);
$context->put("condValues", $condValues);
$this->_notifyConditions[] = $context->get();
return $this;
} | php | {
"resource": ""
} |
q3269 | DataTablesWrapper.removeColumn | train | public function removeColumn(DataTablesColumnInterface $column) {
if (true === array_key_exists($column->getData(), $this->columns)) {
$this->columns[$column->getData()]->getMapping()->setPrefix(null);
unset($this->columns[$column->getData()]);
}
return $this;
} | php | {
"resource": ""
} |
q3270 | Strings.sanitizeJsVarName | train | public static function sanitizeJsVarName($str)
{
$out = preg_replace("/ /", '_', trim($str));
$out = preg_replace("/[^A-Za-z_]/", '', $out);
return $out;
} | php | {
"resource": ""
} |
q3271 | ContextFactory.addAttribute | train | public function addAttribute($name, $value, $type = "Integer", $metadata = null) {
$attr = (object) [
"value" => $value,
"type" => $type
];
if(null != $metadata){
$attr->metadata = (object) $metadata;
}
$this->put($name, $attr);
} | php | {
"resource": ""
} |
q3272 | Tx_Oelib_Visibility_Node.setParent | train | public function setParent(\Tx_Oelib_Visibility_Node $parentNode)
{
if ($this->parentNode !== null) {
throw new \InvalidArgumentException('This node already has a parent node.', 1331488668);
}
$this->parentNode = $parentNode;
} | php | {
"resource": ""
} |
q3273 | TextualDateExtension.textualDateFilter | train | public function textualDateFilter($date)
{
if ( ! $date instanceof \DateTime) {
throw new \InvalidArgumentException('Textual Date Filter expects input to be a instance of DateTime');
}
$now = new \DateTime('now');
$diff = $now->diff($date);
$diffUnit = $this->getHighestDiffUnitAndValue($diff);
$temporalModifier = ($diff->invert)? 'ago':'next';
$translationString = $temporalModifier. '.' .$diffUnit['unit'];
// Override yesterday and tomorrow
if ($diffUnit['unit'] == 'd' && $diffUnit['value'] == 1) {
$translationString = ($diff->invert)? 'date.yesterday':'date.tomorrow';
}
// Override "just.now"
if ($diffUnit['unit'] == 'now') {
$translationString = 'date.just_now';
}
return $this->translator->transChoice($translationString, $diffUnit['value'], array('%value%' => $diffUnit['value']), 'date');
} | php | {
"resource": ""
} |
q3274 | TextualDateExtension.getHighestDiffUnitAndValue | train | protected function getHighestDiffUnitAndValue($diff)
{
// Manually define props due to Reflection Bug #53439 (PHP)
$properties = array('y', 'm', 'd', 'h', 'i', 's');
foreach($properties as $prop) {
if ($diff->$prop > 0) {
return array('unit' => $prop, 'value' => $diff->$prop);
}
}
return array('unit' => 'now', 'value' => 0);
} | php | {
"resource": ""
} |
q3275 | GiroCheckout_SDK_ResponseCode_helper.getMessage | train | public static function getMessage( $code, $lang = 'EN' ) {
if( $code < 0 ) {
return null;
} //code invalid
$lang = strtoupper( $lang );
if( !array_key_exists( $lang, self::$code ) ) { //language not found
$lang = 'EN';
}
if( array_key_exists( $code, self::$code[$lang] ) ) { //code not defined
return self::$code[$lang][$code];
}
return null;
} | php | {
"resource": ""
} |
q3276 | AjaxHandler.registerHooks | train | protected function registerHooks()
{
// Our callbacks are registered only on the admin side even for guest and frontend callbacks
if (is_admin())
{
switch ($this->accessType)
{
case 'guest':
Hooks::action('wp_ajax_nopriv_' . static::$ACTION, $this, 'doAjax');
break;
case 'logged':
Hooks::action('wp_ajax_' . static::$ACTION, $this, 'doAjax');
break;
case 'any':
Hooks::action('wp_ajax_nopriv_' . static::$ACTION, $this, 'doAjax');
Hooks::action('wp_ajax_' . static::$ACTION, $this, 'doAjax');
break;
default:
throw new \InvalidArgumentException("Invalid value for the Ajax access type parameter: "
. $this->accessType);
}
}
// If we have global variables
Hooks::filter('baobab/ajax/global_data', $this, 'addGlobalVariables');
} | php | {
"resource": ""
} |
q3277 | AjaxHandler.addGlobalVariables | train | public function addGlobalVariables($vars)
{
$globalVars = $this->getGlobalVariables();
if ($globalVars == null || empty($globalVars))
{
return $vars;
}
return array_merge($vars, $this->getGlobalVariables());
} | php | {
"resource": ""
} |
q3278 | Tx_Oelib_TemplateRegistry.getByFileName | train | public function getByFileName($fileName)
{
if (!isset($this->templates[$fileName])) {
/** @var \Tx_Oelib_Template $template */
$template = GeneralUtility::makeInstance(\Tx_Oelib_Template::class);
if ($fileName !== '') {
$template->processTemplateFromFile($fileName);
}
$this->templates[$fileName] = $template;
}
return clone $this->templates[$fileName];
} | php | {
"resource": ""
} |
q3279 | GiroCheckout_SDK_Config.setConfig | train | public function setConfig($key,$value) {
switch ($key) {
//curl options
case 'CURLOPT_CAINFO':
case 'CURLOPT_SSL_VERIFYPEER':
case 'CURLOPT_SSL_VERIFYHOST':
case 'CURLOPT_CONNECTTIMEOUT':
// Proxy
case 'CURLOPT_PROXY':
case 'CURLOPT_PROXYPORT':
case 'CURLOPT_PROXYUSERPWD':
// Debug
case 'DEBUG_LOG_PATH':
case 'DEBUG_MODE':
$this->config[$key] = $value;
return true;
break;
default:
return false;
}
} | php | {
"resource": ""
} |
q3280 | AbstractDataTablesTwigExtension.encodeOptions | train | protected function encodeOptions(array $options) {
if (0 === count($options)) {
return "{}";
}
ksort($options);
$output = json_encode($options, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
return str_replace("\n", "\n ", $output);
} | php | {
"resource": ""
} |
q3281 | AbstractDataTablesTwigExtension.jQueryDataTablesStandalone | train | protected function jQueryDataTablesStandalone($selector, $language, array $options) {
if (null !== $language) {
$options["language"] = ["url" => DataTablesWrapperHelper::getLanguageURL($language)];
}
$searches = ["%selector%", "%options%"];
$replaces = [$selector, $this->encodeOptions($options)];
$javascript = StringHelper::replace(self::JQUERY_DATATABLES_STANDALONE, $searches, $replaces);
return $this->getRendererTwigExtension()->coreScriptFilter($javascript);
} | php | {
"resource": ""
} |
q3282 | AbstractDataTablesTwigExtension.renderDataTablesColumn | train | private function renderDataTablesColumn(DataTablesColumnInterface $dtColumn, $rowScope = false) {
$attributes = [];
$attributes["scope"] = true === $rowScope ? "row" : null;
$attributes["class"] = $dtColumn->getClassname();
$attributes["width"] = $dtColumn->getWidth();
return static::coreHTMLElement("th", $dtColumn->getTitle(), $attributes);
} | php | {
"resource": ""
} |
q3283 | AbstractDataTablesTwigExtension.renderDataTablesRow | train | private function renderDataTablesRow(DataTablesWrapperInterface $dtWrapper, $wrapper) {
$innerHTML = "";
$count = count($dtWrapper->getColumns());
for ($i = 0; $i < $count; ++$i) {
$dtColumn = array_values($dtWrapper->getColumns())[$i];
$th = $this->renderDataTablesColumn($dtColumn, ("thead" === $wrapper && 0 === $i));
if ("" === $th) {
continue;
}
$innerHTML .= $th . "\n";
}
$tr = static::coreHTMLElement("tr", "\n" . $innerHTML);
return static::coreHTMLElement($wrapper, "\n" . $tr . "\n");
} | php | {
"resource": ""
} |
q3284 | Tx_Oelib_List.rebuildUidCache | train | private function rebuildUidCache()
{
$this->hasItemWithoutUid = false;
/** @var \Tx_Oelib_Model $item */
foreach ($this as $item) {
if ($item->hasUid()) {
$uid = $item->getUid();
$this->uids[$uid] = $uid;
} else {
$this->hasItemWithoutUid = true;
}
}
} | php | {
"resource": ""
} |
q3285 | Tx_Oelib_List.sort | train | public function sort($callbackFunction)
{
$items = iterator_to_array($this, false);
usort($items, $callbackFunction);
/** @var \Tx_Oelib_Model $item */
foreach ($items as $item) {
$this->detach($item);
$this->attach($item);
}
$this->markAsDirty();
} | php | {
"resource": ""
} |
q3286 | Tx_Oelib_List.purgeCurrent | train | public function purgeCurrent()
{
if (!$this->valid()) {
return;
}
if ($this->current()->hasUid()) {
$uid = $this->current()->getUid();
if (isset($this->uids[$uid])) {
unset($this->uids[$uid]);
}
}
$this->detach($this->current());
$this->markAsDirty();
} | php | {
"resource": ""
} |
q3287 | Tx_Oelib_Model.resetData | train | public function resetData(array $data)
{
$this->data = $data;
if ($this->existsKey('uid')) {
if (!$this->hasUid()) {
$this->setUid((int)$this->data['uid']);
}
unset($this->data['uid']);
}
$this->markAsLoaded();
if ($this->hasUid()) {
$this->markAsClean();
} else {
$this->markAsDirty();
}
} | php | {
"resource": ""
} |
q3288 | Tx_Oelib_Model.setUid | train | public function setUid($uid)
{
if ($this->hasUid()) {
throw new \BadMethodCallException('The UID of a model cannot be set a second time.', 1331489260);
}
if ($this->isVirgin()) {
$this->setLoadStatus(self::STATUS_GHOST);
}
$this->uid = $uid;
} | php | {
"resource": ""
} |
q3289 | Tx_Oelib_Model.load | train | private function load()
{
if ($this->isVirgin()) {
throw new \BadMethodCallException(
get_class($this) . '#' . $this->getUid()
. ': Please call setData() directly after instantiation first.',
1331489395
);
}
if ($this->isGhost()) {
if (!$this->hasLoadCallBack()) {
throw new \BadMethodCallException(
'Ghosts need a load callback function before their data can be accessed.',
1331489414
);
}
$this->markAsLoading();
call_user_func($this->loadCallback, $this);
}
} | php | {
"resource": ""
} |
q3290 | Tx_Oelib_Model.setToDeleted | train | public function setToDeleted()
{
if ($this->isLoaded()) {
$this->data['deleted'] = true;
$this->markAsDirty();
} else {
$this->markAsDead();
}
} | php | {
"resource": ""
} |
q3291 | Tx_Oelib_Model.isEmpty | train | public function isEmpty()
{
if ($this->isGhost()) {
$this->load();
$this->markAsLoaded();
}
return empty($this->data);
} | php | {
"resource": ""
} |
q3292 | DataTablesEnumerator.enumParameters | train | public static function enumParameters() {
return [
DataTablesRequestInterface::DATATABLES_PARAMETER_COLUMNS,
DataTablesRequestInterface::DATATABLES_PARAMETER_DRAW,
DataTablesRequestInterface::DATATABLES_PARAMETER_LENGTH,
DataTablesRequestInterface::DATATABLES_PARAMETER_ORDER,
DataTablesRequestInterface::DATATABLES_PARAMETER_SEARCH,
DataTablesRequestInterface::DATATABLES_PARAMETER_START,
];
} | php | {
"resource": ""
} |
q3293 | DataTablesEnumerator.enumTypes | train | public static function enumTypes() {
return [
DataTablesColumnInterface::DATATABLES_TYPE_DATE,
DataTablesColumnInterface::DATATABLES_TYPE_HTML,
DataTablesColumnInterface::DATATABLES_TYPE_HTML_NUM,
DataTablesColumnInterface::DATATABLES_TYPE_NUM,
DataTablesColumnInterface::DATATABLES_TYPE_NUM_FMT,
DataTablesColumnInterface::DATATABLES_TYPE_STRING,
];
} | php | {
"resource": ""
} |
q3294 | Tx_Oelib_IdentityMap.add | train | public function add(\Tx_Oelib_Model $model)
{
if (!$model->hasUid()) {
throw new \InvalidArgumentException('Add() requires a model that has a UID.', 1331488748);
}
$this->items[$model->getUid()] = $model;
$this->highestUid = max($this->highestUid, $model->getUid());
} | php | {
"resource": ""
} |
q3295 | Tx_Oelib_IdentityMap.get | train | public function get($uid)
{
if ($uid <= 0) {
throw new \InvalidArgumentException('$uid must be > 0.', 1331488761);
}
if (!isset($this->items[$uid])) {
throw new \Tx_Oelib_Exception_NotFound(
'This map currently does not contain a model with the UID ' .
$uid . '.'
);
}
return $this->items[$uid];
} | php | {
"resource": ""
} |
q3296 | ClientFactory.getKeyAuthClient | train | public function getKeyAuthClient($forceNew = false)
{
if ( ! isset($this->instances[self::CLIENT_KEY]) || $forceNew) {
$this->instances[self::CLIENT_KEY] = MeetupKeyAuthClient::factory($this->config);
}
return $this->instances[self::CLIENT_KEY];
} | php | {
"resource": ""
} |
q3297 | ClientFactory.getOauthClient | train | public function getOauthClient($forceNew = false)
{
if ( ! isset($this->instances[self::CLIENT_OAUTH]) || $forceNew) {
$this->instances[self::CLIENT_OAUTH] = MeetupOAuthClient::factory($this->getUpdatedOauthConfig());
}
return $this->instances[self::CLIENT_OAUTH];
} | php | {
"resource": ""
} |
q3298 | ClientFactory.getUpdatedOauthConfig | train | public function getUpdatedOauthConfig()
{
$token = $this->session->has(self::SESSION_TOKEN_KEY)
? $this->session->get(self::SESSION_TOKEN_KEY)
: false;
$tokenSecret = $this->session->has(self::SESSION_TOKEN_SECRET_KEY)
? $this->session->get(self::SESSION_TOKEN_SECRET_KEY)
: false;
return array_merge(
array('token' => $token, 'token_secret' => $tokenSecret),
$this->config
);
} | php | {
"resource": ""
} |
q3299 | ClientFactory.setSessionTokens | train | public function setSessionTokens($token, $tokenSecret = null)
{
$this->session->set(self::SESSION_TOKEN_KEY, $token);
$this->session->set(self::SESSION_TOKEN_SECRET_KEY, $tokenSecret);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.