_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11600 | GroupVersionHydrator.hydrateEntity | train | private function hydrateEntity(EntityInterface $entity, $group, $version)
{
$entity->setEntityGroup($group);
$entity->setAPIVersion($version);
// hydrate all the sub-fields recursively using JMS to extract them and identify their type
$metadata = $this->metadataFactory->getMetadataForClass(\get_class($entity));
/** @var PropertyMetadata $property */
foreach ($metadata->propertyMetadata as $property) {
if ('array' === $property->type['name']) {
$array = $property->getValue($entity);
if (\is_array($array) && \count($array) > 0) {
$first = \array_values($array)[0];
if ((\is_object($first) || \is_array($first))) {
$this->hydrateArray($array, $group, $version);
}
}
} elseif (($object = $property->getValue($entity)) instanceof EntityInterface) {
$this->hydrateEntity($object, $group, $version);
}
}
return $entity;
} | php | {
"resource": ""
} |
q11601 | APIRequests.request | train | public static function request(
$arg_endpoint,
$arg_method,
array $arg_data = array(),
array $arg_headers = array()
) {
$return = array();
$headers = array(
'Accept: application/json',
'DUE-API-KEY: '.Due::getApiKey(),
'DUE-PLATFORM-ID: '.Due::getPlatformId(),
);
if($arg_method == APIRequests::METHOD_PUT){
$headers[]= 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
}
$headers = array_merge($headers, $arg_headers);
$full_url = Due::getRootPath().$arg_endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $full_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $arg_method);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if(!empty($arg_data)){
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arg_data));
}
$response = curl_exec($ch);
$err = curl_error($ch);
if (!$err) {
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$return['headers'] = self::headersToArray($headers);
$return['body'] = json_decode($body, true);
if(!empty($return['body']['errors'][0])){
$api_error = $return['body']['errors'][0];
$message = (empty($api_error['message']) ? '' : $api_error['message']);
$code = (empty($api_error['code']) ? 0 : $api_error['code']);
throw new \Exception($message,$code);
}
}else{
throw new \Exception($err);
}
return $return;
} | php | {
"resource": ""
} |
q11602 | APIRequests.headersToArray | train | public static function headersToArray($header_text)
{
$headers = array();
foreach (explode("\r\n", $header_text) as $i => $line)
if ($i === 0)
$headers['http_code'] = $line;
else
{
if(!empty($line) && strpos($line, ':') !== false){
list ($key, $value) = explode(': ', $line);
$headers['headers'][] = array(
'key' => $key,
'value' => $value,
);
}
}
return $headers;
} | php | {
"resource": ""
} |
q11603 | Application.loadFactory | train | protected function loadFactory(?array $params=[])
{
if (\is_array($params) && !empty($params['class']) && \class_exists($params['class'])) {
$factory = new $params['class']($params['options'] ?? []);
$this->getLogger()->debug('Factory created',[
'factory'=>$factory
]);
return $factory;
} else {
$this->getLogger()->error('Factory not found',[
'params'=>$params
]);
}
return null;
} | php | {
"resource": ""
} |
q11604 | Application.setCookie | train | public function setCookie(string $name, string $value=null, int $expire=0, string $path='', string $domain='', bool $secure=false, bool $httpOnly=false)
{
if ( \array_key_exists($name,$this->cookies) && \is_null($value) ) {
# Remove the Cookie
$this->cookies = \array_diff_key($this->cookies,[$name=>'']);
} else {
# Set the Cookie
$this->cookies[$name] = [
'name' => $name,
'value' => $value,
'expire' => $expire,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httpOnly' => $httpOnly
];
}
return true;
} | php | {
"resource": ""
} |
q11605 | Application.sendResponse | train | public function sendResponse()
{
# Set HTTP Response Code
\http_response_code($this->getResponse()->getStatusCode());
# Set All HTTP headers from Response Object
foreach ($this->getResponse()->getHeaders() as $header => $value) {
if (\is_array($value)) {
$values = \implode(';',$value);
} else {
$values = $value;
}
\header($header.': '.$values);
}
# Remove the "x-powered-by" header set by PHP
if (\function_exists('header_remove')) \header_remove('x-powered-by');
# Set Cookies
foreach ($this->cookies as $cookie)
{
\setCookie( $cookie['name'],
$cookie['value'],
$cookie['expire'] ?? 0,
$cookie['path'] ?? '',
$cookie['domain'] ?? '',
$cookie['secure'] ?? false,
$cookie['httponly'] ?? false
);
}
##
## Send a file or a body?
##
if ( !empty($this->responseFile) ) {
if (\file_exists($this->responseFile)) {
# Debug log
$this->getLogger()->debug('Sending file',[
'code'=>$this->getResponse()->getStatusCode(),
'headers'=>$this->getResponse()->getHeaders(),
'file'=>$this->responseFile
]);
# Send the file
\readfile($this->responseFile);
} else {
# Log warning
$this->getLogger()->warning('File not found',['file'=>$this->responseFile]);
# Fake a response
\response('',404);
# Set HTTP Response Code
\http_response_code(404);
}
} else {
# Get body
$body = (string)$this->response->getBody();
# Debug log
$this->getLogger()->debug('Sending body',[
'code' => $this->getResponse()->getStatusCode(),
'headers' => $this->getResponse()->getHeaders(),
'size' => \strlen($body)
]);
# Send the Body
echo $body;
}
return $this;
} | php | {
"resource": ""
} |
q11606 | TaxModifier.updateTotal | train | public function updateTotal(&$total) {
$rate = (float)self::config()->get('tax_rate') / 100;
$tax = $total * $rate;
$this->setPriceModification($tax);
if (!(bool)self::config()->get('inclusive')) {
$total += $tax;
}
} | php | {
"resource": ""
} |
q11607 | TaxModifier.getTableTitle | train | public function getTableTitle()
{
$rate = _t(
'TaxModifier.TABLE_TITLE',
'{rate}% BTW',
null,
array(
'rate' => (float)self::config()->get('tax_rate')
)
);
if ((bool)self::config()->get('inclusive')) {
$inc = _t('TaxModifier.INCLUSIVE', '(Incl.)');
$rate .= " $inc";
}
return $rate;
} | php | {
"resource": ""
} |
q11608 | TaxModifier.findOrMake | train | public static function findOrMake(Reservation $reservation)
{
if (!$modifier = $reservation->PriceModifiers()->find('ClassName', self::class)) {
$modifier = self::create();
$modifier->write();
}
return $modifier;
} | php | {
"resource": ""
} |
q11609 | MapTableMap.doDelete | train | public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(MapTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \eXpansion\Bundle\Maps\Model\Map) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(MapTableMap::DATABASE_NAME);
$criteria->add(MapTableMap::COL_ID, (array) $values, Criteria::IN);
}
$query = MapQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) {
MapTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) {
MapTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
} | php | {
"resource": ""
} |
q11610 | FileSystem.getUserData | train | public function getUserData() : FilesystemInterface
{
if ($this->connectionType == self::CONNECTION_TYPE_LOCAL) {
return $this->getLocalAdapter();
} else {
return $this->remoteAdapter;
}
} | php | {
"resource": ""
} |
q11611 | FileSystem.getLocalAdapter | train | protected function getLocalAdapter() : FilesystemInterface
{
if (is_null($this->localAdapter)) {
$dir = $this->factory->getConnection()->getMapsDirectory();
$this->localAdapter = new \League\Flysystem\Filesystem(new Local($dir.'/../'));
}
return $this->localAdapter;
} | php | {
"resource": ""
} |
q11612 | PluginManager.isPluginCompatible | train | protected function isPluginCompatible(PluginDescription $plugin, $enabledPlugins, $title, $mode, $script, Map $map)
{
// first check for other plugins.
foreach ($plugin->getParents() as $parentPluginId) {
if (!isset($enabledPlugins[$parentPluginId])) {
// A parent plugin is missing. Can't enable plugin.
return false;
}
}
// Now check for data providers.
foreach ($plugin->getDataProviders() as $dataProvider) {
$dataProviders = explode("|", $dataProvider);
$foundOne = false;
foreach ($dataProviders as $provider) {
$providerId = $this->dataProviderManager->getCompatibleProviderId($provider, $title, $mode, $script, $map);
if (!is_null($providerId) && isset($enabledPlugins[$providerId])) {
// Either there are no data providers compatible or the only one compatible
$foundOne = true;
break;
}
}
if (!$foundOne) {
return false;
}
}
// If data provider need to check if it was "the chosen one".
if ($plugin->isIsDataProvider()) {
$selectedProvider = $this->dataProviderManager->getCompatibleProviderId(
$plugin->getDataProviderName(),
$title,
$mode,
$script,
$map
);
if ($plugin->getPluginId() != $selectedProvider) {
// This data provider wasn't the one selected and therefore the plugin isn't compatible.
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q11613 | PluginManager.enablePlugin | train | protected function enablePlugin(PluginDescription $plugin, $title, $mode, $script, Map $map)
{
$notify = false;
$plugin->setIsEnabled(true);
$pluginService = $this->container->get($plugin->getPluginId());
if (!isset($this->enabledPlugins[$plugin->getPluginId()])) {
$notify = true;
}
foreach ($plugin->getDataProviders() as $provider) {
$dataProviders = explode("|", $provider);
foreach ($dataProviders as $dataProvider) {
$this->dataProviderManager->registerPlugin($dataProvider, $plugin->getPluginId(), $title, $mode, $script, $map);
}
}
$this->enabledPlugins[$plugin->getPluginId()] = $plugin;
return $notify ? $pluginService : null;
} | php | {
"resource": ""
} |
q11614 | InstallHelperService.getDomain | train | public function getDomain()
{
$uri = $this->getServiceLocator()->get('Application')->getMvcEvent()->getRequest()->getUri();
return sprintf('%s://%s', $uri->getScheme(), $uri->getHost());
} | php | {
"resource": ""
} |
q11615 | InstallHelperService.checkMysqlConnection | train | public function checkMysqlConnection($host, $db, $user, $pass)
{
$results = array();
$isConnected = 0;
$isDatabaseExists = 0;
$isDatabaseCollationNameValid = 0;
$isPassCorrect = 1;
if($this->isDomainExists($host)) {
$isConnected = 1;
try {
$dbAdapter = new DbAdapter(array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=INFORMATION_SCHEMA;host='.$host,
'username' => $user,
'password' => $pass,
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
),
));
$sql = new Sql($dbAdapter);
$select = $sql->select();
$select->from('SCHEMATA');
$select->where(array('SCHEMA_NAME' => $db));
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$schema = $result->current();
if(!empty($schema)) {
$isDatabaseExists = 1;
if (!empty($schema['DEFAULT_COLLATION_NAME']) && $schema['DEFAULT_COLLATION_NAME'] === 'utf8_general_ci') {
$isDatabaseCollationNameValid = 1;
}
}
}catch(\Exception $e) {
$isPassCorrect = 0;
}
}
$results = array(
'isConnected' => $isConnected,
'isDatabaseExists' => $isDatabaseExists,
'isMysqlPasswordCorrect' => $isPassCorrect,
'isDatabaseCollationNameValid' => $isDatabaseCollationNameValid,
);
return $results;
} | php | {
"resource": ""
} |
q11616 | InstallHelperService.setDbAdapter | train | public function setDbAdapter($config)
{
if(is_array($config)) {
$this->odbAdapter = new DbAdapter(array_merge(array(
'driver' => 'Pdo_Mysql',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
)
), $config));
$config = new \Zend\Config\Config($config, true);
$writer = new \Zend\Config\Writer\PhpArray();
$conf = $writer->toString($config);
}
} | php | {
"resource": ""
} |
q11617 | InstallHelperService.executeRawQuery | train | public function executeRawQuery($query)
{
$resultSet = null;
if($this->odbAdapter) {
if(!empty($query)) {
$resultSet = $this->getDbAdapter()->query($query, DbAdapter::QUERY_MODE_EXECUTE);
}
}
return $resultSet;
} | php | {
"resource": ""
} |
q11618 | InstallHelperService.isDbTableExists | train | public function isDbTableExists($tableName)
{
$status = false;
$resultSet = array();
$query = $this->executeRawQuery("SHOW TABLES LIKE '".trim($tableName)."';");
if($resultSet)
$resultSet = $query->toArray();
if(!empty($resultSet)) {
$status = true;
}
return $status;
} | php | {
"resource": ""
} |
q11619 | InstallHelperService.importSql | train | public function importSql($path, $files = array('setup_structure.sql'))
{
$status = false;
$fImport = null;
if(file_exists($path)) {
foreach($files as $file) {
if(file_exists($path.$file)) {
$fImport = file_get_contents($path.$file);
$this->executeRawQuery($fImport);
$this->importTableName = array_merge($this->importTableName, $this->getSqlFileTables($path.$file));
}
}
}
return $status;
} | php | {
"resource": ""
} |
q11620 | InstallHelperService.getSqlFileTables | train | public function getSqlFileTables($path)
{
$tables = array();
if(file_exists($path)) {
$file = fopen($path, 'r');
$textToFind = 'CREATE TABLE IF NOT EXISTS ';
$found = array();
$tables = array();
while(!feof($file)) {
$output = fgets($file);
$pos = strrpos($output, $textToFind);
if(is_int($pos)) {
$found[] = $output;
}
}
foreach($found as $table) {
$startPos = strpos($table, '`');
$lastPos = strrpos($table, '`');
$tableName = substr($table, $startPos, $lastPos);
$tableName = preg_replace('/\(|\)/', '', $tableName);
$tables[] = trim(str_replace('`', '', $tableName));
}
}
return $tables;
} | php | {
"resource": ""
} |
q11621 | InstallHelperService.checkEnvironmentVariables | train | public function checkEnvironmentVariables()
{
$settingsValues = array();
$iniSettings = array(
'memory_limit', 'max_execution_time', 'upload_max_filesize'
);
foreach($iniSettings as $setting) {
$settingsValues[$setting] = ini_get($setting);
}
return $settingsValues;
} | php | {
"resource": ""
} |
q11622 | InstallHelperService.filePermission | train | public function filePermission($path, $mode = self::CHMOD_775)
{
$results = array();
$success = 0;
if(file_exists($path)) {
if(!is_writable($path))
chmod($path, $mode);
if(!is_readable($path))
chmod($path, $mode);
if(is_readable($path) && is_writable($path))
$status = 1;
}
$results = array(
'path' => $path,
'mode' => $mode,
'success' => $success
);
return Json::encode($results);
} | php | {
"resource": ""
} |
q11623 | InstallHelperService.replaceFile | train | public function replaceFile($old, $new, array $content)
{
$oldFileContent = file_get_contents($old);
file_put_contents($new, vsprintf($oldFileContent, $content));
unlink($old);
} | php | {
"resource": ""
} |
q11624 | MimeTypeFileExtensionGuesser.guess | train | public static function guess(string $guess): ?string
{
if (! \is_file($guess)) {
throw new FileNotFoundException($guess);
}
if (! \is_readable($guess)) {
throw new AccessDeniedException($guess);
}
return parent::guess(\pathinfo($guess, \PATHINFO_EXTENSION));
} | php | {
"resource": ""
} |
q11625 | ConfigManager.registerConfig | train | public function registerConfig(ConfigInterface $config, $id)
{
$this->configurationDefinitions[spl_object_hash($config)] = $config;
$this->configurationIds[spl_object_hash($config)] = $id;
$this->configTree->set($config->getPath(), $config);
$config->setConfigManager($this);
} | php | {
"resource": ""
} |
q11626 | ModelSearch.run | train | public function run(&$query, $model, $request)
{
$this->query = $query;
$this->getAttributes($model);
$this->parseRequest($request);
return $this->query();
} | php | {
"resource": ""
} |
q11627 | ModelSearch.query | train | private function query()
{
foreach ($this->search_models as $model_name => $filters) {
// Apply search against the original model.
if ($model_name === 'self') {
self::applySearch($this->query, $filters);
continue;
}
// Apply search against the related model.
$this->query->whereHas($model_name, function ($query) use ($filters) {
self::applySearch($query, $filters);
});
}
return $this->query;
} | php | {
"resource": ""
} |
q11628 | ModelSearch.getAttributes | train | public function getAttributes($model)
{
$this->model = $model;
$this->attributes = self::buildRelationshipAttributes($this->model);
$this->attributes = $this->attributes + self::buildAttributes($this->model);
return $this->attributes;
} | php | {
"resource": ""
} |
q11629 | ModelSearch.buildRelationshipAttributes | train | private function buildRelationshipAttributes($model)
{
$result = [];
foreach ($model->getSearchRelationships() as $method) {
if (!method_exists($model, $method)) {
continue;
}
$relation = self::getRelation($model->$method());
$this->relationships[$method] = $relation;
self::buildCastedAttributes($relation['model'], $result, $method);
self::buildSearchAttributes($relation['model'], $result, $method);
}
return $result;
} | php | {
"resource": ""
} |
q11630 | ModelSearch.buildAttributes | train | public static function buildAttributes($model)
{
$result = [];
self::buildCastedAttributes($model, $result);
self::buildSearchAttributes($model, $result);
return $result;
} | php | {
"resource": ""
} |
q11631 | ModelSearch.buildCastedAttributes | train | private static function buildCastedAttributes($model, &$result, $method = null)
{
$model_name = 'self';
$name_append = '';
if (!is_null($method)) {
$model_name = $method;
$name_append = $method.'.';
}
// ModelSchema implementation gives us better data.
if (class_exists('HnhDigital\ModelSchema\Model')
&& $model instanceof \HnhDigital\ModelSchema\Model) {
// Build attributes off the schema.
foreach ($model->getSchema() as $name => $config) {
$result[$name_append.$name] = [
'name' => $name,
'title' => Arr::get($config, 'title', $name),
'attributes' => [sprintf('%s.%s', $model->getTable(), $name)],
'filter' => self::convertCast(Arr::get($config, 'cast')),
'model' => &$model,
'model_name' => $model_name,
'source_model' => Arr::get($config, 'model'),
'source_model_key' => Arr::get($config, 'model_key', null),
'source_model_name' => Arr::get($config, 'model_name', 'display_name'),
];
}
return;
}
// Build attributes off the specified casts.
foreach ($model->getCasts() as $name => $cast) {
$result[$name_append.$name] = [
'name' => $name,
'title' => $name,
'attributes' => [sprintf('%s.%s', $model->getTable(), $name)],
'filter' => self::convertCast($cast),
'model' => &$model,
'model_name' => $model_name,
];
}
} | php | {
"resource": ""
} |
q11632 | ModelSearch.validateAttributes | train | private static function validateAttributes($model, $name, &$attributes)
{
// Should be an array.
if (!is_array($attributes)) {
$attributes = [$attributes];
}
// Is empty, use the name of the table + name.
if (empty($attributes)) {
$attributes = [sprintf('%s.%s', $model->getTable(), $name)];
}
// Check each of the attribute values.
// Convert any prepended with a curly to an expression.
foreach ($attributes as &$value) {
if (substr($value, 0, 1) === '#' || substr($value, 0, 1) === '{') {
$value = new Expression(substr($value, 1));
}
}
} | php | {
"resource": ""
} |
q11633 | ModelSearch.parseRequest | train | private function parseRequest($request)
{
if (empty($request)) {
return;
}
$this->request = $request;
// Models used in this request.
$models_used = [];
// Review each request.
foreach ($this->request as $name => $filters) {
// This name is not present in available attributes.
if (!Arr::has($this->attributes, $name)) {
continue;
}
// Get the settings for the given attribute.
$settings = Arr::get($this->attributes, $name);
// Settings is empty.
if (empty($settings)) {
continue;
}
// Check and validate each of the filters.
$filters = self::validateFilters($filters, $settings);
// Search against current model.
if (($model_name = Arr::get($settings, 'model_name')) === 'self') {
$this->search_models['self'][$name] = $filters;
continue;
}
// Search against an model via relationship.
$models_used[$model_name] = true;
$this->search_models[$model_name][$name] = $filters;
}
// Join the models to this query.
if (count($models_used)) {
$this->modelJoin($models_used);
}
} | php | {
"resource": ""
} |
q11634 | ModelSearch.validateFilters | train | private static function validateFilters($filters, $settings)
{
if (!is_array($filters)) {
$filters = [$filters];
}
// Each fitler.
foreach ($filters as $index => &$filter) {
// Check this item.
$filter = self::validateFilterItem($filter, $settings);
// Remove if invalid.
if (empty($filter)) {
unset($filters[$index]);
}
}
return $filters;
} | php | {
"resource": ""
} |
q11635 | ModelSearch.validateFilterItem | train | private static function validateFilterItem($filter, $settings)
{
// Convert string to filter array.
if (!is_array($filter)) {
$filter = ['', $filter];
}
// Convert string to filter array.
if (Arr::get($settings, 'filter') !== 'boolean' && count($filter) == 1) {
array_unshift($filter, '');
}
// Split the filter array into operator, value1, value2
$operator = Arr::get($filter, 0, '');
$value_one = Arr::get($filter, 1, false);
$value_two = Arr::get($filter, 2, false);
// The wild-all setting was enabled.
// Update value with all characters wildcarded.
if (Arr::has($settings, 'enable.wild-all')) {
self::applyWildAll($operator, $value_one);
}
self::checkInlineOperator($operator, $value_one, $settings);
self::checkNullOperator($operator, $value_one);
self::checkEmptyOperator($operator, $value_one);
// Defaullt operator.
if (empty($operator)) {
$operator = self::getDefaultOperator(Arr::get($settings, 'filter'), $operator);
}
// Return filter as an associative array.
$filter = [
'operator' => $operator,
'method' => 'where',
'arguments' => [],
'value_one' => $value_one,
'value_two' => $value_two,
'settings' => $settings,
'positive' => true,
];
// Update filter based on the filter being used.
$validation_method = 'filterBy'.Str::studly(Arr::get($settings, 'filter'));
if (method_exists(__CLASS__, $validation_method)) {
$filter = self::{$validation_method}($filter);
}
if ($filter === false) {
return $filter;
}
// Update based on operator.
$filter['positive'] = !(stripos($operator, '!') !== false || stripos($operator, 'NOT') !== false);
return $filter;
} | php | {
"resource": ""
} |
q11636 | ModelSearch.applyWildAll | train | private static function applyWildAll(&$operator, &$value)
{
$positive = !(stripos($operator, '!') !== false || stripos($operator, 'NOT') !== false);
$operator = $positive ? '*=*' : '*!=*';
$value_array = str_split(str_replace(' ', '', $value));
$value = implode('%', $value_array);
} | php | {
"resource": ""
} |
q11637 | ModelSearch.parseInlineOperator | train | public static function parseInlineOperator($text)
{
$operator_name = 'contains';
$operator = Arr::get($text, 0, '');
$value = Arr::get($text, 1, false);
self::checkInlineOperator($operator, $value);
if (!empty($operator)) {
$operator_name = Arr::get(self::getOperator('string', $operator), 'inline', 'contains');
}
return [
$operator_name,
$operator,
$value,
];
} | php | {
"resource": ""
} |
q11638 | ModelSearch.checkInlineOperator | train | private static function checkInlineOperator(&$operator, &$value, $settings = [])
{
if (is_array($value)) {
return;
}
// Boolean does not provide inline operations.
if (Arr::get($settings, 'filter') === 'boolean') {
return;
}
$value_array = explode(' ', trim($value), 2);
if (count($value_array) == 1) {
return;
}
$check_operator = array_shift($value_array);
if (self::checkOperator(Arr::get($settings, 'filter', 'string'), $check_operator)) {
$operator = $check_operator;
$value = array_shift($value_array);
}
} | php | {
"resource": ""
} |
q11639 | ModelSearch.filterByUuid | train | public static function filterByUuid($filter)
{
$operator = Arr::get($filter, 'operator');
$method = Arr::get($filter, 'method');
$arguments = Arr::get($filter, 'arguments');
$value_one = Arr::get($filter, 'value_one');
$value_two = Arr::get($filter, 'value_two');
$settings = Arr::get($filter, 'settings');
$positive = Arr::get($filter, 'positive');
switch ($operator) {
case 'IN':
$method = 'whereIn';
$arguments = [static::getListFromString($value_one)];
break;
case 'NOT_IN':
$method = 'whereNotIn';
$arguments = [static::getListFromString($value_one)];
break;
case 'NULL':
$method = 'whereNull';
break;
case 'NOT_NULL':
$method = 'whereNotNull';
break;
}
return [
'operator' => $operator,
'method' => $method,
'arguments' => $arguments,
'value_one' => $value_one,
'value_two' => $value_two,
'settings' => $settings,
'positive' => $positive,
];
} | php | {
"resource": ""
} |
q11640 | ModelSearch.filterByString | train | public static function filterByString($filter)
{
$operator = Arr::get($filter, 'operator');
$method = Arr::get($filter, 'method');
$arguments = Arr::get($filter, 'arguments');
$value_one = Arr::get($filter, 'value_one');
$value_two = Arr::get($filter, 'value_two');
$settings = Arr::get($filter, 'settings');
$positive = Arr::get($filter, 'positive');
switch ($operator) {
case '=':
case '!=':
$arguments = [$operator, $value_one];
break;
case '*=*':
case '*!=*':
$operator = (stripos($operator, '!') !== false) ? 'not ' : '';
$operator .= 'like';
$arguments = [$operator, '%'.$value_one.'%'];
break;
case '*=':
case '*!=':
$operator = (stripos($operator, '!') !== false) ? 'not ' : '';
$operator .= 'like';
$arguments = [$operator, '%'.$value_one];
break;
case '=*':
case '!=*':
$operator = (stripos($operator, '!') !== false) ? 'not ' : '';
$operator .= 'like';
$arguments = [$operator, $value_one.'%'];
break;
case 'EMPTY':
$method = 'whereRaw';
$arguments = "%s = ''";
break;
case 'NOT_EMPTY':
$method = 'whereRaw';
$arguments = "%s != ''";
break;
case 'IN':
$method = 'whereIn';
$arguments = [static::getListFromString($value_one)];
break;
case 'NOT_IN':
$method = 'whereNotIn';
$arguments = [static::getListFromString($value_one)];
break;
case 'NULL':
$method = 'whereNull';
break;
case 'NOT_NULL':
$method = 'whereNotNull';
break;
}
return [
'operator' => $operator,
'method' => $method,
'arguments' => $arguments,
'value_one' => $value_one,
'value_two' => $value_two,
'settings' => $settings,
'positive' => $positive,
];
} | php | {
"resource": ""
} |
q11641 | ModelSearch.filterByScope | train | public static function filterByScope($filter)
{
$operator = Arr::get($filter, 'operator');
$method = Arr::get($filter, 'method');
$source = Arr::get($filter, 'settings.source');
$arguments = Arr::get($filter, 'arguments');
$value_one = Arr::get($filter, 'value_one');
$value_two = Arr::get($filter, 'value_two');
$settings = Arr::get($filter, 'settings');
$positive = Arr::get($filter, 'positive');
if (Arr::has($filter, 'settings.source')) {
$model = Arr::get($filter, 'settings.model');
$method_transform = 'transform'.Str::studly($source).'Value';
if (method_exists($model, $method_transform)) {
$value_one = $model->$method_transform($value_one);
}
$method_lookup = 'scope'.Str::studly($source);
if (!method_exists($model, $method_lookup)) {
return false;
}
$method = Str::camel($source);
$arguments = [$value_one];
}
return [
'operator' => $operator,
'method' => $method,
'arguments' => $arguments,
'value_one' => $value_one,
'value_two' => $value_two,
'settings' => $settings,
'positive' => $positive,
];
} | php | {
"resource": ""
} |
q11642 | ModelSearch.modelJoin | train | public function modelJoin($relationships, $operator = '=', $type = 'left', $where = false)
{
if (!is_array($relationships)) {
$relationships = [$relationships];
}
if (empty($this->query->columns)) {
$this->query->selectRaw('DISTINCT '.$this->model->getTable().'.*');
}
foreach ($relationships as $relation_name => $load_relationship) {
// Required variables.
$model = Arr::get($this->relationships, $relation_name.'.model');
$method = Arr::get($this->relationships, $relation_name.'.method');
$table = Arr::get($this->relationships, $relation_name.'.table');
$parent_key = Arr::get($this->relationships, $relation_name.'.parent_key');
$foreign_key = Arr::get($this->relationships, $relation_name.'.foreign_key');
// Add the columns from the other table.
// @todo do we need this?
//$this->query->addSelect(new Expression("`$table`.*"));
$this->query->join($table, $parent_key, $operator, $foreign_key, $type, $where);
// The join above is to the intimidatory table. This joins the query to the actual model.
if ($method === 'BelongsToMany') {
$related_foreign_key = $model->getQualifiedRelatedKeyName();
$related_relation = $model->getRelated();
$related_table = $related_relation->getTable();
$related_qualified_key_name = $related_relation->getQualifiedKeyName();
$this->query->join($related_table, $related_qualified_key_name, $operator, $related_foreign_key, $type, $where);
}
}
// Group by the original model.
$this->query->groupBy($this->model->getQualifiedKeyName());
} | php | {
"resource": ""
} |
q11643 | ModelSearch.applySearch | train | private static function applySearch(&$query, $search)
{
foreach ($search as $name => $filters) {
foreach ($filters as $filter) {
self::applySearchFilter($query, $filter);
}
}
} | php | {
"resource": ""
} |
q11644 | ModelSearch.applySearchFilter | train | private static function applySearchFilter(&$query, $filter)
{
$filter_type = Arr::get($filter, 'settings.filter');
$method = Arr::get($filter, 'method');
$arguments = Arr::get($filter, 'arguments');
$attributes = Arr::get($filter, 'settings.attributes');
$positive = Arr::get($filter, 'positive');
if ($filter_type !== 'scope' && is_array($arguments)) {
array_unshift($arguments, '');
}
$query->where(function ($query) use ($filter_type, $attributes, $method, $arguments, $positive) {
$count = 0;
foreach ($attributes as $attribute_name) {
// Place attribute name into argument.
if ($filter_type !== 'scope' && is_array($arguments)) {
$arguments[0] = $attribute_name;
// Argument is raw and using sprintf.
} elseif (!is_array($arguments)) {
$arguments = [sprintf($arguments, self::quoteIdentifier($attribute_name))];
}
if ($filter_type === 'scope') {
$arguments[] = $positive;
}
$query->$method(...$arguments);
// Apply an or to the where.
if ($filter_type !== 'scope' && $count === 0 && $positive) {
$method = 'or'.Str::studly($method);
}
$count++;
}
});
} | php | {
"resource": ""
} |
q11645 | ModelSearch.getOperator | train | public static function getOperator($type, $operator)
{
$operators = self::getOperators($type);
return Arr::get($operators, $operator, []);
} | php | {
"resource": ""
} |
q11646 | ModelSearch.getOperators | train | public static function getOperators($type)
{
if (!in_array($type, self::getTypes())) {
return [];
}
$source = snake_case($type).'_operators';
return self::$$source;
} | php | {
"resource": ""
} |
q11647 | ModelSearch.getListFromString | train | private static function getListFromString($value)
{
if (is_string($value_array = $value)) {
$value = str_replace([',', ' '], ';', $value);
$value_array = explode(';', $value);
}
if (is_array($value_array)) {
return array_filter(array_map('trim', $value_array));
}
return [];
} | php | {
"resource": ""
} |
q11648 | Smarty_Internal_Template.compileTemplateSource | train | public function compileTemplateSource()
{
if (!$this->source->recompiled) {
$this->properties['file_dependency'] = array();
if ($this->source->components) {
// for the extends resource the compiler will fill it
// uses real resource for file dependency
// $source = end($this->source->components);
// $this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $source->type);
} else {
$this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $this->source->type);
}
}
// compile locking
if ($this->smarty->compile_locking && !$this->source->recompiled) {
if ($saved_timestamp = $this->compiled->timestamp) {
touch($this->compiled->filepath);
}
}
// call compiler
try {
$code = $this->compiler->compileTemplate($this);
}
catch (Exception $e) {
// restore old timestamp in case of error
if ($this->smarty->compile_locking && !$this->source->recompiled && $saved_timestamp) {
touch($this->compiled->filepath, $saved_timestamp);
}
throw $e;
}
// compiling succeded
if (!$this->source->recompiled && $this->compiler->write_compiled_code) {
// write compiled template
$_filepath = $this->compiled->filepath;
if ($_filepath === false) {
throw new SmartyException('getCompiledFilepath() did not return a destination to save the compiled template to');
}
Smarty_Internal_Write_File::writeFile($_filepath, $code, $this->smarty);
$this->compiled->exists = true;
$this->compiled->isCompiled = true;
}
// release compiler object to free memory
unset($this->compiler);
} | php | {
"resource": ""
} |
q11649 | Smarty_Internal_Template.getSubTemplate | train | public function getSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope)
{
// already in template cache?
if ($this->smarty->allow_ambiguous_resources) {
$_templateId = Smarty_Resource::getUniqueTemplateName($this, $template) . $cache_id . $compile_id;
} else {
$_templateId = $this->smarty->joined_template_dir . '#' . $template . $cache_id . $compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
if (isset($this->smarty->template_objects[$_templateId])) {
// clone cached template object because of possible recursive call
$tpl = clone $this->smarty->template_objects[$_templateId];
$tpl->parent = $this;
$tpl->caching = $caching;
$tpl->cache_lifetime = $cache_lifetime;
} else {
$tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime);
}
// get variables from calling scope
if ($parent_scope == Smarty::SCOPE_LOCAL) {
$tpl->tpl_vars = $this->tpl_vars;
$tpl->tpl_vars['smarty'] = clone $this->tpl_vars['smarty'];
} elseif ($parent_scope == Smarty::SCOPE_PARENT) {
$tpl->tpl_vars = & $this->tpl_vars;
} elseif ($parent_scope == Smarty::SCOPE_GLOBAL) {
$tpl->tpl_vars = & Smarty::$global_tpl_vars;
} elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) {
$tpl->tpl_vars = & $this->tpl_vars;
} else {
$tpl->tpl_vars = & $scope_ptr->tpl_vars;
}
$tpl->config_vars = $this->config_vars;
if (!empty($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[$_key] = new Smarty_variable($_val);
}
}
/// dark edit
\Dark\SmartyView\SmartyEngine::integrateViewComposers($tpl, $template);
/// end edit
return $tpl->fetch(null, null, null, null, false, false, true);
} | php | {
"resource": ""
} |
q11650 | ServerRequestFactory.createServerRequestFromArray | train | public function createServerRequestFromArray(?array $server)
{
global $app;
# Copied from Guzzles ::fromGlobals(), but we need to support the $server array as
# paramter, so we use that instead of the $_SERVER array guzzle uses by default
$method = isset($server['REQUEST_METHOD']) ? $server['REQUEST_METHOD'] : 'GET';
$headers = \function_exists('getallheaders') ? \getallheaders() : [];
$uri = ServerRequest::getUriFromGlobals();
$body = new LazyOpenStream('php://input', 'r+');
$protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
$serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $server);
\logger()->debug('Created PSR-7 ServerRequest("'.$method.'","'.$uri.'") from array (Guzzle)');
return $serverRequest
->withCookieParams($_COOKIE)
->withQueryParams($_GET)
->withParsedBody($_POST)
->withUploadedFiles(ServerRequest::normalizeFiles($_FILES));
} | php | {
"resource": ""
} |
q11651 | Kohana_PayPal.payment | train | public static function payment($amount, $localTrxID = null) {
$impl = new PayPal();
$registration = $impl->registerTransaction($amount, $impl->storeLocalTrx($localTrxID));
Session::instance()->set(self::SESSION_TOKEN, $registration->id);
foreach ($registration->links as $link) {
if ($link->rel == 'approval_url') {
HTTP::redirect($link->href);
exit; // shouldn't be needed, redirect throws
}
}
throw new PayPal_Exception_InvalidResponse('Missing approval URL');
} | php | {
"resource": ""
} |
q11652 | Kohana_PayPal.registerTransaction | train | public function registerTransaction($amount, $localTrxID) {
$token = $this->authenticate();
// paypal like the amount as string, to prevent floating point errors
if (!is_string($amount))
$amount = sprintf("%0.2f", $amount);
$a = (object)[
"amount" => (object)[
"total" => $amount,
"currency" => $this->currency,
]
];
$route = Route::get('paypal_response');
$base = URL::base(true);
$payment_data = (object)[
'intent' => "sale",
'redirect_urls' => (object)[
'return_url' => $base . $route->uri([
'action' => 'complete', 'trxid' => $localTrxID]),
'cancel_url' => $base . $route->uri([
'action' => 'cancel', 'trxid' => $localTrxID]),
],
'payer' => (object)[ 'payment_method' => 'paypal', ],
"transactions" => [ $a ],
];
$request = $this->genRequest('payments/payment', $payment_data, $token);
return $this->call($request);
} | php | {
"resource": ""
} |
q11653 | Kohana_PayPal.storeLocalTrx | train | private function storeLocalTrx($localTrxID) {
if (is_null($localTrxID))
return $localTrxID;
$trxco = sha1(time() . "" . serialize($localTrxID));
$this->cache->set($trxco, $localTrxID, self::MAX_SESSION_LENGTH);
return $trxco;
} | php | {
"resource": ""
} |
q11654 | Kohana_PayPal.retrieveLocalTrx | train | private function retrieveLocalTrx($localTrxHash) {
if (is_null($localTrxHash))
return $localTrxHash;
$trxid = $this->cache->get($localTrxHash, false);
if ($trxid === false)
throw new Exception("Failed to retrieve local data for " . $localTrxHash);
return $trxid;
} | php | {
"resource": ""
} |
q11655 | Kohana_PayPal.extractSales | train | private function extractSales($transactions) {
$out = [];
foreach ($transactions as $trx) {
foreach ($trx->related_resources as $src) {
if (isset($src->sale)) {
$out[] = $src->sale;
}
}
}
return $out;
} | php | {
"resource": ""
} |
q11656 | Kohana_PayPal.getRefundURL | train | private function getRefundURL($paymentDetails) {
if (!is_object($paymentDetails))
throw new Exception("Invalid payment details in getRefundURL");
if (!is_array($paymentDetails->transactions))
throw new Exception("Invalid transaction list in getRefundURL");
foreach ($paymentDetails->transactions as $transact) {
if (!is_array($transact->related_resources))
throw new Exception("Invalid related resources in getRefundURL");
foreach ($transact->related_resources as $res) {
if (!is_array($res->sale->links))
throw new Exception("Invalid related links in getRefundURL");
foreach ($res->sale->links as $link) {
if ($link->rel == 'refund')
return $link->href;
}
}
}
throw new Exception("Missing refund URL in getRefundURL");
} | php | {
"resource": ""
} |
q11657 | Kohana_PayPal.genRequest | train | protected function genRequest($address, $data = [], $token = null, $get = false) {
// compose request URL
if (strstr($address, 'https://'))
$url = $address;
else
$url = $this->endpoint . '/v1/' . $address;
$method = (is_null($data) || $get) ? 'GET' : 'POST';
self::debug("PayPal Auth: " . $token->token_type . ' ' . $token->access_token);
// create HTTP request
$req = (new Request($url))->method($method)
->headers('Accept','application/json')
->headers('Accept-Language', 'en_US')
->headers('Authorization', is_null($token) ?
'Basic ' . base64_encode($this->clientID . ":" . $this->secret) :
$token->token_type . ' ' . $token->access_token)
->headers('Content-Type', (is_array($data) && $method == 'POST') ?
'application/x-www-form-urlencoded' : 'application/json');
if (is_null($data)) {
self::debug("Sending message to $url");
return $req;
}
if (is_array($data)) {
$req = $req->post($data); // set all fields directly
self::debug("Sending POST message to $url :", $data);
return $req;
}
if (!is_object($data))
throw new PayPal_Exception("Invalid data type in PayPal::genRequest");
$data = json_encode($data);
$req = $req->body($data);
self::debug("Sending JSON message to $url : $data");
return $req;
} | php | {
"resource": ""
} |
q11658 | Kohana_PayPal.call | train | protected function call(Request $request) {
$response = $request->execute();
if (!$response->isSuccess()) {
self::debug("Error in PayPal call", $response);
throw new PayPal_Exception_InvalidResponse("Error " . $response->status() . " in PayPal call (". $response->body() .")");
}
$res = json_decode($response->body());
if (isset($res->error)) {
self::error("Error in PayPal call: " . print_r($res, true));
throw new PayPal_Exception_InvalidResponse('PayPal: ' . $res->error_description . ' [' . $res->error .
'] while calling ' . $request->uri());
}
return $res;
} | php | {
"resource": ""
} |
q11659 | ImageExtension.getBase64 | train | public function getBase64()
{
if ($this->owner->exists()) {
$file = $this->owner->getFullPath();
$mime = mime_content_type($file);
$fileContent = file_get_contents($file);
return "data://$mime;base64," . base64_encode($fileContent);
}
return null;
} | php | {
"resource": ""
} |
q11660 | Template_Part.set_var | train | public function set_var( $key, $value ) {
if ( null === $this->wp_query->get( $key, null ) ) {
$this->vars[ $key ] = $value;
$this->wp_query->set( $key, $value );
}
} | php | {
"resource": ""
} |
q11661 | Template_Part.render | train | public function render() {
$html = '';
ob_start();
if ( $this->_is_root_template() ) {
$this->_root_get_template_part();
} else {
get_template_part( $this->slug, $this->name );
}
$html = ob_get_clean();
// @codingStandardsIgnoreStart
echo apply_filters( 'inc2734_view_controller_template_part_render', $html, $this->slug, $this->name, $this->vars );
// @codingStandardsIgnoreEnd
foreach ( $this->vars as $key => $value ) {
unset( $value );
$this->wp_query->set( $key, null );
}
} | php | {
"resource": ""
} |
q11662 | Template_Part._is_root_template | train | protected function _is_root_template() {
$hierarchy = [];
/**
* @deprecated
*/
$root = apply_filters(
'inc2734_view_controller_template_part_root',
'',
$this->slug,
$this->name,
$this->vars
);
if ( $root ) {
$hierarchy[] = $root;
}
$hierarchy = apply_filters(
'inc2734_view_controller_template_part_root_hierarchy',
$hierarchy,
$this->slug,
$this->name,
$this->vars
);
$hierarchy = array_unique( $hierarchy );
foreach ( $hierarchy as $root ) {
$is_root = $this->_is_root( $root );
if ( $is_root ) {
return $is_root;
}
}
return false;
} | php | {
"resource": ""
} |
q11663 | Template_Part._is_root | train | protected function _is_root( $root ) {
$this->root = $root;
$is_root = (bool) $this->_root_locate_template();
if ( ! $is_root ) {
$this->root = '';
}
return $is_root;
} | php | {
"resource": ""
} |
q11664 | Template_Part._get_root_template_part_slugs | train | protected function _get_root_template_part_slugs() {
if ( ! $this->root ) {
return [];
}
if ( $this->name ) {
$templates[] = trailingslashit( $this->root ) . $this->slug . '-' . $this->name . '.php';
}
$templates[] = trailingslashit( $this->root ) . $this->slug . '.php';
return $templates;
} | php | {
"resource": ""
} |
q11665 | DataCollection.getData | train | public function getData($page)
{
$this->loadData();
$start = ($page - 1) * $this->pageSize;
return array_slice($this->filteredData, $start, $this->pageSize);
} | php | {
"resource": ""
} |
q11666 | DataCollection.getLastPageNumber | train | public function getLastPageNumber()
{
$this->loadData();
$count = count($this->filteredData);
return ceil($count / $this->pageSize);
} | php | {
"resource": ""
} |
q11667 | DataCollection.setFiltersAndSort | train | public function setFiltersAndSort($filters, $sortField = null, $sortOrder = "ASC")
{
$this->reset();
$this->filters = $filters;
if ($sortField && $sortOrder) {
$this->sort = [$sortField, $sortOrder];
}
return $this;
} | php | {
"resource": ""
} |
q11668 | DataCollection.setDataByIndex | train | public function setDataByIndex($line, $data)
{
$this->data[$line] = $data;
$this->filteredData = null;
} | php | {
"resource": ""
} |
q11669 | DataCollection.reset | train | public function reset()
{
$this->filteredData = null;
$this->filters = [];
$this->sort = null;
return $this;
} | php | {
"resource": ""
} |
q11670 | DataCollection.loadData | train | protected function loadData()
{
if (is_null($this->filteredData)) {
$this->filteredData = $this->filterHelper->filterData(
$this->data,
$this->filters,
FilterInterface::FILTER_LOGIC_OR
);
if (!is_null($this->sort)) {
$sort = $this->sort;
uasort($this->filteredData, function ($a, $b) use ($sort) {
if (is_numeric($a[$sort[0]])) {
$comp = ($a[$sort[0]] < $b[$sort[0]]) ? -1 : 1;
} else {
$comp = (strcmp($a[$sort[0]], $b[$sort[0]]));
}
if ($sort[1] == "DESC") {
return -1 * $comp;
} else {
return $comp;
}
});
}
}
} | php | {
"resource": ""
} |
q11671 | DataProviderManager.isProviderCompatible | train | public function isProviderCompatible($provider, $title, $mode, $script, Map $map)
{
return !is_null($this->getCompatibleProviderId($provider, $title, $mode, $script, $map));
} | php | {
"resource": ""
} |
q11672 | DataProviderManager.registerPlugin | train | public function registerPlugin($provider, $pluginId, $title, $mode, $script, Map $map)
{
$providerId = $this->getCompatibleProviderId($provider, $title, $mode, $script, $map);
if (empty($providerId)) {
return;
}
/** @var AbstractDataProvider $providerService */
$providerService = $this->container->get($providerId);
$pluginService = $this->container->get($pluginId);
$interface = $this->providerInterfaces[$provider];
if ($pluginService instanceof $interface) {
$this->deletePlugin($provider, $pluginId);
$providerService->registerPlugin($pluginId, $pluginService);
} else {
throw new UncompatibleException("Plugin $pluginId isn't compatible with $provider. Should be instance of $interface");
}
$this->logger->info("Plugin '$pluginId' will use data provider '$provider' : '$providerId'");
} | php | {
"resource": ""
} |
q11673 | DataProviderManager.deletePlugin | train | public function deletePlugin($provider, $pluginId)
{
foreach ($this->providersByCompatibility[$provider] as $titleProviders) {
foreach ($titleProviders as $modeProviders) {
foreach ($modeProviders as $providerId) {
$providerService = $this->container->get($providerId);
$providerService->deletePlugin($pluginId);
}
}
}
} | php | {
"resource": ""
} |
q11674 | DataProviderManager.dispatch | train | public function dispatch($eventName, $params)
{
if (isset($this->enabledProviderListeners[$eventName])) {
foreach ($this->enabledProviderListeners[$eventName] as $callback) {
call_user_func_array($callback, $params);
}
}
} | php | {
"resource": ""
} |
q11675 | Service.makeBoletoAsHTML | train | public function makeBoletoAsHTML($codigoBanco, $boleto)
{
$boleto = new Boleto($boleto);
$factory = new BoletoFactory($this->config);
return $factory->makeBoletoAsHTML($codigoBanco, $boleto->toArray());
} | php | {
"resource": ""
} |
q11676 | CountryIpv4.ipv4For | train | protected function ipv4For($country)
{
$country = self::toUpper($country);
if (!isset(self::$ipv4Ranges[$country])) {
return '';
}
return static::randomElement(self::$ipv4Ranges[$country]) . mt_rand(1, 254);
} | php | {
"resource": ""
} |
q11677 | Smarty_CacheResource_Memcache.delete | train | protected function delete(array $keys)
{
foreach ($keys as $k) {
$k = sha1($k);
$this->memcache->delete($k);
}
return true;
} | php | {
"resource": ""
} |
q11678 | Module.initSession | train | public function initSession()
{
$sessionManager = new SessionManager();
$sessionManager->start();
Container::setDefaultManager($sessionManager);
$container = new Container('melisinstaller');
} | php | {
"resource": ""
} |
q11679 | FormField.getEditable | train | public function getEditable($is_create = true)
{
return
(
$this->getParent()->getEditable() ||
$this->getParent()->getRequired()
) &&
! $this->getField()->getCalculated() &&
! $this->getField()->getAutoNumber() &&
(
$is_create && $this->getField()->getCreateable() ||
! $is_create && $this->getField()->getUpdateable()
)
;
} | php | {
"resource": ""
} |
q11680 | LayoutScrollable.forceContainerSize | train | public function forceContainerSize($x, $y)
{
$this->force = true;
$this->_X = $x;
$this->_Y = $y;
} | php | {
"resource": ""
} |
q11681 | CheckoutSteps.nextStep | train | public static function nextStep($step)
{
$steps = self::getSteps();
$key = self::getStepIndex($step) + 1;
if (key_exists($key, $steps)) {
return $steps[$key];
} else {
return null;
}
} | php | {
"resource": ""
} |
q11682 | CheckoutSteps.get | train | public static function get(CheckoutStepController $controller)
{
$list = new ArrayList();
$steps = self::getSteps();
foreach ($steps as $step) {
$data = new ViewableData();
$data->Link = $controller->Link($step);
$data->Title = _t("CheckoutSteps.$step", ucfirst($step));
$data->InPast = self::inPast($step, $controller);
$data->InFuture = self::inFuture($step, $controller);
$data->Current = self::current($step, $controller);
$list->add($data);
}
return $list;
} | php | {
"resource": ""
} |
q11683 | CheckoutSteps.inPast | train | private static function inPast($step, CheckoutStepController $controller)
{
$currentStep = $controller->getURLParams()['Action'];
return self::getStepIndex($step) < self::getStepIndex($currentStep);
} | php | {
"resource": ""
} |
q11684 | CheckoutSteps.inFuture | train | private static function inFuture($step, CheckoutStepController $controller)
{
$currentStep = $controller->getURLParams()['Action'];
return self::getStepIndex($step) > self::getStepIndex($currentStep);
} | php | {
"resource": ""
} |
q11685 | CheckoutSteps.current | train | private static function current($step, CheckoutStepController $controller)
{
$currentStep = $controller->getURLParams()['Action'];
return self::getStepIndex($step) === self::getStepIndex($currentStep);
} | php | {
"resource": ""
} |
q11686 | ScriptMapDataProvider.dispatchMapEvent | train | protected function dispatchMapEvent($eventName, $params)
{
$map = $this->mapStorage->getMap($params['map']['uid']);
$this->dispatch(
$eventName,
[
$params['count'],
isset($params['time']) ? $params['time'] : time(),
isset($params['restarted']) ? $params['restarted'] : false,
$map,
]
);
} | php | {
"resource": ""
} |
q11687 | MapratingTableMap.doDelete | train | public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(MapratingTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \eXpansion\Bundle\LocalMapRatings\Model\Maprating) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(MapratingTableMap::DATABASE_NAME);
$criteria->add(MapratingTableMap::COL_ID, (array) $values, Criteria::IN);
}
$query = MapratingQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) {
MapratingTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) {
MapratingTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
} | php | {
"resource": ""
} |
q11688 | UserProfile.formUserInfo | train | protected function formUserInfo()
{
$form = new XmlFormCollection($this->_context, $this->_url, $this->_myWords->Value("UPDATETITLE"));
$this->_paragraph->addXmlnukeObject($form);
$hidden = new XmlInputHidden("action", "update");
$form->addXmlnukeObject($hidden);
$labelField = new XmlInputLabelField($this->_myWords->Value("LABEL_LOGIN"), $this->_user->getField($this->_users->getUserTable()->username));
$form->addXmlnukeObject($labelField);
$textBox = new XmlInputTextBox($this->_myWords->Value("LABEL_NAME"), "name",$this->_user->getField($this->_users->getUserTable()->name));
$form->addXmlnukeObject($textBox);
$textBox = new XmlInputTextBox($this->_myWords->Value("LABEL_EMAIL"), "email", $this->_user->getField($this->_users->getUserTable()->email));
$form->addXmlnukeObject($textBox);
$button = new XmlInputButtons();
$button->addSubmit($this->_myWords->Value("TXT_UPDATE"),"");
$form->addXmlnukeObject($button);
} | php | {
"resource": ""
} |
q11689 | UserProfile.formPasswordInfo | train | protected function formPasswordInfo()
{
$form = new XmlFormCollection($this->_context, $this->_url, $this->_myWords->Value("CHANGEPASSTITLE"));
$this->_paragraph->addXmlnukeObject($form);
$hidden = new XmlInputHidden("action", "changepassword");
$form->addXmlnukeObject($hidden);
$textbox = new XmlInputTextBox($this->_myWords->Value("CHANGEPASSOLDPASS"), "oldpassword","");
$textbox->setInputTextBoxType(InputTextBoxType::PASSWORD );
$form->addXmlnukeObject($textbox);
$textbox = new XmlInputTextBox($this->_myWords->Value("CHANGEPASSNEWPASS"), "newpassword","");
$textbox->setInputTextBoxType(InputTextBoxType::PASSWORD );
$form->addXmlnukeObject($textbox);
$textbox = new XmlInputTextBox($this->_myWords->Value("CHANGEPASSNEWPASS2"), "newpassword2","");
$textbox->setInputTextBoxType(InputTextBoxType::PASSWORD );
$form->addXmlnukeObject($textbox);
$button = new XmlInputButtons();
$button->addSubmit($this->_myWords->Value("TXT_CHANGE"),"");
$form->addXmlnukeObject($button);
} | php | {
"resource": ""
} |
q11690 | UserProfile.formRolesInfo | train | protected function formRolesInfo()
{
$form = new XmlFormCollection($this->_context, $this->_url, $this->_myWords->Value("OTHERTITLE"));
$this->_paragraph->addXmlnukeObject($form);
$easyList = new XmlEasyList(EasyListType::SELECTLIST , "", $this->_myWords->Value("OTHERROLE"), $this->_users->returnUserProperty($this->_context->authenticatedUserId(), UserProperty::Role));
$form->addXmlnukeObject($easyList);
} | php | {
"resource": ""
} |
q11691 | ReservationController.ReservationForm | train | public function ReservationForm()
{
$reservationForm = new ReservationForm($this, 'ReservationForm', ReservationSession::get());
$reservationForm->setNextStep(CheckoutSteps::nextStep($this->step));
return $reservationForm;
} | php | {
"resource": ""
} |
q11692 | UUID.generate | train | public static function generate(): string
{
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
\mt_rand( 0, 0xffff ), \mt_rand( 0, 0xffff ),
// 16 bits for "time_mid"
\mt_rand( 0, 0xffff ),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
\mt_rand( 0, 0x0fff ) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
\mt_rand( 0, 0x3fff ) | 0x8000,
// 48 bits for "node"
\mt_rand( 0, 0xffff ), \mt_rand( 0, 0xffff ), \mt_rand( 0, 0xffff )
);
} | php | {
"resource": ""
} |
q11693 | Tokenizer.setInput | train | public function setInput($input)
{
$this->input = $input;
$this->pos = 0;
$this->line = 0;
$this->linePos = 0;
$this->tokenType = TokenType::BOF;
$this->tokenValue = null;
$this->length = strlen($this->input);
} | php | {
"resource": ""
} |
q11694 | Tokenizer.nextChar | train | private function nextChar()
{
if( ! $this->isEOF())
{
$this->linePos ++;
return $this->input[$this->pos++];
}
return null;
} | php | {
"resource": ""
} |
q11695 | Environments.init | train | public static function init()
{
$instance = self::getInstance();
$instance->_environments = $instance->_loadEnvironment($instance->_envPath . DS . 'config.php');
if (!isset($instance->_environments['local'])) {
$instance->_environments['local'] = [];
}
$instance->_current = $instance->_getEnvironment();
if ($instance->_current !== null && isset($instance->_environments[$instance->_current])) {
$instance->_loadEnvironment($instance->_envPath . DS . 'environment.' . $instance->_current . '.php');
}
} | php | {
"resource": ""
} |
q11696 | Environments._loadEnvironment | train | protected function _loadEnvironment($envFilePath)
{
if (file_exists($envFilePath)) {
include $envFilePath;
// $configure has to be defined in the included environment file.
if (isset($configure) && is_array($configure) && !empty($configure)) {
$config = Hash::merge(Configure::read(), Hash::expand($configure));
Configure::write($config);
}
if (isset($availableEnvironments) && empty($this->_environments)) {
return $availableEnvironments;
}
}
return [];
} | php | {
"resource": ""
} |
q11697 | Environments._getEnvironment | train | protected function _getEnvironment()
{
$environment = self::$forceEnvironment;
// Check if the environment has been manually set (forced).
if ($environment !== null) {
if (!isset($this->_environments[$environment])) {
throw new Exception('Environment configuration for "' . $environment . '" could not be found.');
}
}
// If no manual setting is available, use "host:port" to decide which config to use.
if ($environment === null && !empty($_SERVER['HTTP_HOST'])) {
$host = (string)$_SERVER['HTTP_HOST'];
foreach ($this->_environments as $env => $envConfig) {
if (isset($envConfig['domain']) && in_array($host, $envConfig['domain'])) {
$environment = $env;
break;
}
}
}
// If there is no host:port match, try "host" only.
if ($environment === null && !empty($_SERVER['SERVER_NAME'])) {
$host = (string)$_SERVER['SERVER_NAME'];
foreach ($this->_environments as $env => $envConfig) {
if (isset($envConfig['domain']) && in_array($host, $envConfig['domain'])) {
$environment = $env;
break;
}
}
}
// If no host matched then try to use the APP path.
if ($environment === null && ($serverPath = $this->_getRealAppPath())) {
foreach ($this->_environments as $env => $envConfig) {
if (isset($envConfig['path']) && in_array($serverPath, $envConfig['path'])) {
$environment = $env;
break;
}
}
}
// No environment could be identified -> we are on a dev machine.
if (!$environment) {
$environment = 'local';
}
return $environment;
} | php | {
"resource": ""
} |
q11698 | Environments._getRealAppPath | train | protected function _getRealAppPath()
{
$path = realpath(APP);
if (substr($path, -1, 1) !== DS) {
$path .= DS;
}
return $path;
} | php | {
"resource": ""
} |
q11699 | CryptBehavior.initialize | train | public function initialize(array $config)
{
$config += $this->_defaultConfig;
$this->config('fields', $this->_resolveFields($config['fields']));
$this->config('strategy', $this->_resolveStrategy($config['strategy']));
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.