_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
language
stringclasses
1 value
meta_information
dict
q900
FileOutputPrinter.setOutputPath
train
public function setOutputPath($path) { if (!file_exists($path)) { if (!mkdir($path, 0755, true)) { throw new BadOutputPathException( sprintf( 'Output path %s does not exist and could not be created!', $path ), $path ); } } else { if (!is_dir($path)) { throw new BadOutputPathException( sprintf(
php
{ "resource": "" }
q901
FoxyStripeController.processFoxyRequest
train
protected function processFoxyRequest(HTTPRequest $request) { $encryptedData = $request->postVar('FoxyData') ? urldecode($request->postVar('FoxyData')) : urldecode($request->postVar('FoxySubscriptionData'));
php
{ "resource": "" }
q902
FoxyStripeController.parseFeedData
train
private function parseFeedData($encryptedData, $decryptedData) { $orders = new \SimpleXMLElement($decryptedData); // loop over each transaction to find FoxyCart Order ID foreach ($orders->transactions->transaction
php
{ "resource": "" }
q903
FoxyStripeController.sso
train
public function sso() { // GET variables from FoxyCart Request $fcsid = $this->request->getVar('fcsid'); $timestampNew = strtotime('+30 days'); // get current member if logged in. If not, create a 'fake' user with Customer_ID = 0 // fake user will redirect to FC checkout, ask customer to log in // to do: consider a login/registration form here if not logged in if (!$Member = Security::getCurrentUser()) { $Member = new Member(); $Member->Customer_ID = 0; } $auth_token = sha1($Member->Customer_ID . '|' . $timestampNew . '|' . FoxyCart::getStoreKey()); $config = FoxyStripeSetting::current_foxystripe_setting(); if ($config->CustomSSL) {
php
{ "resource": "" }
q904
Cluster.terminate
train
private static function terminate(): Promise { if (self::$onClose === null) { return Promise\any([]); } if (self::$signalWatchers) { foreach (self::$signalWatchers as $watcher) {
php
{ "resource": "" }
q905
Cluster.onReceivedMessage
train
private static function onReceivedMessage(string $event, $data) {
php
{ "resource": "" }
q906
Cluster.createLogHandler
train
public static function createLogHandler(string $logLevel = LogLevel::DEBUG, bool $bubble = false): HandlerInterface { if (!self::isWorker()) { throw new \Error(__FUNCTION__ . " should only be called when running as a worker. " . "Create your own log handler when
php
{ "resource": "" }
q907
Util.prepareOptions
train
public static function prepareOptions($value, $defaults = []) { if (is_string($value)) {
php
{ "resource": "" }
q908
EzRSSAggregator.process
train
public function process(DOMElement $node, Item $item) { foreach ($this->keys
php
{ "resource": "" }
q909
CustomerExtension.onAfterWrite
train
public function onAfterWrite() { parent::onAfterWrite(); if ($this->owner->PasswordEncryption
php
{ "resource": "" }
q910
CustomerExtension.setDataFromTransaction
train
public function setDataFromTransaction($transaction) { foreach ($this->owner->config()->get('customer_map') as $type => $map) { switch ($type) { case 'int': foreach ($map as $foxyField => $foxyStripeField) { if ((int)$transaction->{$foxyField}) { $this->owner->{$foxyStripeField} = (int)$transaction->{$foxyField};
php
{ "resource": "" }
q911
CustomerExtension.resetPasswordEncryption
train
private function resetPasswordEncryption() { $defaultEncryption = Security::config()->get('password_encryption_algorithm'); if ($this->owner->PasswordEncryption != $defaultEncryption)
php
{ "resource": "" }
q912
ExtraFormBuilder.buildConstraint
train
protected function buildConstraint(array $constraint) { $extraFormConstraint = $this ->constraintRegistry ->getConstraint($constraint['extra_form_constraint']) ;
php
{ "resource": "" }
q913
ExtraFormBuilder.buildFormOptions
train
protected function buildFormOptions($name, array $field, $data = null) { // Allow sub options structure (collection case) if (isset($field['options']['constraints'])) { $field['options']['options'] = $this->buildFormOptions('', $field['options']);
php
{ "resource": "" }
q914
DonationProductController.updatevalue
train
public function updatevalue(\SilverStripe\Control\HTTPRequest $request) { if ($request->getVar('Price') && FoxyStripeSetting::current_foxystripe_setting()->CartValidation) { $vars = $request->getVars(); $signedPrice = FoxyCart_Helper::fc_hash_value($this->Code, 'price', $vars['Price'], 'name', false); $json = json_encode(['Price' => $signedPrice]);
php
{ "resource": "" }
q915
FastFeed.addFeed
train
public function addFeed($channel, $feed) { if (!filter_var($feed, FILTER_VALIDATE_URL)) { throw new LogicException('You tried to
php
{ "resource": "" }
q916
FastFeed.getFeed
train
public function getFeed($channel) { if (!isset($this->feeds[$channel])) { throw new LogicException('You tried to get a not existent
php
{ "resource": "" }
q917
FastFeed.setFeed
train
public function setFeed($channel, $feed) { if (!is_string($channel)) { throw new LogicException('You tried to add a invalid channel.'); }
php
{ "resource": "" }
q918
FastFeed.get
train
protected function get($url) { $request = $this->http->get( $url, array('User-Agent' => self::USER_AGENT.' v.'.self::VERSION) ); $response = $request->send();
php
{ "resource": "" }
q919
Permutation.getPermutations
train
public function getPermutations(array $sourceDataSet, $subsetSize = null) { $combinationMap = $this->_combination->getCombinations($sourceDataSet, $subsetSize); $permutationsMap = []; foreach ($combinationMap as $combination) { $permutationsMap = array_merge(
php
{ "resource": "" }
q920
Permutation._findPermutations
train
private function _findPermutations($combination) { // If the combination only has 1 element, then the permutation is the same as the combination if (count($combination) <= 1) { return [$combination]; } $permutationList = []; $startKey = $this->_processSubPermutations($combination, $permutationList); // Now that the first element has been rotated to the end, we calculate permutations until // we
php
{ "resource": "" }
q921
ContentElement.generate
train
public function generate() { // Get the content element object $this->objElement = \ElementsModel::findPublishedByAlias($this->type); if ($this->objElement === null) { return; } // Register the custom template if (!array_key_exists($this->objElement->template, TemplateLoader::getFiles())) { TemplateLoader::addFile($this->objElement->template, $this->objElement->getRelated('pid')->templates); } if (TL_MODE == 'BE' && $this->objElement->backendTpl) { $this->strTemplate = $this->objElement->backendTpl; } else { $this->strTemplate = $this->objElement->template; } if (TL_MODE == 'FE' && !BE_USER_LOGGED_IN && ($this->invisible || ($this->start != '' && $this->start > time()) || ($this->stop != '' && $this->stop < time()))) { return ''; } $this->Template = new Template($this->strTemplate); // Deliver
php
{ "resource": "" }
q922
ContentElement.compile
train
protected function compile() { // Get the pattern model collection $colPattern = \PatternModel::findVisibleByPid($this->objElement->id); if ($colPattern === null) { return; } // Get correct content element id (included content element) see #37 $intPid = ($this->origId) ? $this->origId : $this->id; // Get the data $colData = \DataModel::findByPid($intPid); if ($colData !== null) { foreach ($colData as $objData) { $arrData[$objData->pattern] = $objData; } } // Prepare values for every pattern foreach($colPattern as $objPattern) { if (!Pattern::hasOutput($objPattern->type)) { continue; } $strClass = Pattern::findClass($objPattern->type); if (!class_exists($strClass))
php
{ "resource": "" }
q923
RequestHandler.setPath
train
protected static function setPath($path = null) { if (!static::$pathStack) { $requestURI = parse_url($_SERVER['REQUEST_URI']);
php
{ "resource": "" }
q924
IbanToArrayTransformer.reverseTransform
train
public function reverseTransform($out) { if (null !== $out && is_array($out)) { return strtoupper( sprintf( '%s%s%s%s%s%s%s%s', $out['c1'], $out['c2'], $out['c3'], $out['c4'],
php
{ "resource": "" }
q925
tl_elements.setDefaultType
train
public function setDefaultType ($value, DataContainer $dc) { $db = Database::getInstance(); if ($value) { // There can only be one default element $db->prepare("UPDATE tl_elements
php
{ "resource": "" }
q926
tl_elements.checkTitle
train
public function checkTitle ($value, DataContainer $dc) { $db = Database::getInstance(); $objTitle = $db->prepare("SELECT id FROM tl_elements WHERE NOT id=? AND pid=? AND title=?") ->execute($dc->activeRecord->id, $dc->activeRecord->pid, $value); if
php
{ "resource": "" }
q927
tl_elements.generateAlias
train
public function generateAlias (DataContainer $dc) { $db = Database::getInstance(); // Generate alias from theme name and title $alias = \StringUtil::generateAlias(\ThemeModel::findById($dc->activeRecord->pid)->name . '-' . $dc->activeRecord->title); if ($alias != $dc->activeRecord->alias) { // Save alias to database $db->prepare("UPDATE tl_elements SET alias=? WHERE id=?") ->execute($alias, $dc->activeRecord->id);
php
{ "resource": "" }
q928
tl_elements.getContentElementTemplates
train
public function getContentElementTemplates(DataContainer $dc) { $arrTemplates = array(); // Get the default templates foreach (\TemplateLoader::getPrefixedFiles('ce_') as $strTemplate) { $arrTemplates[$strTemplate][] = 'root'; } $arrCustomized = glob(TL_ROOT . '/templates/ce_*'); // Add the customized templates if (is_array($arrCustomized)) { foreach ($arrCustomized as $strFile) { $strTemplate = basename($strFile, strrchr($strFile, '.')); $arrTemplates[$strTemplate][] = $GLOBALS['TL_LANG']['MSC']['global']; }
php
{ "resource": "" }
q929
tl_elements.editButton
train
public function editButton($row, $href, $label, $title, $icon, $attributes) { switch ($row['type']) { case 'group': return \Image::getHtml(str_replace('.', '_.', $icon), $label) . ' '; case 'element':
php
{ "resource": "" }
q930
ConfiguredTypeRepository.findByTags
train
public function findByTags(array $tags) { $qb = $this->createQueryBuilder('c'); foreach ($tags as $key => $tag) { $operator = substr($tag, 0, 1); if ($operator === '+' || $operator === '-') { $tag = substr($tag, 1); } $literalExpr = $qb->expr()->literal('%'.$tag.'%'); if ($operator === '-') { $qb->andWhere($qb->expr()->notLike('c.tags', $literalExpr)); } elseif ($operator === '+') { $qb->andWhere($qb->expr()->like('c.tags', $literalExpr));
php
{ "resource": "" }
q931
ConfiguredTypeRepository.getAllTags
train
public function getAllTags() { $qb = $this->createQueryBuilder('c'); $qb ->select('c.tags') ->where($qb->expr()->isNotNull('c.tags')) ->distinct() ; $tagStrings = array_map('current', $qb->getQuery()->getScalarResult()); $distinctTags = array(); foreach ($tagStrings as $tagString) {
php
{ "resource": "" }
q932
UserEndpoint.find
train
public function find($username) { $parameters['username'] = $username;
php
{ "resource": "" }
q933
UserEndpoint.update
train
public function update($username, $parameters = array()) { $parameters['username'] = $username;
php
{ "resource": "" }
q934
UserEndpoint.add
train
public function add($username, $parameters = array()) { $parameters['username'] = $username; return $this->apiClient->callEndpoint( self::ENDPOINT,
php
{ "resource": "" }
q935
UserEndpoint.findAvatars
train
public function findAvatars($username) { $parameters['username'] = $username;
php
{ "resource": "" }
q936
UserEndpoint.updatePassword
train
public function updatePassword($username, $password) { $parameters['username'] = $username; $parameters['password'] = $password; return $this->apiClient->callEndpoint(
php
{ "resource": "" }
q937
UserEndpoint.picker
train
public function picker($query, $maxResults = null, $showAvatar = null, $exclude = null) { $parameters = array( 'query' => $query, 'maxResults' => $maxResults, 'showAvatar' => $showAvatar,
php
{ "resource": "" }
q938
UserEndpoint.search
train
public function search($username, $startAt = null, $maxResults = null, $includeActive = null, $includeInactive = null) { $parameters = array( 'username' => $username, 'startAt' => $startAt, 'maxResults' => $maxResults,
php
{ "resource": "" }
q939
Versioning.getRevisionRecords
train
public static function getRevisionRecords($options = []) { $options = Util::prepareOptions($options, [ 'indexField' => false, 'conditions' => [], 'order' => false, 'limit' => false, 'offset' => 0, ]); $query = 'SELECT * FROM `%s` WHERE (%s)'; $params = [ static::getHistoryTable(), count($options['conditions']) ? join(') AND (', static::_mapConditions($options['conditions'])) : 1, ]; if ($options['order']) { $query .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order'])); }
php
{ "resource": "" }
q940
Versioning.beforeVersionedSave
train
public function beforeVersionedSave() { $this->wasDirty = false; if ($this->isDirty && static::$createRevisionOnSave) { // update creation time
php
{ "resource": "" }
q941
Versioning.afterVersionedSave
train
public function afterVersionedSave() { if ($this->wasDirty && static::$createRevisionOnSave) { // save a copy to history table $recordValues = $this->_prepareRecordValues(); $set = static::_mapValuesToSet($recordValues); DB::nonQuery(
php
{ "resource": "" }
q942
AuthenticationEndpoint.authentication
train
public function authentication($username, $password) { $endpoint = sprintf('authentication?username=%s', urlencode($username));
php
{ "resource": "" }
q943
ConfiguredType.getExtraFormConstraints
train
public function getExtraFormConstraints() { if (null === $this->extraFormType) { return null; }
php
{ "resource": "" }
q944
CaptchaTheme._theme
train
protected function _theme($theme_name = NULL, $options = array()) { if ( count($options) > 0 ) { // Avoid invalid options passed via array foreach ($options as $opt => $value) { if ( !array_key_exists($opt, $this->_recaptchaOptions) ) { unset($options[$opt]); } } } // Avoid empty values foreach ($this->_recaptchaOptions as $key => $value) { if ( NULL === $value || $value === 0 ) { unset($this->_recaptchaOptions[$key]); } } $this->_recaptchaOptions = array_merge($this->_recaptchaOptions, $options); if ( NULL !== $theme_name ) { $this->_recaptchaOptions['theme'] = $theme_name; } // Skip to default reCAPTCHA theme if there is no options if ( count($this->_recaptchaOptions) == 0 ) { return; } // Whether lang option value is not built-in try to set it from a translation file if ( isset($this->_recaptchaOptions['lang']) && !in_array($this->_recaptchaOptions['lang'], $this->_builtInlang) && !isset($this->_recaptchaOptions['custom_translations']) ) { $this->setTranslation($this->_recaptchaOptions['lang']); } // Whether theme empty set default theme to default for FALLBACK if ( !isset($this->_recaptchaOptions['theme']) && count($this->_recaptchaOptions) > 0 ) { $this->_recaptchaOptions['theme'] = 'red'; } // Skip to default reCAPTCHA theme if it's set to 'red' and there is no options at all if ( $this->_recaptchaOptions['theme'] === 'red' && count($this->_recaptchaOptions)
php
{ "resource": "" }
q945
CaptchaTheme.i18n
train
protected function i18n($key = NULL, $path = NULL) { static $RECAPTCHA_LANG; if ( $RECAPTCHA_LANG ) { return isset($key) ? $RECAPTCHA_LANG[$key] : $RECAPTCHA_LANG; } if ( !isset($this->_recaptchaOptions['lang']) ) { $language = $this->clientLang(); } else { $language = $this->_recaptchaOptions['lang']; } $RECAPTCHA_LANG = array( 'instructions_visual' => 'Enter the words above:', 'instructions_audio' => 'Type what you hear:', 'play_again' => 'Play sound again', 'cant_hear_this' => 'Download sound as MP3', 'visual_challenge' => 'Get an image CAPTCHA', 'audio_challenge' => 'Get an audio CAPTCHA', 'refresh_btn' => 'Get another CAPTCHA', 'help_btn' =>
php
{ "resource": "" }
q946
CaptchaTheme.clientLang
train
public function clientLang() { if ( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) { $language = explode(',', preg_replace('/(;\s?q=[0-9\.]+)|\s/i', '',
php
{ "resource": "" }
q947
ReCaptchaType.isEnabled
train
private function isEnabled() { if (!$this->enabled) { return false; } if ($this->authorizationChecker) { foreach ($this->trustedRoles as $trustedRole) {
php
{ "resource": "" }
q948
ActiveRecord.init
train
public static function init() { $className = get_called_class(); if (empty(static::$_fieldsDefined[$className])) { static::_defineFields(); static::_initFields(); static::$_fieldsDefined[$className] = true; } if (empty(static::$_relationshipsDefined[$className]) && static::isRelational()) { static::_defineRelationships(); static::_initRelationships();
php
{ "resource": "" }
q949
ActiveRecord.setValue
train
public function setValue($name, $value) { // handle field if (static::fieldExists($name)) { $this->_setFieldValue($name, $value);
php
{ "resource": "" }
q950
ActiveRecord.create
train
public static function create($values = [], $save = false) { $className = get_called_class(); // create class $ActiveRecord = new $className();
php
{ "resource": "" }
q951
ActiveRecord.changeClass
train
public function changeClass($className = false, $fieldValues = false) { if (!$className) { return $this; } $this->_record[static::_cn('Class')] = $className; $ActiveRecord = new $className($this->_record, true, $this->isPhantom); if ($fieldValues) {
php
{ "resource": "" }
q952
ActiveRecord.setFields
train
public function setFields($values) { foreach ($values as
php
{ "resource": "" }
q953
ActiveRecord.getData
train
public function getData() { $data = []; foreach (static::$_classFields[get_called_class()] as $field => $options) {
php
{ "resource": "" }
q954
ActiveRecord.save
train
public function save($deep = true) { // run before save $this->beforeSave(); if (static::isVersioned()) { $this->beforeVersionedSave(); } // set created if (static::fieldExists('Created') && (!$this->Created || ($this->Created == 'CURRENT_TIMESTAMP'))) { $this->Created = time(); } // validate if (!$this->validate($deep)) { throw new Exception('Cannot save invalid record'); } $this->clearCaches(); if ($this->isDirty) { // prepare record values $recordValues = $this->_prepareRecordValues(); // transform record to set array $set = static::_mapValuesToSet($recordValues); // create new or update existing if ($this->_isPhantom) { DB::nonQuery( 'INSERT INTO `%s` SET %s', [ static::$tableName, join(',', $set), ], [static::class,'handleError'] ); $this->_record[static::$primaryKey ? static::$primaryKey : 'ID'] = DB::insertID(); $this->_isPhantom = false; $this->_isNew = true; } elseif (count($set)) { DB::nonQuery(
php
{ "resource": "" }
q955
ActiveRecord.destroy
train
public function destroy() { if (static::isVersioned()) { if (static::$createRevisionOnDestroy) { // save a copy to history table if ($this->fieldExists('Created')) { $this->Created = time(); } $recordValues = $this->_prepareRecordValues(); $set = static::_mapValuesToSet($recordValues); DB::nonQuery( 'INSERT INTO `%s` SET %s',
php
{ "resource": "" }
q956
ActiveRecord.delete
train
public static function delete($id) { DB::nonQuery('DELETE FROM `%s` WHERE `%s` = %u', [ static::$tableName, static::_cn(static::$primaryKey ? static::$primaryKey : 'ID'),
php
{ "resource": "" }
q957
ActiveRecord.getByID
train
public static function getByID($id) { $record = static::getRecordByField(static::$primaryKey ? static::$primaryKey : 'ID',
php
{ "resource": "" }
q958
ActiveRecord.getByField
train
public static function getByField($field, $value, $cacheIndex = false) { $record =
php
{ "resource": "" }
q959
ActiveRecord.getRecordByField
train
public static function getRecordByField($field, $value, $cacheIndex = false) { $query = 'SELECT * FROM `%s` WHERE `%s` = "%s" LIMIT 1'; $params = [ static::$tableName, static::_cn($field), DB::escape($value), ]; if ($cacheIndex) {
php
{ "resource": "" }
q960
ActiveRecord.getRecordByWhere
train
public static function getRecordByWhere($conditions, $options = []) { if (!is_array($conditions)) { $conditions = [$conditions]; } $options = Util::prepareOptions($options, [ 'order' => false, ]); // initialize conditions and order $conditions = static::_mapConditions($conditions); $order = $options['order'] ? static::_mapFieldOrder($options['order']) : []; return DB::oneRecord(
php
{ "resource": "" }
q961
ActiveRecord.getAllByContextObject
train
public static function getAllByContextObject(ActiveRecord $Record, $options = []) {
php
{ "resource": "" }
q962
ActiveRecord.buildExtraColumns
train
public static function buildExtraColumns($columns) { if (!empty($columns)) { if (is_array($columns)) { foreach ($columns as $key => $value) { return ', '.$value.'
php
{ "resource": "" }
q963
ActiveRecord.buildHaving
train
public static function buildHaving($having) { if (!empty($having)) {
php
{ "resource": "" }
q964
ActiveRecord.getAllRecordsByWhere
train
public static function getAllRecordsByWhere($conditions = [], $options = []) { $className = get_called_class(); $options = Util::prepareOptions($options, [ 'indexField' => false, 'order' => false, 'limit' => false, 'offset' => 0, 'calcFoundRows' => !empty($options['limit']), 'extraColumns' => false, 'having' => false, ]); // initialize conditions if ($conditions) { if (is_string($conditions)) { $conditions = [$conditions]; } $conditions = static::_mapConditions($conditions); } // build query $query = 'SELECT %1$s `%3$s`.*'; $query .= static::buildExtraColumns($options['extraColumns']); $query .= ' FROM `%2$s` AS `%3$s`'; $query .= ' WHERE (%4$s)'; $query .= static::buildHaving($options['having']); $params = [ $options['calcFoundRows'] ? 'SQL_CALC_FOUND_ROWS' : '', static::$tableName, $className::$rootClass, $conditions ? join(') AND (', $conditions) : '1',
php
{ "resource": "" }
q965
ActiveRecord.getAllRecords
train
public static function getAllRecords($options = []) { $options = Util::prepareOptions($options, [ 'indexField' => false, 'order' => false, 'limit' => false, 'calcFoundRows' => false, 'offset' => 0, ]); $query = 'SELECT '.($options['calcFoundRows'] ? 'SQL_CALC_FOUND_ROWS' : '').'* FROM `%s`'; $params = [ static::$tableName, ]; if ($options['order']) { $query .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order'])); }
php
{ "resource": "" }
q966
ActiveRecord.instantiateRecords
train
public static function instantiateRecords($records) { foreach ($records as &$record) { $className = static::_getRecordClass($record);
php
{ "resource": "" }
q967
ActiveRecord.getFieldOptions
train
public static function getFieldOptions($field, $optionKey = false) { if ($optionKey) { return static::$_classFields[get_called_class()][$field][$optionKey];
php
{ "resource": "" }
q968
ActiveRecord.getColumnName
train
public static function getColumnName($field) { static::init(); if (!static::fieldExists($field)) { throw
php
{ "resource": "" }
q969
ActiveRecord.getValidationError
train
public function getValidationError($field) { // break apart path $crumbs = explode('.', $field); // resolve path recursively $cur = &$this->_validationErrors; while ($crumb = array_shift($crumbs)) { if (array_key_exists($crumb, $cur)) {
php
{ "resource": "" }
q970
ActiveRecord._getRecordClass
train
protected static function _getRecordClass($record) { $static = get_called_class(); if (!static::fieldExists('Class')) { return $static;
php
{ "resource": "" }
q971
ActiveRecord._getFieldValue
train
protected function _getFieldValue($field, $useDefault = true) { $fieldOptions = static::$_classFields[get_called_class()][$field]; if (isset($this->_record[$fieldOptions['columnName']])) { $value = $this->_record[$fieldOptions['columnName']]; // apply type-dependent transformations switch ($fieldOptions['type']) { case 'password': { return $value; } case 'timestamp': { if (!isset($this->_convertedValues[$field])) { if ($value && $value != '0000-00-00 00:00:00') { $this->_convertedValues[$field] = strtotime($value); } else { $this->_convertedValues[$field] = null; } } return $this->_convertedValues[$field]; } case 'serialized': { if (!isset($this->_convertedValues[$field])) { $this->_convertedValues[$field] = is_string($value) ? unserialize($value) : $value; } return $this->_convertedValues[$field]; } case 'set': case 'list': { if (!isset($this->_convertedValues[$field])) { $delim = empty($fieldOptions['delimiter']) ? ',' : $fieldOptions['delimiter']; $this->_convertedValues[$field] = array_filter(preg_split('/\s*'.$delim.'\s*/', $value)); } return $this->_convertedValues[$field];
php
{ "resource": "" }
q972
ActiveRecord._setFieldValue
train
protected function _setFieldValue($field, $value) { // ignore setting versioning fields if (static::isVersioned()) { if (array_key_exists($field, static::$versioningFields)) { return false; } } if (!static::fieldExists($field)) { return false; } $fieldOptions = static::$_classFields[get_called_class()][$field]; // no overriding autoincrements if ($fieldOptions['autoincrement']) { return false; } // pre-process value $forceDirty = false; switch ($fieldOptions['type']) { case 'clob': case 'string': { $value = $this->_setStringValue($fieldOptions, $value); break; } case 'boolean': { $value = $this->_setBooleanValue($value); break; } case 'decimal': { $value = $this->_setDecimalValue($value); break; } case 'int': case 'uint': case 'integer': { $value = $this->_setIntegerValue($fieldOptions, $value); break; } case 'timestamp': { $value = $this->_setTimestampValue($value); break; } case 'date': { $value = $this->_setDateValue($value); break; } // these types are converted to strings from another PHP type on save case 'serialized': { $this->_convertedValues[$field] = $value; $value = $this->_setSerializedValue($value); break;
php
{ "resource": "" }
q973
ElementsModel.findPublishedByAlias
train
public function findPublishedByAlias($strAlias, array $arrOptions=array()) { $t = static::$strTable;
php
{ "resource": "" }
q974
CollectionEventSubscriber.preSubmitData
train
public function preSubmitData(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); if (null === $data || '' === $data) { $data = array(); }
php
{ "resource": "" }
q975
CollectionEventSubscriber.buildCollection
train
public function buildCollection(FormEvent $event, $eventName) { $form = $event->getForm(); for ($i = 0; $i < $this->options['max_items']; ++$i) { $required = $i < $this->options['min_items'] ? true : false; $displayed = $i < $this->options['min_items'] || $this->isDisplayable($event, $i, $eventName); $options = $this->options['options']; $options['required'] = isset($options['required']) ? $options['required'] && $required : $required ; $options['attr'] = array_replace( isset($options['attr']) ? $options['attr'] : array(), array( 'data-collection-id' => $this->options['collection_id'], 'data-display' => $displayed ? 'show' : 'hide', 'data-position' => $i, )
php
{ "resource": "" }
q976
CollectionEventSubscriber.changeData
train
public function changeData(FormEvent $event) { $data = $event->getData(); if (null === $data) { $data = array();
php
{ "resource": "" }
q977
CollectionEventSubscriber.onSubmit
train
public function onSubmit(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); if (null === $data) { $data = array(); } if (!is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) { throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)'); } // The data mapper only adds, but does not remove items, so do this here $toDelete = array(); foreach ($data as $name => $child) { if (null === $child || ( $form->get($name)->has('__to_remove') &&
php
{ "resource": "" }
q978
CollectionEventSubscriber.isDisplayable
train
protected function isDisplayable(FormEvent $event, $i, $eventName) { $form = $event->getForm(); $data = $event->getData(); if (!isset($data[$i])) { return false; } $item = is_object($data[$i]) ? (array) $data[$i] : $data[$i]; if (!is_array($item)) { return true; } if (FormEvents::PRE_SUBMIT === $eventName) { if (isset($item['__to_remove'])) { return !(bool) $item['__to_remove']; } } foreach ($item as $k =>
php
{ "resource": "" }
q979
SQL.getCreateTable
train
public static function getCreateTable($recordClass, $historyVariant = false) { $indexes = $historyVariant ? [] : $recordClass::$indexes; $fulltextColumns = []; $queryString = []; // history table revisionID field if ($historyVariant) { $queryString[] = '`RevisionID` int(10) unsigned NOT NULL auto_increment'; $queryString[] = 'PRIMARY KEY (`RevisionID`)'; } $queryString = array_merge($queryString, static::compileFields($recordClass, $historyVariant)); if (!$historyVariant) { // If ContextClass && ContextID are members of this model let's index them if ($recordClass::fieldExists('ContextClass') && $recordClass::fieldExists('ContextID')) { $queryString[] = static::getContextIndex($recordClass); } $fulltextColumns = static::getFullTextColumns($recordClass); }
php
{ "resource": "" }
q980
Watcher.stop
train
public function stop() { if (!$this->running) { return; } $this->running = false; $promise = call(function () { $promises = []; foreach (clone $this->workers as $worker) { \assert($worker instanceof Internal\IpcParent); $promises[] = call(function () use ($worker) { list($process, $promise) = $this->workers[$worker]; \assert($process instanceof Process); try { yield $worker->shutdown(); yield Promise\timeout($promise, self::WORKER_TIMEOUT); } catch (ContextException $exception) { // Ignore if the worker has already died unexpectedly. } finally { if ($process->isRunning()) { $process->kill();
php
{ "resource": "" }
q981
MySQL.escape
train
public static function escape($data) { if (is_string($data)) { $data = static::getConnection()->quote($data); $data = substr($data, 1, strlen($data)-2); return $data; } elseif (is_array($data)) { foreach ($data as $key=>$string) {
php
{ "resource": "" }
q982
MySQL.allRecords
train
public static function allRecords($query, $parameters = [], $errorHandler = null) { // execute query $result = static::query($query, $parameters, $errorHandler); $records = [];
php
{ "resource": "" }
q983
MySQL.allValues
train
public static function allValues($valueKey, $query, $parameters = [], $errorHandler = null) { // execute query $result = static::query($query, $parameters, $errorHandler); $records = [];
php
{ "resource": "" }
q984
MySQL.oneRecordCached
train
public static function oneRecordCached($cacheKey, $query, $parameters = [], $errorHandler = null) { // check for cached record if (array_key_exists($cacheKey, static::$_record_cache)) { // return cache hit return static::$_record_cache[$cacheKey]; } // preprocess and execute query $result = static::query($query, $parameters, $errorHandler);
php
{ "resource": "" }
q985
MySQL.oneRecord
train
public static function oneRecord($query, $parameters = [], $errorHandler = null) { // preprocess and execute query $result = static::query($query, $parameters, $errorHandler);
php
{ "resource": "" }
q986
MySQL.oneValue
train
public static function oneValue($query, $parameters = [], $errorHandler = null) { // get the first record $record = static::oneRecord($query, $parameters, $errorHandler);
php
{ "resource": "" }
q987
MySQL.handleError
train
public static function handleError($query = '', $queryLog = false, $errorHandler = null) { if (is_callable($errorHandler, false, $callable)) { return call_user_func($errorHandler, $query, $queryLog); } // save queryLog if ($queryLog) { $error = static::getConnection()->errorInfo(); $queryLog['error'] = $error[2]; static::finishQueryLog($queryLog); } // get error message $error = static::getConnection()->errorInfo(); $message = $error[2]; if (App::$Config['environment']=='dev') { $Handler = \Divergence\App::$whoops->popHandler();
php
{ "resource": "" }
q988
MySQL.preprocessQuery
train
protected static function preprocessQuery($query, $parameters = []) { if (is_array($parameters) && count($parameters)) { return vsprintf($query, $parameters); } else { if (isset($parameters)) {
php
{ "resource": "" }
q989
MySQL.finishQueryLog
train
protected static function finishQueryLog(&$queryLog, $result = false) { if ($queryLog == false) { return false; } // save finish time and number of affected rows $queryLog['time_finish'] = sprintf('%f', microtime(true)); $queryLog['time_duration_ms'] = ($queryLog['time_finish'] - $queryLog['time_start']) * 1000; // save result information if ($result) {
php
{ "resource": "" }
q990
RequestSerializer.serialize
train
public static function serialize(RequestInterface $request): string {
php
{ "resource": "" }
q991
BelongsTo.getContent
train
public function getContent() { return strtr($this->getRelationStubContent(), [ '{{name}}' => $this->name, '{{relatedTable}}' => $this->relatedModel->getTable(),
php
{ "resource": "" }
q992
ThrottlingMiddleware.safeHandle
train
protected function safeHandle(Request $request, Closure $next, int $limit, $decay, bool $global, bool $headers) { if ($this->shouldPassThrough($request)) { return $next($request); } $key = $global ? sha1($request->ip()) : $request->fingerprint(); if ($this->limiter->tooManyAttempts($key, $limit, $decay)) { throw $this->buildException($key, $limit, $headers);
php
{ "resource": "" }
q993
RecordsRequestHandler.handleRequest
train
public static function handleRequest() { // save static class static::$calledClass = get_called_class(); // handle JSON requests if (static::peekPath() == 'json') { // check access for API response modes static::$responseMode = static::shiftPath(); if (in_array(static::$responseMode, ['json','jsonp'])) {
php
{ "resource": "" }
q994
Controller.addContentElementsCSS
train
public function addContentElementsCSS ($strBuffer='', $objTemplate=null) { foreach (array('CSS', 'SCSS' , 'LESS') as $strType) { if ($GLOBALS['TL_CTB_' . $strType] == '') { continue; } $strKey = substr(md5($strType . $GLOBALS['TL_CTB_CSS'] . $GLOBALS['TL_CTB_SCSS'] . $GLOBALS['TL_CTB_LESS']), 0, 12); $strPath = 'assets/css/' . $strKey . '.' . strtolower($strType); // Write to a temporary file in the assets folder if (!file_exists($strPath))
php
{ "resource": "" }
q995
Controller.addContentElementsJS
train
public function addContentElementsJS ($strBuffer='', $objTemplate=null) { if ($GLOBALS['TL_CTB_JS'] == '') { return $strBuffer; } $strKey = substr(md5('js' . $GLOBALS['TL_CTB_JS']), 0, 12); $strPath = 'assets/js/' . $strKey . '.js';
php
{ "resource": "" }
q996
Controller.registerBlockElements
train
public function registerBlockElements () { // Don´t register twice if (isset($GLOBALS['TL_CTE']['CTE'])) { return; } $db = \Database::getInstance(); if ($db->tableExists("tl_elements")) { $arrElements = $db->prepare("SELECT * FROM tl_elements ORDER BY sorting ASC")
php
{ "resource": "" }
q997
Controller.getRootPageId
train
public static function getRootPageId ($strTable, $intId) { if ($strTable == 'tl_article') { $objArticle = \ArticleModel::findById($intId); if ($objArticle === null) { return null; } $objPage = \PageModel::findWithDetails($objArticle->pid); if ($objPage === null) { return null; } return $objPage->rootId; } elseif($strTable == 'tl_news') { $objNews = \NewsModel::findById($intId); if ($objNews === null) { return null; } $objPage = \PageModel::findWithDetails($objNews->getRelated('pid')->jumpTo); if ($objPage === null) { return null; } return $objPage->rootId; } else { //
php
{ "resource": "" }
q998
Controller.addBackendCSS
train
private static function addBackendCSS($objLayout) { $arrCSS = \StringUtil::deserialize($objLayout->backendCSS); if (!empty($arrCSS) && is_array($arrCSS)) { // Consider the sorting order (see #5038) if ($objLayout->orderBackendCSS != '') { $tmp = \StringUtil::deserialize($objLayout->orderBackendCSS); if (!empty($tmp) && is_array($tmp)) { // Remove all values $arrOrder = array_map(function(){}, array_flip($tmp)); // Move the matching elements to their position in $arrOrder foreach ($arrCSS as $k=>$v)
php
{ "resource": "" }
q999
Controller.addBackendJS
train
private static function addBackendJS($objLayout) { $arrJS = \StringUtil::deserialize($objLayout->backendJS); if (!empty($arrJS) && is_array($arrJS)) { // Consider the sorting order (see #5038) if ($objLayout->orderBackendJS != '') { $tmp = \StringUtil::deserialize($objLayout->orderBackendJS); if (!empty($tmp) && is_array($tmp)) { // Remove all values $arrOrder = array_map(function(){}, array_flip($tmp)); // Move the matching elements to their position in $arrOrder foreach ($arrJS as $k=>$v)
php
{ "resource": "" }