_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q265100 | MetaObject.prefixPackage | test | protected function prefixPackage($name)
{
// no package prefix as package.object, add it
if ($name && !strpos($name, ".") && ($this->package)) {
$name = $this->package . "." . $name;
}
return $name;
} | php | {
"resource": ""
} |
q265101 | MetaObject.allowAccess | test | public function allowAccess($access = null)
{
if (CLI) {
return OPENBIZ_ALLOW;
}
if (!$access) {
$access = $this->access;
}
if ($access) {
return Openbizx::$app->allowUserAccess($access);
}
return OPENBIZ_ALLOW;
} | php | {
"resource": ""
} |
q265102 | PhpRedisDriverFactory.build | test | private function build($container):PhpRedisDriver
{
/* @var $options BernardOptions */
$options = $container->get(BernardOptions::class);
/* @var $instance Redis */
$instance = $container->get($options->getRedisInstanceKey());
return new PhpRedisDriver($instance);
} | php | {
"resource": ""
} |
q265103 | IdiormTrait.getModel | test | public function getModel($table, $connection = null)
{
if (!$connection) {
return $this['idiorm.db']->for_table($table);
} else {
return $this['idiorm.dbs'][$connection]->for_table($table);
}
} | php | {
"resource": ""
} |
q265104 | Resolver.addResolverType | test | public function addResolverType(string $type, string $path, string $extension = "", SubResolver $instance = null)
{
// Check argument validity
if (isset($this->resolvers[$type]))
throw new \LogicException("Duplicate resolver type: " . $type);
if ($instance !== null && $extension !== "")
throw new \LogicException("Cannot set a file extension for a provided instance");
// Instantiate a new resolver when none has been passed
if ($instance === null)
$instance = new SubResolver($type, $extension);
$this->resolvers[$type] = [
'path' => $path,
'resolver' => $instance
];
if ($this->cache)
$this->resolvers[$type]['resolver']->setCache($this->cache);
// Register found modules with the new resolver
foreach ($this->modules as $name => $module_path)
if (is_dir($module_path . DIRECTORY_SEPARATOR . $path))
$instance->addToSearchPath($name, $path);
return $this;
} | php | {
"resource": ""
} |
q265105 | Resolver.getResolver | test | public function getResolver(string $type)
{
if (!isset($this->resolvers[$type]))
throw new \InvalidArgumentException("Unknown resolver type: " . $type);
return $this->resolvers[$type]['resolver'];
} | php | {
"resource": ""
} |
q265106 | Resolver.setResolver | test | public function setResolver(string $type, SubResolver $resolver)
{
if (!isset($this->resolvers[$type]))
throw new \InvalidArgumentException("Unknown resolver type: " . $type);
if ($this->cache !== null)
$resolver->setCache($this->cache);
$this->resolvers[$type]['resolver'] = $resolver;
return $this;
} | php | {
"resource": ""
} |
q265107 | Resolver.resolve | test | public function resolve(string $type, string $reference)
{
if (!isset($this->resolvers[$type]))
throw new \InvalidArgumentException("Unknown resolver type: " . $type);
return $this->resolvers[$type]['resolver']->resolve($reference);
} | php | {
"resource": ""
} |
q265108 | Resolver.setAuthorative | test | public function setAuthorative(bool $authorative)
{
foreach ($this->resolvers as $resolver)
$resolver['resolver']->setAuthorative($authorative);
$this->authorative = $authorative;
return $this;
} | php | {
"resource": ""
} |
q265109 | Resolver.registerModule | test | public function registerModule(string $module, string $path, int $precedence)
{
// Normalize the module name: lowercased, with dots
$module = strtolower(preg_replace('/([\.\\/\\\\])/', '.', $module));
$found_elements = array();
foreach ($this->resolvers as $type => $resolver)
{
$type_path = $path . DIRECTORY_SEPARATOR . $resolver['path'];
if (is_dir($type_path))
{
$resolver['resolver']->addToSearchPath($module, $type_path, $precedence);
$found_elements[] = $type;
}
}
if (!empty($found_elements))
$this->modules[$module] = ['path' => $path, 'precedence' => $precedence];
else
self::getLogger()->debug("No resolvable items found in module: " . $module);
// No longer sorted, probably
$this->sorted = false;
return $this;
} | php | {
"resource": ""
} |
q265110 | Resolver.sortModules | test | protected function sortModules()
{
uasort($this->modules, function ($l, $r) {
if ($l['precedence'] !== $r['precedence'])
return $l['precedence'] - $r['precedence'];
return strcmp($l['path'], $r['path']);
});
$this->sorted = true;
} | php | {
"resource": ""
} |
q265111 | Resolver.setPrecedence | test | public function setPrecedence(string $module, int $precedence)
{
foreach ($this->resolvers as $type => $resolver)
{
try
{
$resolver['resolver']->setPrecedence($module, $precedence);
}
catch (\InvalidArgumentException $e)
{} // Not all resolvers may contain this module
}
$this->modules[$module]['precedence'] = $precedence;
// No longer sorted, probably
$this->sorted = false;
return $this;
} | php | {
"resource": ""
} |
q265112 | Resolver.autoConfigureFromComposer | test | public function autoConfigureFromComposer(string $vendor_dir)
{
$main_dir = dirname($vendor_dir);
// Add the main module
$this->main_module = "main";
$package = $main_dir . DIRECTORY_SEPARATOR . "composer.json";
if (file_exists($package))
{
// A composer.json file should exist for a composer project,
// so read the module name from that.
$json = @file_get_contents($package);
if ($json)
{
$js = @json_decode($json, true);
if (isset($js['name']))
$this->main_module = $js['name'];
}
}
// Register the main module with the highest precedence
$this->registerModule($this->main_module, $main_dir, 0);
$modules = $this->findModules($vendor_dir, "", 1);
ksort($modules);
$count = 0;
foreach ($modules as $name => $path)
$this->registerModule($name, $path, ++$count);
return $this;
} | php | {
"resource": ""
} |
q265113 | Resolver.findModules | test | public static function findModules(string $path, string $module_name_prefix, int $depth)
{
if (!is_dir($path))
throw new \InvalidArgumentException("Not a path: $path");
$dirs = dir($path);
$modules = array();
while ($dir = $dirs->read())
{
if ($dir === ".." || $dir === ".")
continue;
$mod_path = $path . DIRECTORY_SEPARATOR . $dir;
if (!is_dir($mod_path))
continue;
$dirname = ucfirst(strtolower($dir));
$module_name = $module_name_prefix . $dirname;
if ($depth > 0)
{
$sub_modules = self::findModules($mod_path, $module_name . '.', $depth - 1);
$modules = array_merge($modules, $sub_modules);
}
else
{
$modules[$module_name] = $mod_path;
}
}
return $modules;
} | php | {
"resource": ""
} |
q265114 | Panel.getByField | test | public function getByField($fieldName)
{
/* @var $elem Element */
$elems = $this->varValue;
foreach ($elems as $elem) {
if ($elem->fieldName == $fieldName && $elem->className != 'RowCheckbox') {
return $elem;
}
}
} | php | {
"resource": ""
} |
q265115 | ServiceProvider.register | test | public function register()
{
$this->registerCallers();
$this->registerCollections();
$this->registerControllers();
$this->registerDispatchers();
$this->registerResolvers();
if (static::$helpers) {
Helpers::loadAll();
}
PublicReflection::pushCustomerReflections(static::$customReflections);
Caller::$eventCallable = [Event::class, "dispatch"];
return $this;
} | php | {
"resource": ""
} |
q265116 | TypeManager.formattedStringToValue | test | public function formattedStringToValue($type, $format, $formattedString)
{
if ($formattedString === null || $formattedString === "") {
return null;
}
switch ($type)
{
case "Number": return $this->numberToValue($format, $formattedString);
case "Text": return $this->textToValue($format, $formattedString);
case "Date": return $this->dateToValue($format, $formattedString);
case "Datetime": return $this->datetimeToValue($format, $formattedString);
case "Currency": return $this->currencyToValue($format, $formattedString);
case "Phone": return $this->phoneToValue($format, $formattedString);
default: return $formattedString;
}
} | php | {
"resource": ""
} |
q265117 | TypeManager.valueToFormattedString | test | public function valueToFormattedString($type, $format, $value)
{
switch ($type)
{
case "Number": return $this->valueToNumber($format, $value);
case "Text": return $this->valueToText($format, $value);
case "Date": return $this->valueToDate($format, $value);
case "Datetime": return $this->valueToDatetime($format, $value);
case "Currency": return $this->valueToCurrency($format, $value);
case "Phone": return $this->valueToPhone($format, $value);
default: return $value;
}
} | php | {
"resource": ""
} |
q265118 | TypeManager.valueToNumber | test | protected function valueToNumber($format, $value)
{
if ($format[0] == "%") {
return sprintf($format, $value);
}
if (!$this->_localeInfo) {
return $value;
}
$formattedNumber = $value;
if ($format == "Int") {
$formattedNumber = number_format($value, 0, $this->_localeInfo['decimal_point'], $this->_localeInfo['thousands_sep']);
} elseif ($format == "Float") {
$formattedNumber = number_format($value, $this->_localeInfo['frac_digits'], $this->_localeInfo['decimal_point'], $this->_localeInfo['thousands_sep']);
}
return $formattedNumber;
} | php | {
"resource": ""
} |
q265119 | TypeManager.numberToValue | test | protected function numberToValue($format, $formattedValue)
{
if ($formattedValue === false || $formattedValue === true) {
return null;
}
if ($format[0] == "%") {
return sscanf($formattedValue, $format);
}
if (!$this->_localeInfo) {
return $formattedValue;
}
$tmp = str_replace($this->_localeInfo['thousands_sep'], null, $formattedValue);
$tmp = str_replace($this->_localeInfo['decimal_point'], ".", $tmp);
if ($format == "Int") {
return (int) $tmp;
}
return $tmp;
} | php | {
"resource": ""
} |
q265120 | TypeManager.valueToDate | test | protected function valueToDate($format, $value)
{
// ISO format YYYY-MM-DD as input
if ($value == "0000-00-00") {
return "";
}
if (!$value) {
return "";
}
if (strlen(trim($value)) < 1) {
return "";
}
$tt = strtotime($value);
if ($tt != - 1) {
return strftime($format, strtotime($value));
}
return "";
} | php | {
"resource": ""
} |
q265121 | TypeManager.dateToValue | test | protected function dateToValue($format, $formattedValue)
{
if (!$formattedValue) {
return '';
}
$stdFormat = $this->convertDatetimeFormat($formattedValue, $format, '%Y-%m-%d');
return $stdFormat;
} | php | {
"resource": ""
} |
q265122 | TypeManager.valueToDatetime | test | protected function valueToDatetime ($fmt, $value)
{
// ISO format YYYY-MM-DD HH:MM:SS as input
if ($value == "0000-00-00 00:00:00") {
return "";
}
if ($fmt == null) {
$fmt = DATETIME_FORMAT;
}
return $this->valueToDate($fmt, $value);
} | php | {
"resource": ""
} |
q265123 | TypeManager.datetimeToValue | test | protected function datetimeToValue($format, $formattedValue)
{
if (!$formattedValue) {
return '';
}
$stdFormat = $this->convertDatetimeFormat($formattedValue, $format, '%Y-%m-%d %H:%M:%S');
return $stdFormat;
} | php | {
"resource": ""
} |
q265124 | TypeManager.valueToCurrency | test | protected function valueToCurrency($format, $value)
{
if (!$value) {
return "";
}
if (!$this->_localeInfo) {
return $value;
}
$fmtNum = number_format($value, $this->_localeInfo['frac_digits'], $this->_localeInfo['mon_decimal_point'], $this->_localeInfo['mon_thousands_sep']);
return $this->_localeInfo["currency_symbol"] . $fmtNum;
} | php | {
"resource": ""
} |
q265125 | TypeManager.currencyToValue | test | protected function currencyToValue($format, $formattedValue)
{
if (!$this->_localeInfo) {
return $formattedValue;
}
$tmp = str_replace($this->_localeInfo["currency_symbol"], null, $formattedValue);
$tmp = str_replace($this->_localeInfo['thousands_sep'], null, $tmp);
return (float) $tmp;
} | php | {
"resource": ""
} |
q265126 | TypeManager.valueToPhone | test | protected function valueToPhone($mask, $value)
{
if (substr($value, 0, 1) == "*") { // if phone starts with "*", it's an international number, don't convert it
return $value;
}
if (trim($value) == "") {
return $value;
}
$maskLen = strlen($mask);
$ph_len = strlen($value);
$ph_fmt = $mask;
$j = 0;
for ($i = 0; $i < $maskLen; $i ++)
{
if ($mask[$i] == "#")
{
$ph_fmt[$i] = $value[$j];
$j ++;
if ($j == $ph_len) {
break;
}
}
}
return substr($ph_fmt, 0, $i + 1);
} | php | {
"resource": ""
} |
q265127 | TypeManager.convertDatetimeFormat | test | public function convertDatetimeFormat($oldFormattedValue, $oldFormat, $newFormat)
{
if ($oldFormat == $newFormat) {
return $oldFormattedValue;
}
$timeStamp = $this->_parseDate($oldFormat, $oldFormattedValue);
return strftime($newFormat, $timeStamp);
} | php | {
"resource": ""
} |
q265128 | TypeManager._parseDate | test | private function _parseDate ($fmt, $fmtValue)
{
$y = 0;
$m = 0;
$d = 0;
$hr = 0;
$min = 0;
$sec = 0;
$a = preg_split("/\W+/", $fmtValue);
preg_match_all("/%./", $fmt, $b);
for ($i = 0; $i < count($a); ++ $i)
{
if (!$a[$i]) {
continue;
}
switch ($b[0][$i])
{
case "%d": // the day of the month ( 00 .. 31 )
case "%e": // the day of the month ( 0 .. 31 )
$d = intval($a[$i], 10);
break;
case "%m": // month ( 01 .. 12 )
$m = intval($a[$i], 10);
break;
case "%Y": // year including the century ( ex. 1979 )
case "%y": // year without the century ( 00 .. 99 )
$y = intval($a[$i], 10);
if ($y < 100) {
$y += ($y > 29) ? 1900 : 2000;
}
break;
case "%H": // hour ( 00 .. 23 )
case "%I": // hour ( 01 .. 12 )
case "%k": // hour ( 00 .. 23 )
case "%l": // hour ( 01 .. 12 )
$hr = intval($a[$i], 10);
break;
case "%P": // PM or AM
case "%p": // pm or am
if ($a[$i] == 'pm' && $hr < 12) {
$hr += 12;
} else
if ($a[$i] == 'am' && $hr >= 12) {
$hr -= 12;
}
break;
case "%M": // minute ( 00 .. 59 )
$min = intval($a[$i], 10);
break;
case "%S": // second ( 00 .. 59 )
$sec = intval($a[$i], 10);
break;
//default:
}
}
$timeStamp = mktime($hr, $min, $sec, $m, $d, $y);
return $timeStamp;
} | php | {
"resource": ""
} |
q265129 | Database.renderDsnForMySQL | test | protected function renderDsnForMySQL()
{
$h = $this->getHost();
$p = $this->getPort();
$s = $this->getUnixSocket();
$c = $this->getCharset();
$b = $this->getDbName();
return self::DRIVER_MYSQL . $this->renderDsnParts([
'host' => !empty($h) ? $h : NULL,
'port' => !empty($p) ? $p : NULL,
'unix_socket' => !empty($s) ? $s : NULL,
'dbname' => !empty($b) ? $b : NULL,
'username' => $this->getUsername(),
'password' => $this->getPassword(),
'charset' => !empty($c) ? $c : NULL,
], ';');
} | php | {
"resource": ""
} |
q265130 | Database.renderDsnForPgsql | test | protected function renderDsnForPgsql()
{
$h = $this->getHost();
$p = $this->getPort();
$b = $this->getDbName();
return self::DRIVER_PGSQL . $this->renderDsnParts([
'host' => !empty($h) ? $h : NULL,
'port' => !empty($p) ? $p : NULL,
'dbname' => !empty($b) ? $b : NULL,
'user' => $this->getUsername(),
'password' => $this->getPassword(),
], ' ');
} | php | {
"resource": ""
} |
q265131 | Database.renderDsnParts | test | protected function renderDsnParts(array $map, $delimiter = ';')
{
$list = [];
foreach ($map as $key => $value)
{
if (!\is_null($value))
{
$list[] = $key . '=' . $value;
}
}
return \implode($delimiter, $list);
} | php | {
"resource": ""
} |
q265132 | Database.public__insert | test | protected function public__insert($table_name, array $data_to_insert)
{
$pdo = $this->getPDOInstance();
\ksort($data_to_insert);
$fieldNames = \implode('`, `', \array_keys($data_to_insert));
$fieldValues = ':' . \implode(', :', \array_keys($data_to_insert));
$sqlQuery = "INSERT INTO " . $this->quoteTableName($this->getPrefixedTableName($table_name)) . " (`$fieldNames`) VALUES ($fieldValues)";
$sth = $pdo->prepare($sqlQuery);
foreach ($data_to_insert as $key => $value)
{
$sth->bindValue(":$key", $value, $this->getPdoType(\gettype($value)));
}
$sth->execute();
return $this->setLastInsertId($pdo->lastInsertId())->getLastInsertId();
} | php | {
"resource": ""
} |
q265133 | Database.public__insertMultiple | test | protected function public__insertMultiple($table_name, array $data_to_insert)
{
$pdo = $this->getPDOInstance();
$fieldNames = \implode('`, `', \array_values($data_to_insert['field_names']));
$sqlQuery = "INSERT INTO " . $this->quoteTableName($this->getPrefixedTableName($table_name)) . " (`$fieldNames`) VALUES ";
$i = 0;
$fieldValues = '';
foreach ($data_to_insert['values'] as $rec_value)
{
$fieldValues .= '(';
foreach ($rec_value as $value)
{
$fieldValues .= ":v$i,";
$i++;
}
$fieldValues .= \rtrim($fieldValues, ',') . '),';
}
$sqlQuery .= \rtrim($fieldValues, ',') . ";";
$sth = $pdo->prepare($sqlQuery);
$i = 0;
foreach ($data_to_insert['values'] as $rec_value)
{
foreach ($rec_value as $value)
{
$sth->bindValue(':v' . $i++, $value, $this->getPdoType(\gettype($value)));
}
}
try
{
$pdo->beginTransaction();
$sth->execute();
$pdo->commit();
}
catch (Exception $exc)
{
$pdo->rollback();
return FALSE;
}
return TRUE;
} | php | {
"resource": ""
} |
q265134 | Request.request_path | test | private function request_path()
{
$request_uri = explode('/', trim($this->options['REQUEST_URI'], '/'));
$script_name = explode('/', trim($this->options['SCRIPT_NAME'], '/'));
$parts = array_diff_assoc($request_uri, $script_name);
if (empty($parts)) {
return '/';
}
$path = implode('/', $parts);
if (($position = strpos($path, '?')) !== false) {
$path = substr($path, 0, $position);
}
return $path;
} | php | {
"resource": ""
} |
q265135 | Container.get | test | public function get($id)
{
if( !$this->has($id) ){
throw new EntryNotFoundException;
}
$concrete = $this->items[$id];
if( $concrete instanceof ContainerBuilder ){
return $concrete->make();
}
return $concrete;
} | php | {
"resource": ""
} |
q265136 | QueryStringParam.formatQueryString | test | public static function formatQueryString($field, $opr, $value)
{
$key = ":_v".QueryStringParam::$_counter;
$queryString = "$field $opr $key";
QueryStringParam::$_counter++;
QueryStringParam::$params[$key] = $value;
return $queryString;
} | php | {
"resource": ""
} |
q265137 | QueryStringParam.formatQueryValue | test | public static function formatQueryValue($value)
{
$key = ":_v".QueryStringParam::$_counter;
$queryString = "$key";
QueryStringParam::$_counter++;
QueryStringParam::$params[$key] = $value;
return $queryString;
} | php | {
"resource": ""
} |
q265138 | QueryStringParam.setBindValues | test | public static function setBindValues($params)
{
if (!$params)
return;
QueryStringParam::$params = $params;
QueryStringParam::$_counter = count($params)+1;
} | php | {
"resource": ""
} |
q265139 | profileService.getDBProfile | test | protected function getDBProfile($userId, $password)
{
// CASE 1: simple one table query
// SELECT role, group, pstn, divn, org FROm user_table AS t1
// WHERE t1.userid='$userid'
// CASE 2: intersection table user_pstn (user_role, user_divn, user_org ...), need to query multiple times
// SELECT t1.pstnid, t2.name FROM user_pstn_table AS t1
// JOIN pstn_table AS t2 ON t1.pstnid=t2.id
// WHERE t1.userid='$userid'
// CASE 3: all hierarchy info contained in one big party table, do query once, then filter on type column
// SELECT t1.partyid, t2.name, t2.type FROM user_party_table AS t1
// JOIN party_table AS t2 ON t1.partyid=t2.id
// WHERE t1.userid='$userid'
$db = Openbizx::$app->getDbConnection();
$resultSet = $db->execute($sql);
$sqlArr = $resultSet->fetchRow();
// process the result
} | php | {
"resource": ""
} |
q265140 | PlainTextSettingsWriter.format | test | public function format(IReport $report)
{
$params = $this->getParameters();
$file = $params->get('location', 'environaut-config');
$groups = $params->get('groups');
$output = $this->startOutput($file, $groups);
$embed_group_path = $params->get('embed_group_path', true);
$filter_settings = $params->get('filter_settings', array());
$template = $params->get('template', false);
if (!$template) {
throw new RuntimeException(
sprintf("The %s does not support a default template. Please define one.", __CLASS__)
);
}
$template_settings = array();
foreach ($report->getSettingsAsArray($groups) as $setting) {
if ($embed_group_path === true) {
$setting_key = $setting['group'] . '.' . $setting['name'];
} else {
$setting_key = $setting['name'];
}
$template_settings[$setting_key] = $setting['value'];
}
$content = self::vksprintf($template, $template_settings);
return $this->endOutput(
file_put_contents($file, $content, LOCK_EX)
);
} | php | {
"resource": ""
} |
q265141 | validateService.strongPassword | test | public function strongPassword($value)
{
$this->errorMessage = null;
require_once 'Zend/Validate/Regex.php';
$validator = new \Zend_Validate_Regex("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/");
$result = $validator->isValid($value);
if (!$result) {
$this->errorMessage = MessageHelper::getMessage("VALIDATESVC_PASSWORD_NOT_STRONG", array($this->fieldNameMask));
}
return $result;
} | php | {
"resource": ""
} |
q265142 | validateService.email | test | public function email($email)
{
$this->errorMessage = null;
//require_once 'Zend/Validate/EmailAddress.php';
/*
* it's a newbelogic, too complicated
$validator = new \Zend_Validate_EmailAddress();
$result = $validator->isValid($email);
*/
if (preg_match("/^[A-Z0-9_-][A-Z0-9._-]*@([A-Z0-9][A-Z0-9-]*\.)+[A-Z\.]{2,6}$/i", $email)) {
$result = true;
} else {
$result = false;
}
if (!$result) {
$this->errorMessage = MessageHelper::getMessage("VALIDATESVC_EMAIL_INVALID", array($this->fieldNameMask));
}
return $result;
} | php | {
"resource": ""
} |
q265143 | validateService.date | test | public function date($date)
{
$this->errorMessage = null;
require_once 'Zend/Validate/Date.php';
$validator = new \Zend_Validate_Date();
$result = $validator->isValid($date);
if (!$result) {
$this->errorMessage = MessageHelper::getMessage("VALIDATESVC_DATE_INVALID", array($this->fieldNameMask));
}
return $result;
} | php | {
"resource": ""
} |
q265144 | validateService.getErrorMessage | test | public function getErrorMessage($validator = null, $fieldName = null)
{
if ($this->errorMessage != "") {
if ($fieldName != "") {
$this->errorMessage = str_replace($this->fieldNameMask, $fieldName, $this->errorMessage);
}
return $this->errorMessage;
} else {
$validator = str_replace('{@validate:', '', $validator);
$pos1 = strpos($validator, '(');
$type = substr($validator, 0, $pos1);
switch ($type) {
case "date":
return MessageHelper::getMessage("VALIDATESVC_DATE_INVALID", array($fieldName));
break;
case "email":
return MessageHelper::getMessage("VALIDATESVC_EMAIL_INVALID", array($fieldName));
break;
case "phone":
return MessageHelper::getMessage("VALIDATESVC_PHONE_INVALID", array($fieldName));
break;
case "zip":
return MessageHelper::getMessage("VALIDATESVC_ZIP_INVALID", array($fieldName));
break;
case "social":
return MessageHelper::getMessage("VALIDATESVC_SOCIAL_INVALID", array($fieldName));
break;
case "credit":
return MessageHelper::getMessage("VALIDATESVC_CREDIT_INVALID", array($fieldName));
break;
case "street":
return MessageHelper::getMessage("VALIDATESVC_STREET_INVALID", array($fieldName));
break;
case "strongPassword":
return MessageHelper::getMessage("VALIDATESVC_PASSWORD_NOT_STRONG", array($fieldName));
break;
}
return MessageHelper::getMessage("VALIDATESVC_INVALID", array($fieldName));
}
} | php | {
"resource": ""
} |
q265145 | Adapter.make | test | final public function make(array $input, $fillable, array $defaults = []): Adapter
{
$this->input = Collection::make($input);
try {
$this->setFillable($fillable);
} catch (\TypeError $e) {
$this->fillable = (array)$fillable;
}
try {
$this->setDefaults($fillable, $defaults);
} catch (\TypeError $e) {
$this->defaults = $defaults;
}
$this->output = Collection::make([]);
$this->process();
return $this;
} | php | {
"resource": ""
} |
q265146 | Model.agregar | test | public static function agregar() {
$atributos = func_get_arg(0);
$c = get_called_class();
$c = new $c( $atributos );
$c->insert();
return $c;
} | php | {
"resource": ""
} |
q265147 | genIdService.getNewID | test | public function getNewID($idGeneration, $conn, $dbType, $table=null, $column=null)
{
try
{
if (!$idGeneration || $idGeneration == 'Openbizx')
{
$newid = $this->getNewSYSID($conn, $table, true);
}
elseif ($idGeneration == 'Identity')
{
//$newid = $this->getNewIdentity($conn, $dbtype, $table, $column);
$newid = $conn->lastInsertId($table, $column); // user zend_db method
}
elseif (strpos($idGeneration, 'Sequence:')===0)
{
$seqname = substr($idGeneration, 9);
//$newid = $this->getNewSequence($conn, $dbtype, $seqname);
$newid = $conn->nextSequenceId($seqname); // user zend_db method
}
elseif ($idGeneration == 'GUID')
{
$newid = $this->getNewGUID($conn, $dbType, $table, $column);
}
elseif ($idGeneration == 'UUID')
{
$newid = $this->getNewUUID();
}
else
{
throw new Exception("Error in generating new ID: unsupported generation type.");
}
}
catch (Exception $e)
{
throw new Exception($e->getMessage());
}
return $newid;
} | php | {
"resource": ""
} |
q265148 | genIdService.getNewSYSID | test | protected function getNewSYSID($conn, $tableName, $includePrefix=false, $base=-1)
{
$maxRetry = 10;
// try to update the table idbody column
for ($try=1; $try <= $maxRetry; $try++)
{
$sql = "SELECT * FROM ob_sysids WHERE TABLENAME='$tableName'";
try
{
$rs = $conn->query($sql);
}
catch (Exception $e)
{
throw new Exception("Error in query: " . $sql . ". " . $e->getMessage());
return false;
}
$row = $rs->fetch();
unset($rs);
list($tblname, $prefix, $idbody) = $row;
if (!$row)
throw new Exception("Error in generating new system id: '$tableName' is not in ob_sysids table.");
if ($row)
{
if ($idbody == null && $prefix) // idbody is empty, return false
throw new Exception("Error in generating new system id: ob_sysids table does not have a valid sequence for '$tableName'.");
}
// try to update the table idbody column
$sql = "UPDATE ob_sysids SET IDBODY=IDBODY+1 WHERE TABLENAME='$tableName' AND IDBODY=$idbody";
try
{
$rs = $conn->query($sql);
}
catch (Exception $e)
{
throw new Exception("Error in query: " . $sql . ". " . $e->getMessage());
return false;
}
if ($rs->rowCount() > 0)
{
$idbody += 1;
break;
}
}
if ($try <= $maxRetry)
{
if ($base>=2 && $base<=36)
$idbody = dec2base($idbody, $base);
if ($includePrefix)
return $prefix."_".$idbody;
return $idbody;
}
else
throw new Exception("Error in generating new system id: unable to get a valid id.");
return false;
} | php | {
"resource": ""
} |
q265149 | genIdService.getNewGUID | test | protected function getNewGUID($conn, $dbType, $table=null, $column=null)
{
$dbType = strtoupper($dbType);
if ($dbType == 'mysql' || $dbType == 'PDO_DBLIB')
$sql = "select uuid()";
else if ($dbType == 'oracle' || $dbType == 'oci8' || $dbType == 'PDO_OCI')
$sql = "select rawtohex(sys_guid()) from dual";
else if ($dbType == 'msql' || $dbType == 'PDO_MYSQL')
$sql = "select newid()";
else
throw new Exception("Error in generating new GUID: unsupported database type.");
// execute sql to get the id
$newId = $this->_getIdWithSql($conn, $sql);
if ($newId === false)
throw new Exception("Error in generating new GUID: unable to get a valid id.");
return $newId;
} | php | {
"resource": ""
} |
q265150 | genIdService._getIdWithSql | test | private function _getIdWithSql($conn, $sql)
{
try
{
$rs = $conn->query($sql);
Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Get New Id: $sql");
}
catch (Exception $e)
{
$this->errorMessage = "Error in query: " . $sql . ". " . $e->getMessage();
return false;
}
if (($row = $rs->fetch()) != null)
{
//print_r($row);
return $row[0];
}
return false;
} | php | {
"resource": ""
} |
q265151 | GetsAttributes.getVisibleAttribute | test | protected function getVisibleAttribute(string $name, $default = null)
{
$method = "get" . ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method($default);
} elseif (PublicReflection::hasAttribute(get_class($this), $name)) {
return $this->getAttribute($name, $default);
} elseif ($this->triggerUndefinedAttributeNotice) {
$className = get_class($this);
trigger_error("The property {$className}::\${$name} is not accessible.", E_USER_NOTICE);
}
return $default;
} | php | {
"resource": ""
} |
q265152 | logService.setFormatter | test | public function setFormatter()
{
switch ($this->_format) {
case 'HTML':
//HTML Format
$this->_formatter = new \Zend_Log_Formatter_Simple('<tr><td>%date%</td> <td>%time%</td> <td>%priorityName%</td> <td>%package%</td> <td>%message%</td> <td>%back_trace%</td> </tr>' . PHP_EOL);
break;
case 'XML':
//XML Format
require_once 'Zend/Log/Formatter/Xml.php';
$this->_formatter = new \Zend_Log_Formatter_Xml();
break;
case 'CSV':
default:
//CSV Format
$this->_formatter = new \Zend_Log_Formatter_Simple("'%date%','%time%','%priorityName%','%package%','%message%','%back_trace%'" . PHP_EOL);
break;
}
} | php | {
"resource": ""
} |
q265153 | logService.prepFile | test | public function prepFile($path)
{
//Check for existing file and HTML format
if (file_exists($path) and $this->_format == 'HTML') {
$file = file($path);
array_pop($file);
file_put_contents($path, $file);
} elseif ($this->_format == 'HTML') {
$html = '<html><head></head><body><table border="1">' . PHP_EOL;
$file = fopen($path, 'a');
fwrite($file, $html);
fclose($file);
} elseif (file_exists($path) and $this->_format == 'XML') {
$file = file($path);
array_pop($file);
file_put_contents($path, $file);
} elseif ($this->_format == 'XML') {
$xml = '<?xml version="1.0" standalone="no"?><log>' . PHP_EOL;
$file = fopen($path, 'a');
fwrite($file, $xml);
fclose($file);
}
} | php | {
"resource": ""
} |
q265154 | logService.closeFile | test | public function closeFile($path)
{
//Close up the file if needed
switch ($this->_format) {
case 'HTML':
$html = "</table></body></html>";
$file = fopen($path, 'a');
fwrite($file, $html);
fclose($file);
break;
case 'XML':
$xml = "</log>";
$file = fopen($path, 'a');
fwrite($file, $xml);
fclose($file);
break;
default:
break;
}
} | php | {
"resource": ""
} |
q265155 | logService._getPath | test | private function _getPath($fileName = null)
{
$level = $this->_level;
if ($fileName) {
return OPENBIZ_LOG_PATH . '/' . $fileName . $this->_extension;
}
switch ($this->_org) {
case 'DATE':
return OPENBIZ_LOG_PATH . '/' . date("Y_m_d") . $this->_extension;
case 'LEVEL':
$level = $this->_level2filename($level);
return OPENBIZ_LOG_PATH . '/' . $level . $this->_extension;
case 'LEVEL-DATE':
$level = $this->_level2filename($level);
//delete old log files
if ($this->_daystolive > 0) {
if (is_array(glob(OPENBIZ_LOG_PATH . '/' . $level . '-*' . $this->_extension))) {
foreach (glob(OPENBIZ_LOG_PATH . '/' . $level . '-*' . $this->_extension) as $filename) {
$mtime = filemtime($filename);
if ((time() - $mtime) >= $this->_daystolive * 86400) {
@unlink($filename);
}
}
}
}
return OPENBIZ_LOG_PATH . '/' . $level . '-' . date("Y_m_d") . $this->_extension;
case 'PROFILE':
$profile = Openbizx::$app->getUserProfile('USERID');
if (!$profile) {
$profile = 'Guest';
}
return OPENBIZ_LOG_PATH . '/' . $profile . $this->_extension;
default:
break;
}
} | php | {
"resource": ""
} |
q265156 | Export.getFormatterByExtension | test | protected function getFormatterByExtension($location)
{
$ext = pathinfo($location, PATHINFO_EXTENSION);
$formatter = null;
switch ($ext) {
case 'json':
$formatter = 'Environaut\Export\Formatter\JsonSettingsWriter';
break;
case 'xml':
$formatter = 'Environaut\Export\Formatter\XmlSettingsWriter';
break;
case 'php':
$formatter = 'Environaut\Export\Formatter\PhpSettingsWriter';
break;
case 'sh':
$formatter = 'Environaut\Export\Formatter\ShellSettingsWriter';
break;
case 'txt':
default:
$formatter = 'Environaut\Export\Formatter\PlainTextSettingsWriter';
}
return $formatter;
} | php | {
"resource": ""
} |
q265157 | DefaultController.getManager | test | protected function getManager()
{
$gdm = $this->get('wobblecode_manager.document_manager')
->setDocument('WobbleCodeUserBundle:Organization')
->setKey('organization')
->setAcceptFromRequest(['page', 'query', 'itemsPerPage'])
->setItemsPerPage(2)
->setQueryFields(['name', 'type']);
return $gdm;
} | php | {
"resource": ""
} |
q265158 | pdfService.renderView | test | public function renderView($viewName)
{
$viewObj = Openbizx::getObject($viewName);
if($viewObj)
{
$viewObj->setConsoleOutput(false);
$sHTML = $viewObj->render();
//$sHTML = "Test";
//require_once("dompdf/dompdf_config.inc.php");
$domPdf = new DOMPDF();
$domPdf->load_html($sHTML);
//$dompdf->set_paper($_POST["paper"], $_POST["orientation"]);
$domPdf->render();
$this->output($domPdf);
//$dompdf->stream("dompdf_out.pdf");
}
} | php | {
"resource": ""
} |
q265159 | pdfService.output | test | public function output($domPdf)
{
//$tmpfile = getcwd()."/tmpfiles";
$tmpDir = OPENBIZ_APP_PATH."/tmpfiles";
//echo $tmpfile;
$this->cleanFiles($tmpDir, 100);
//Determine a temporary file name in the current directory
$tmpFile = tempnam($tmpDir,'tmp');
$fileName = $tmpFile.'.pdf';
$fileName = str_replace("\\","/",$fileName);
unlink($tmpFile);
//Save PDF to file
$pdfText = $domPdf->output();
$fileHandle = fopen($fileName, 'w') or die("can't open pdf file to write");
fwrite($fileHandle, $pdfText) or die("can't write to the pdf file");
fclose($fileHandle);
//JavaScript redirection
$path_parts = pathinfo($fileName);
$file_download = "tmpfiles/".$path_parts['basename'];
echo "<HTML><BODY onload=\"window.location.href='../$file_download';\"</BODY></HTML>";
} | php | {
"resource": ""
} |
q265160 | RestClient.setBaseUrl | test | public static function setBaseUrl(string $url = ""): string
{
// IF no URL has been specified...
if($url === "" || $url === null)
{
// AND the current URL is not set...
if (self::$_baseUrl === "")
// ... Throw an exception!
throw new \Exception("[MVQN\REST\ResClient] ".
"'baseUrl' must be set by RestClient::baseUrl() before calling any RestClient methods!");
}
else
{
// OTHERWISE set the URL to that which was specified here.
self::$_baseUrl = $url;
self::client(true);
}
// Finally, return the URL, which should NEVER be empty at this point!
return self::$_baseUrl;
} | php | {
"resource": ""
} |
q265161 | RestClient.curl | test | private static function curl(string $endpoint)
{
// Get the base URL and App Key.
$baseUrl = self::$_baseUrl;
// Create a cURL session.
$curl = curl_init();
// Set the options necessary for communicating with the UCRM Server.
curl_setopt($curl, CURLOPT_URL, $baseUrl.$endpoint);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
// IF the Base URL is using HTTPS AND is requesting localhost...
if(Strings::startsWith(self::$_baseUrl, "https://localhost"))
{
// THEN disable host/peer certificate checks, as localhost cannot resolve to a valid name for SSL!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
}
else
{
// OTHERWISE, enable host/peer certificate checks, this is fine for all HTTP URLs (including localhost)!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // DEFAULT
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); // DEFAULT
// Downloaded from: https://curl.haxx.se/docs/caextract.html
curl_setopt($curl, CURLOPT_CAINFO, __DIR__ . "/Certificates/cacert-2018-10-17.pem");
curl_setopt($curl, CURLOPT_CAPATH, __DIR__ . "/Certificates/cacert-2018-10-17.pem");
}
// Set the necessary HTTP HEADERS.
curl_setopt($curl, CURLOPT_HTTPHEADER, self::$_headers);
return $curl;
} | php | {
"resource": ""
} |
q265162 | RestClient.getMany | test | public static function getMany(array $endpoints): array
{
// Create a cURL multi-session handler and an array to store each instance of the cURL sessions.
$curl_handler = curl_multi_init();
$curls = [];
// Loop through each provided endpoint...
for($i = 0; $i < count($endpoints); $i++)
{
// Create the cURL session.
$curl = self::curl($endpoints[$i]);
// Add the cURL session to the multi-session handler and store it in the array of sessions.
curl_multi_add_handle($curl_handler, $curl);
$curls[] = $curl;
}
$running = null;
// Loop through and execute all of the cURL sessions in the multi-session handler...
do curl_multi_exec($curl_handler, $running); while ($running);
$responses = [];
// Loop through each of the cURL sessions...
for($i = 0; $i < count($curls); $i++)
{
// Get each session response and convert it to an associative array.
$response = curl_multi_getcontent($curls[$i]);
// Check to see if there were any errors...
if(!$response)
throw new \Exception("[MVQN\REST\ResClient] ".
"The REST request failed with the following error(s): ".curl_error($curls[$i]));
// Append the successful response to the array of responses.
$responses[] = json_decode($response, true);
// Then remove the cURL session from the multi-session handler.
curl_multi_remove_handle($curl_handler, $curls[$i]);
}
// Close the cURL multi-session handler.
curl_multi_close($curl_handler);
// Finally, return the
return $responses;
} | php | {
"resource": ""
} |
q265163 | RestClient.post | test | public static function post(string $endpoint, array $data): array
{
/*
// Create the cURL session.
$curl = self::curl($endpoint);
// Set any additional options.
curl_setopt($curl, CURLOPT_POST, true);
// Set the data to be provided to the endpoint.
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, self::JSON_OPTIONS));
// Execute the request and capture the response.
$response = curl_exec($curl);
// Check to see if there were any errors...
if(!$response)
throw new \Exception("[MVQN\REST\ResClient] The REST request failed with the following error(s): ".curl_error($curl));
// Close the cURL session.
curl_close($curl);
*/
$response = (string)self::client()->post(ltrim($endpoint, "/"), [ "json" => $data ] )->getBody();
// Finally, return the resulting associative array!
return json_decode($response, true);
} | php | {
"resource": ""
} |
q265164 | RestClient.postMany | test | public static function postMany(array $endpoints, array $data): array
{
if(count($endpoints) !== count($data))
throw new \Exception("[MVQN\REST\ResClient] ".
"Each endpoint in a RestClient::postMany() call must have an accompanying data element.");
// Create a cURL multi-session handler and an array to store each instance of the cURL sessions.
$curl_handler = curl_multi_init();
$curls = [];
// Loop through each provided endpoint...
for($i = 0; $i < count($endpoints); $i++)
{
// Create the cURL session.
$curl = self::curl($endpoints[$i]);
// Set any additional options.
curl_setopt($curl, CURLOPT_POST, true);
// Set the data to be provided to the endpoint.
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data[$i], self::JSON_OPTIONS));
// Add the cURL session to the multi-session handler and store it in the array of sessions.
curl_multi_add_handle($curl_handler, $curl);
$curls[] = $curl;
}
$running = null;
// Loop through and execute all of the cURL sessions in the multi-session handler...
do curl_multi_exec($curl_handler, $running); while ($running);
$responses = [];
// Loop through each of the cURL sessions...
for($i = 0; $i < count($curls); $i++)
{
// Get each session response and convert it to an associative array.
$response = curl_multi_getcontent($curls[$i]);
// Check to see if there were any errors...
if(!$response)
throw new \Exception("[MVQN\REST\ResClient] ".
"The REST request failed with the following error(s): ".curl_error($curls[$i]));
// Append the successful response to the array of responses.
$responses[] = json_decode($response, true);
// Then remove the cURL session from the multi-session handler.
curl_multi_remove_handle($curl_handler, $curls[$i]);
}
// Close the cURL multi-session handler.
curl_multi_close($curl_handler);
// Finally, return the
return $responses;
} | php | {
"resource": ""
} |
q265165 | Queue.push | test | public function push(Job $job)
{
return $this->driver->push(
$job->queue,
$this->createPayload($job),
$job->retry_after
);
} | php | {
"resource": ""
} |
q265166 | Queue.createPayload | test | protected function createPayload(Job $job)
{
$payload = json_encode([
'type' => self::TYPE, //只有 type 为 tree6bee 才会自动处理,其他的不处理
'job' => serialize(clone $job),
]);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException('Unable to create payload: ' . json_last_error_msg());
}
return $payload;
} | php | {
"resource": ""
} |
q265167 | ContentElementUtility.contentElementIdentifier | test | public static function contentElementIdentifier(string $contentElementKey): string {
$contentElementIdentifier = $contentElementKey;
if (strpos($contentElementIdentifier, '_') ||
strpos($contentElementIdentifier, '-') ||
strpos($contentElementIdentifier, ' ')) {
$contentElementIdentifier = mb_strtolower($contentElementKey);
$contentElementIdentifier = str_replace('_', ' ', $contentElementIdentifier);
$contentElementIdentifier = str_replace('-', ' ', $contentElementIdentifier);
$contentElementIdentifier = str_replace(' ', '', ucwords($contentElementIdentifier));
}
if ($contentElementIdentifier[0]) {
$contentElementIdentifier[0] = mb_strtoUpper($contentElementIdentifier[0]);
}
return $contentElementIdentifier;
} | php | {
"resource": ""
} |
q265168 | ContentElementUtility.contentElementSignature | test | public static function contentElementSignature(string $extensionIdentifier, string $contentElementIdentifier): string {
$contentElementSignature = mb_strtolower($extensionIdentifier . '_' . $contentElementIdentifier);
return $contentElementSignature;
} | php | {
"resource": ""
} |
q265169 | ContentElementUtility.getContentElementSignature | test | public static function getContentElementSignature(string $extensionIdentifier, string $contentElementIdentifier): string {
return self::contentElementSignature($extensionIdentifier, $contentElementIdentifier);
} | php | {
"resource": ""
} |
q265170 | ColumnImage.getTitle | test | protected function getTitle()
{
if ($this->title == null) {
return null;
}
$formobj = $this->getFormObj();
return Expression::evaluateExpression($this->title, $formobj);
} | php | {
"resource": ""
} |
q265171 | ListForm.removeRecord | test | public function removeRecord()
{
if ($id == null || $id == '')
$id = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');
$selIds = Openbizx::$app->getClientProxy()->getFormInputs('row_selections', false);
if ($selIds == null)
$selIds[] = $id;
foreach ($selIds as $id) {
$rec = $this->getDataObj()->fetchById($id);
$ok = $this->getDataObj()->removeRecord($rec, $bPrtObjUpdated);
if (!$ok)
return $this->processDataObjError($ok);
}
$this->runEventLog();
$this->rerender();
if ($this->parentFormName) {
$this->renderParent();
}
} | php | {
"resource": ""
} |
q265172 | ListForm.sortRecord | test | public function sortRecord($sortCol, $order = 'ASC')
{
$element = $this->getElement($sortCol);
// turn off the OnSort flag of the old onsort field
$element->setSortFlag(null);
// turn on the OnSort flag of the new onsort field
if ($order == "ASC")
$order = "DESC";
else
$order = "ASC";
$element->setSortFlag($order);
// change the sort rule and issue the query
$this->getDataObj()->setSortRule("[" . $element->fieldName . "] " . $order);
// move to 1st page
$this->currentPage = 1;
$this->sortRule = "";
$this->rerender();
} | php | {
"resource": ""
} |
q265173 | ViewColumnViewHelper.filterViewChildrenByViewColumn | test | protected function filterViewChildrenByViewColumn(array $viewChildren, int $viewColumn) {
$result = [];
if ($viewChildren) {
foreach($viewChildren as $viewChild) {
if (intval($viewChild['tx_gridelements_columns']) == $viewColumn) {
$result[] = $viewChild;
}
}
}
return $result;
} | php | {
"resource": ""
} |
q265174 | ViewColumnViewHelper.filterViewChildrenBySysLanguage | test | protected function filterViewChildrenBySysLanguage($viewChildren) {
$result = [];
if ($viewChildren) {
$sysLanguageUid = $this->getSysLanguageUid();
foreach($viewChildren as $viewChild) {
if (intval($viewChild['sys_language_uid']) == $sysLanguageUid) {
$result[] = $viewChild;
}
}
}
return $result;
} | php | {
"resource": ""
} |
q265175 | Manager.setFieldValueByDbKey | test | public function setFieldValueByDbKey(Entity $entity, $dbFieldName, $value)
{
$this->getTableSchema();
if (!array_key_exists('db_to_field', $this->cache) && !array_key_exists($dbFieldName, $this->cache['db_to_field'])) {
throw new \Exception('There is no field mapped to ' . $dbFieldName . ' in ' . get_class($this));
}
$fieldName = $this->cache['db_to_field'][$dbFieldName];
$method = 'set' . ucfirst($fieldName);
/** @var Column $columnSchema */
$columnSchema = $this->cache['columns'][$fieldName];
if ($columnSchema->getType() == 'Array') {
if (!is_array($value)) {
$value = $value ? json_decode($value, true) : [];
}
} elseif ($columnSchema->getType() == 'Boolean') {
$value = $value ? true : false;
}
$entity->$method($value);
} | php | {
"resource": ""
} |
q265176 | Manager.getDataArray | test | public function getDataArray(Entity $entity, $onlyChanged = false, $updateLoadedData = false)
{
$result = array();
foreach ($this->getColumnsSchemas() as $fieldName => $schema) {
$value = $this->getFieldValue($entity, $fieldName);
if ($schema->getType() == 'Array') {
if (!is_array($value) || !$value) {
$value = json_encode([]);
} else {
$value = json_encode($value);
}
}
if ($onlyChanged && array_key_exists($schema->getName(), $entity->getLoadedData())) {
if ($schema->getType() == 'Boolean') {
if ($value === ($entity->getLoadedData()[$schema->getName()] ? true : false)) {
continue;
}
}
if ($value === $entity->getLoadedData()[$schema->getName()]) {
continue;
}
}
if ($updateLoadedData) {
$entity->getLoadedData()[$schema->getName()] = $value;
}
if (!$value) {
if ($value === false) {
$value = '0';
} elseif ($value === 0) {
$value = '0';
}
}
$result[$schema->getName()] = $value;
}
return $result;
} | php | {
"resource": ""
} |
q265177 | Manager.fillByData | test | public function fillByData(array $data, Entity $entity = null)
{
$entity = $entity ? $entity : $this->createEntity();
$entity->setLoadedData($data);
foreach ($data as $key => $value) {
if ($key == $this->getIdColumnName()) {
$entity->setLoadedFromDb(true);
}
$this->setFieldValueByDbKey($entity, $key, $value);
}
return $entity;
} | php | {
"resource": ""
} |
q265178 | File.extractZip | test | public static function extractZip(string $archive, string $dir, bool $remove = false): void
{
$zip = new ZipArchive();
$x = $zip->open($archive);
if ($x === true) {
if (!$zip->extractTo($dir)) {
throw new IOException("File '$archive' cannot be extracted");
}
$zip->close();
if ($remove) {
unlink($archive);
}
} else {
throw new IOException("File '$archive' cannot be opened: $x");
}
} | php | {
"resource": ""
} |
q265179 | File.addToZip | test | private static function addToZip(string $sourcePath, ZipArchive $zipFile): void
{
$source = new SplFileInfo($sourcePath);
$exclusiveLength = strlen(str_replace($source->getFilename(), '', $source->getRealPath()));
if ($source->isReadable()) {
if ($source->isDir()) {
$zipFile->addEmptyDir($source->getFilename());
foreach (Finder::findFiles('*')
->from($sourcePath) as $file) {
/* @var $file \SplFileObject */
$filePath = $file->getRealPath();
$localPath = substr($filePath, $exclusiveLength);
if ($file->isDir()) {
$zipFile->addEmptyDir($localPath);
} else {
$zipFile->addFile($filePath, $localPath);
}
}
} else {
$zipFile->addFile($source->getRealPath(), $source->getFilename());
}
}
} | php | {
"resource": ""
} |
q265180 | File.extractGZ | test | public static function extractGZ(string $archive, string $sufix = null): void
{
if ($sfp = @gzopen($archive, "rb")) {
$source = str_replace('.gz', '', $archive);
if ($sufix != null) {
$source .= '.' . $sufix;
}
if ($fp = @fopen($source, "w")) {
while (!gzeof($sfp)) {
$string = gzread($sfp, 4096);
if (!fwrite($fp, $string, strlen($string))) {
throw new IOException("File '$source' cannot be write.");
}
}
fclose($fp);
} else {
throw new IOException("File '$source' cannot be write.");
}
gzclose($sfp);
unlink($archive);
} else {
throw new IOException("File '$archive' cannot be read.");
}
} | php | {
"resource": ""
} |
q265181 | File.readLine | test | public static function readLine(string $file, callable $callable, ?int $length = 4096): void
{
if (!$handle = fopen($file, "r")) {
throw new IOException("File '$file' cannot be open.");
}
$fgets = function () use (&$handle, &$length) {
if ($length !== null) {
return fgets($handle, $length);
} else {
return fgets($handle);
}
};
$line = 1;
$stopped = false;
while (($buffer = $fgets()) !== false) {
if ($callable($buffer, $line++) === false) {
$stopped = true;
break;
}
}
if (!$stopped && !feof($handle)) {
throw new IOException("Error: unexpected fgets() fail '$file'");
}
fclose($handle);
} | php | {
"resource": ""
} |
q265182 | File.size | test | public static function size(string $path): float
{
if (is_file($path)) {
return filesize($path);
} else {
$size = 0;
foreach (glob(rtrim($path, '/') . '/*', GLOB_NOSORT) as $each) {
$size += self::size($each);
}
return $size;
}
} | php | {
"resource": ""
} |
q265183 | File.getClasses | test | public static function getClasses(string $file): array
{
$php_code = file_get_contents($file);
$classes = [];
$tokens = token_get_all($php_code);
$count = count($tokens);
for ($i = 2; $i < $count; $i++) {
if ($tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) {
$class_name = $tokens[$i][1];
$classes[] = $class_name;
}
}
return $classes;
} | php | {
"resource": ""
} |
q265184 | IndexedRouter.add | test | public function add($methods, string $uri, $target): Route
{
// Create new Route instance
$route = new Route($methods, $uri, $target, $this->config);
// Index the route
$this->indexRoute($route);
return $route;
} | php | {
"resource": ""
} |
q265185 | IndexedRouter.resolve | test | public function resolve(Request $request): ?Route
{
foreach( $this->indexes[$request->getMethod()] ?? [] as $route ){
if( $route->matchUri($request->getPathInfo()) &&
$route->matchMethod($request->getMethod()) &&
$route->matchHostname($request->getHost()) &&
$route->matchScheme($request->getScheme()) ){
return $route;
}
}
return null;
} | php | {
"resource": ""
} |
q265186 | Config.resolve | test | protected function resolve(string $key)
{
// Break the dotted notation keys into its parts
$parts = explode(".", $key);
// Set the pointer at the root of the items array
$pointer = &$this->items;
/**
*
* Loop through all the parts and see if the key exists.
*
*/
foreach( $parts as $part ){
if( array_key_exists($part, $pointer) === false ){
throw new \Exception("Config key {$key} not found.");
}
$pointer = &$pointer[$part];
}
return $pointer;
} | php | {
"resource": ""
} |
q265187 | Config.has | test | public function has(string $key): bool
{
try {
$this->resolve($key);
} catch( \Exception $exception ){
return false;
}
return true;
} | php | {
"resource": ""
} |
q265188 | Config.get | test | public function get(string $key, $default = null)
{
// Attempt to lazy load keys.
if( $this->has($key) === false ){
$this->load($key);
}
return $this->resolve($key);
} | php | {
"resource": ""
} |
q265189 | Config.loadFile | test | public function loadFile(string $key, string $file): void
{
// Check for file's existence
if( file_exists($file) === false ){
throw new \Exception("Config file not found: {$file}");
}
// Pull config file in and add values into master config
$config = require_once $file;
$this->add($key, $config);
} | php | {
"resource": ""
} |
q265190 | Background.getBackgroundDetails | test | protected function getBackgroundDetails()
{
return [
'position' => [
'0 0' => Translate::t('background.details.position.left_top', [], 'backgroundfield'),
'50% 0' => Translate::t('background.details.position.center_top', [], 'backgroundfield'),
'100% 0' => Translate::t('background.details.position.right_top', [], 'backgroundfield'),
'0 50%' => Translate::t('background.details.position.left_middle', [], 'backgroundfield'),
'50% 50%' => Translate::t('background.details.position.center_middle', [], 'backgroundfield'),
'100% 50%' => Translate::t('background.details.position.right_middle', [], 'backgroundfield'),
'0 100%' => Translate::t('background.details.position.left_bottom', [], 'backgroundfield'),
'50% 100%' => Translate::t('background.details.position.center_bottom', [], 'backgroundfield'),
'100% 100%' => Translate::t('background.details.position.right_bottom', [], 'backgroundfield'),
],
'repeat' => [
'no-repeat' => Translate::t('background.details.repeat.no_repeat', [], 'backgroundfield'),
'repeat-x' => Translate::t('background.details.repeat.repeat_x', [], 'backgroundfield'),
'repeat-y' => Translate::t('background.details.repeat.repeat_y', [], 'backgroundfield'),
'repeat' => Translate::t('background.details.repeat.repeat', [], 'backgroundfield'),
],
'size' => [
'auto' => [
'times',
Translate::t('background.details.size.auto', [], 'backgroundfield'),
],
'cover' => [
'arrows-h',
Translate::t('background.details.size.cover', [], 'backgroundfield'),
],
'contain' => [
'arrows',
Translate::t('background.details.size.contain', [], 'backgroundfield'),
],
],
];
} | php | {
"resource": ""
} |
q265191 | Stream.connect | test | public function connect() : void
{
if (is_resource($this->connection)) {
$this->logger->info('Connection already opened.');
return;
}
$this->logger->info('Opening new connection.');
$request = $this->oauth->getOauthRequest(
$this->getParams(),
$this->httpMethod,
self::BASE_URL,
$this->endpoint
);
$this->connection = fsockopen('ssl://stream.twitter.com', 443);
stream_set_blocking($this->connection, true);
$this->write($request);
$response = [];
while (!$this->eof()) {
$line = trim((string)$this->readLine());
if (empty($line)) {
break;
}
$response[] = $line;
}
$this->checkResponseStatusCode($response[0]);
$this->logger->info('Connection successful.', $response);
} | php | {
"resource": ""
} |
q265192 | Stream.checkResponseStatusCode | test | protected function checkResponseStatusCode($response)
{
preg_match('/^HTTP\/1\.1 ([0-9]{3}).*$/', $response, $matches);
if (200 !== (int)$matches[1]) {
$this->logger->critical('Connection error', [$response]);
throw new Exception\ConnectionException('Connection error: ' . $response);
}
} | php | {
"resource": ""
} |
q265193 | Stream.handleMessage | test | protected function handleMessage(string $messageJson) : void
{
$message = json_decode($messageJson);
$this->logger->info('Message received', [$message]);
} | php | {
"resource": ""
} |
q265194 | Stream.isMessage | test | private function isMessage(string $status) : bool
{
$testStr = substr($status, 0, 14);
if ('{"created_at":' == $testStr) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q265195 | Stream.readNextChunkSize | test | protected function readNextChunkSize() : int
{
while (!$this->eof()) {
$line = trim($this->readLine());
if (!empty($line)) {
$chunkSize = hexdec($line);
return (int)$chunkSize;
}
}
$this->logger->error('Connection closed.');
throw new Exception\ConnectionClosedException('Connection closed.');
} | php | {
"resource": ""
} |
q265196 | Stream.readStream | test | public function readStream() : \Generator
{
$this->connect();
$status = '';
while (!$this->eof()) {
$chunkSize = $this->readNextChunkSize();
if ($this->isEmptyChunk($chunkSize)) {
continue;
}
$chunk = $this->readChunk($chunkSize);
$status .= $chunk;
if ($this->isJsonFinished($chunk, $chunkSize)) {
if ($this->isMessage($status)) {
$this->handleMessage($status);
} else {
yield $status;
}
$status = '';
}
}
$this->close();
} | php | {
"resource": ""
} |
q265197 | Element.getProperty | test | public function getProperty($propertyName)
{
if ($propertyName == "Value") return $this->getValue();
$ret = parent::getProperty($propertyName);
if ($ret) return $ret;
return $this->$propertyName;
} | php | {
"resource": ""
} |
q265198 | Element.getDefaultValue | test | public function getDefaultValue()
{
if ($this->defaultValue == "" && $this->keepCookie!='Y')
return "";
$formObj = $this->getFormObj();
if($this->keepCookie=='Y'){
$cookieName = $formObj->objectName."-".$this->objectName;
$cookieName = str_replace(".","_",$cookieName);
$defValue = $_COOKIE[$cookieName];
}
if(!$defValue){
$defValue = Expression::evaluateExpression($this->defaultValue, $formObj);
}
//add automatic append like new record (2)
if($this->defaultValueRename!='N'){
if(!is_numeric($defValue)){
$dataobj = $formObj->getDataObj();
if($this->fieldName && $dataobj){
if(substr($this->fieldName,0,1)!='_'){
$recs = $dataobj->directfetch("[".$this->fieldName."] = '$defValue' OR "."[".$this->fieldName."] LIKE '$defValue (%)'" );
if($recs->count()>0){
$defValue.= " ( ".$recs->count()." )";
}
}
}
}
}
return $defValue;
} | php | {
"resource": ""
} |
q265199 | Element.getHidden | test | protected function getHidden()
{
if (!$this->hidden || $this->hidden=='N') return "N";
$formObj = $this->getFormObj();
return Expression::evaluateExpression($this->hidden, $formObj);
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.