_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q252300 | Path.files | validation | public static function files($path, array $extensions = array())
{
$files = array();
$it = new \RecursiveDirectoryIterator($path);
$filter = false;
if(!empty($extensions) && is_array($extensions)){
$filter = true;
}
foreach(new \RecursiveIteratorIterator($it) as $file){
if($filter){
$f = explode('.', $file);
$ext = strtolower(array_pop($f));
if (in_array($ext, $extensions)){
// $files[] = $file->__toString();
$files[] = $file;
}
}else{
$files[] = $file;
}
}
return $files;
} | php | {
"resource": ""
} |
q252301 | StringType.value | validation | public function value($encoding = null)
{
if ($this->value !== null) {
if ($encoding === null) {
return mb_convert_encoding($this->value, $this->encoding, 'UTF-8');
} else {
$encoding = $this->getRealEncoding($encoding);
return mb_convert_encoding($this->value, $encoding, 'UTF-8');
}
}
} | php | {
"resource": ""
} |
q252302 | StringType.supportedEncodings | validation | public static function supportedEncodings()
{
if (static::$supported_encodings === null) {
$supported = mb_list_encodings();
foreach ($supported as $key => $value) {
static::$supported_encodings[strtolower($value)] = $value;
foreach (mb_encoding_aliases($value) as $k => $v) {
static::$supported_encodings[strtolower($v)] = $value;
}
}
}
return static::$supported_encodings;
} | php | {
"resource": ""
} |
q252303 | StringType.isEncodingSupported | validation | public static function isEncodingSupported($encoding)
{
$encoding = strtolower($encoding);
if (isset (static::supportedEncodings()[$encoding])) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q252304 | StringType.getRealEncoding | validation | public function getRealEncoding($encoding)
{
if (static::isEncodingSupported($encoding) === false) {
throw new \Exception('Encoding is not supported: "' . $encoding . '"');
}
return static::supportedEncodings()[strtolower($encoding)];
} | php | {
"resource": ""
} |
q252305 | StringType.upperFirst | validation | public function upperFirst()
{
$this->value = mb_strtoupper(mb_substr($this->value, 0, 1, 'UTF-8'), 'UTF-8') . mb_substr($this->value, 1, null, 'UTF-8');
return $this;
} | php | {
"resource": ""
} |
q252306 | LogStyler.icon | validation | public function icon($level, $default = null)
{
if (array_key_exists($level, $this->icons)) {
return $this->icons[$level];
}
return $default;
} | php | {
"resource": ""
} |
q252307 | Query.addMethods | validation | public function addMethods($mixin, array $methods)
{
foreach ($methods as $method)
{
$this->method_map[$method] = $mixin;
}
return $this;
} | php | {
"resource": ""
} |
q252308 | Query.compileMixins | validation | protected function compileMixins()
{
$sql = array();
foreach ($this->mixins as $mixin)
{
$compiled = $this->{$mixin}->compile();
if ($compiled !== "")
{
$sql[] = $compiled;
}
}
return $sql;
} | php | {
"resource": ""
} |
q252309 | CascadeGateway.sendMessage | validation | public function sendMessage(Message $message)
{
$exceptions = [];
/** @var string $gatewayName */
/** @var GatewayInterface $gateway*/
foreach ($this->gateways as $gatewayName => $gateway) {
try {
$gateway->sendMessage($message);
return;
} catch (GatewayException $e) {
$exceptions[$gatewayName] = $e;
$this->logger->warning(
sprintf('(Cascade gateway: %s) %s', $gatewayName, $e->getMessage()),
['exception' => $e]
);
}
}
throw new CascadeGatewayException($exceptions);
} | php | {
"resource": ""
} |
q252310 | ProductStatusTransformer.getStatusData | validation | protected function getStatusData($identifier)
{
foreach ($this->options['statuses'] as $status) {
if ((int)$status['id'] === (int)$identifier) {
return $status;
}
}
return null;
} | php | {
"resource": ""
} |
q252311 | DataBuilder.setBoolean | validation | public function setBoolean(string $key, $value, bool $ignoredDefaultValue = null)
{
$this->set($key, (bool) $value, $ignoredDefaultValue);
return $this;
} | php | {
"resource": ""
} |
q252312 | DataBuilder.setInteger | validation | public function setInteger(string $key, $value, int $ignoredDefaultValue = null)
{
$this->set($key, (int) $value, $ignoredDefaultValue);
return $this;
} | php | {
"resource": ""
} |
q252313 | DataBuilder.setFloat | validation | public function setFloat(string $key, $value, float $ignoredDefaultValue = null)
{
$this->set($key, (float) $value, $ignoredDefaultValue);
return $this;
} | php | {
"resource": ""
} |
q252314 | DataBuilder.setString | validation | public function setString(string $key, $value, string $ignoredDefaultValue = null)
{
$this->set($key, (string) $value, $ignoredDefaultValue);
return $this;
} | php | {
"resource": ""
} |
q252315 | DataBuilder.setDateTime | validation | public function setDateTime(string $key, $value, string $format, string $ignoredDefaultValue = null)
{
if ($value instanceof DateTime) {
$this->set($key, $value->format($format), $ignoredDefaultValue);
}
return $this;
} | php | {
"resource": ""
} |
q252316 | DataBuilder.setArray | validation | public function setArray(string $key, $value, callable $callback = null, array $ignoredDefaultValue = null)
{
if ($value instanceof Traversable) {
$value = iterator_to_array($value);
}
if (is_array($value)) {
if (is_callable($callback)) {
$value = array_map($callback, $value);
}
$this->set($key, $value, $ignoredDefaultValue);
}
return $this;
} | php | {
"resource": ""
} |
q252317 | Client.getHttpClient | validation | public function getHttpClient()
{
if (null === $this->httpClient) {
$this->httpClient = new HttpClient();
$this->httpClient->setAdapter($this->getHttpAdapter());
}
return $this->httpClient;
} | php | {
"resource": ""
} |
q252318 | Client.getHttpAdapter | validation | public function getHttpAdapter()
{
if (null === $this->httpAdapter) {
$this->httpAdapter = new Curl();
$this->httpAdapter->setOptions(array(
'sslverifypeer' =>false,
));
}
return $this->httpAdapter;
} | php | {
"resource": ""
} |
q252319 | Tools.formatPhoneNumber | validation | public static function formatPhoneNumber($phoneNumber, $formatType = Tools::PHONE_NUMBER_FORMAT_NUMBER)
{
$formatType = (int)$formatType;
if ($formatType !== self::PHONE_NUMBER_FORMAT_INTERNATIONAL && $formatType !== self::PHONE_NUMBER_FORMAT_INTERNATIONAL_NICE &&
$formatType !== self::PHONE_NUMBER_FORMAT_NUMBER && $formatType !== self::PHONE_NUMBER_FORMAT_NICE &&
$formatType !== self::PHONE_NUMBER_FORMAT_SMSTOOLS
) {
return false;
}
if (!Validate::isPhoneNumber($phoneNumber)) {
return false;
}
$phoneNumber = self::removeSpace($phoneNumber);
$phoneLen = \strlen($phoneNumber);
if ($phoneLen > 9 && 0 !== strpos($phoneNumber, '+')) {
$phoneNumber = '+' . $phoneNumber;
$phoneLen++;
}
if ($phoneLen !== 9 && !($phoneLen >= 11 && $phoneLen <= 13 && 0 === strpos($phoneNumber, '+'))) {
return false;
}
$international = ($phoneLen !== 9);
switch ($formatType) {
case self::PHONE_NUMBER_FORMAT_INTERNATIONAL_NICE:
$formattedPhone = preg_replace(
'/^(\+\d{1,3})(\d{3})(\d{3})(\d{3})$/',
'$1 $2 $3 $4',
$international ? $phoneNumber : '+420' . $phoneNumber
);
break;
case self::PHONE_NUMBER_FORMAT_INTERNATIONAL:
$formattedPhone = $international ? $phoneNumber : '+420' . $phoneNumber;
break;
case self::PHONE_NUMBER_FORMAT_NICE:
$formattedPhone = preg_replace(
'/^(\+\d{1,3})(\d{3})(\d{3})(\d{3})$/',
'$2 $3 $4',
$international ? $phoneNumber : '+420' . $phoneNumber
);
break;
case self::PHONE_NUMBER_FORMAT_NUMBER:
$formattedPhone = $international ? substr($phoneNumber, -9) : $phoneNumber;
break;
case self::PHONE_NUMBER_FORMAT_SMSTOOLS:
$formattedPhone = $international ? trim($phoneNumber, '+') : '420' . $phoneNumber;
break;
default:
$formattedPhone = false;
}
return $formattedPhone;
} | php | {
"resource": ""
} |
q252320 | Tools.getMonthName | validation | public static function getMonthName($month)
{
if ($month < 1 || $month > 12) {
return '';
}
$monthNames = [
1 => self::poorManTranslate('fts-shared', 'January'),
2 => self::poorManTranslate('fts-shared', 'February'),
3 => self::poorManTranslate('fts-shared', 'March'),
4 => self::poorManTranslate('fts-shared', 'April'),
5 => self::poorManTranslate('fts-shared', 'May'),
6 => self::poorManTranslate('fts-shared', 'June'),
7 => self::poorManTranslate('fts-shared', 'July'),
8 => self::poorManTranslate('fts-shared', 'August'),
9 => self::poorManTranslate('fts-shared', 'September'),
10 => self::poorManTranslate('fts-shared', 'October'),
11 => self::poorManTranslate('fts-shared', 'November'),
12 => self::poorManTranslate('fts-shared', 'December'),
];
return $monthNames[$month];
} | php | {
"resource": ""
} |
q252321 | Tools.getDayName | validation | public static function getDayName($day)
{
if ($day < self::DOW_MONDAY || $day > self::DOW_SUNDAY) {
return '';
}
$dayNames = [
self::DOW_MONDAY => self::poorManTranslate('fts-shared', 'Monday'),
self::DOW_TUESDAY => self::poorManTranslate('fts-shared', 'Tuesday'),
self::DOW_WEDNESDAY => self::poorManTranslate('fts-shared', 'Wednesday'),
self::DOW_THURSDAY => self::poorManTranslate('fts-shared', 'Thursday'),
self::DOW_FRIDAY => self::poorManTranslate('fts-shared', 'Friday'),
self::DOW_SATURDAY => self::poorManTranslate('fts-shared', 'Saturday'),
self::DOW_SUNDAY => self::poorManTranslate('fts-shared', 'Sunday'),
];
return $dayNames[$day];
} | php | {
"resource": ""
} |
q252322 | Tools.GUIDv4 | validation | public static function GUIDv4()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
} | php | {
"resource": ""
} |
q252323 | Tools.GUIDv5 | validation | public static function GUIDv5($namespace, $name)
{
if (!Validate::isGuid($namespace)) {
return false;
}
$nHex = str_replace(['-', '{', '}'], '', $namespace);
$nStr = '';
$nHexLen = \strlen($nHex);
for ($i = 0; $i < $nHexLen; $i += 2) {
$nStr .= \chr(\intval($nHex[$i] . $nHex[$i + 1], 16));
}
$hash = sha1($nStr . $name);
return sprintf(
'%08s-%04s-%04x-%04x-%12s',
substr($hash, 0, 8),
substr($hash, 8, 4),
(\intval(substr($hash, 12, 4), 16) & 0x0fff) | 0x5000,
(\intval(substr($hash, 16, 4), 16) & 0x3fff) | 0x8000,
substr($hash, 20, 12)
);
} | php | {
"resource": ""
} |
q252324 | Tools.passwdGen | validation | public static function passwdGen($length = 8, $flag = 'ALPHANUMERIC')
{
switch ($flag) {
case 'NUMERIC':
$str = '0123456789';
break;
case 'ALPHA':
$str = 'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'ALPHA_LOWER':
$str = 'abcdefghijkmnopqrstuvwxyz';
break;
default:
$str = 'abcdefghijkmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
}
for ($i = 0, $passwd = ''; $i < $length; $i++) {
$passwd .= substr($str, mt_rand(0, \strlen($str) - 1), 1);
}
return $passwd;
} | php | {
"resource": ""
} |
q252325 | Tools.deleteDirectory | validation | public static function deleteDirectory($dirName, $deleteSelf = true)
{
$dirName = rtrim($dirName, '/') . '/';
if (file_exists($dirName) && $files = scandir($dirName, SCANDIR_SORT_NONE)) {
foreach ($files as $file) {
if ($file !== '.' && $file !== '..' && $file !== '.svn') {
if (is_dir($dirName . $file)) {
self::deleteDirectory($dirName . $file, true);
} elseif (file_exists($dirName . $file)) {
@chmod($dirName . $file, 0777); // NT ?
unlink($dirName . $file);
}
}
}
if ($deleteSelf && !rmdir($dirName)) {
@chmod($dirName, 0777); // NT ?
return false;
}
return true;
}
return false;
} | php | {
"resource": ""
} |
q252326 | Tools.unformatBytes | validation | public static function unformatBytes($value)
{
if (is_numeric($value)) {
return $value;
}
$value_length = strlen($value);
$qty = (int)substr($value, 0, $value_length - 1);
$unit = strtolower(substr($value, $value_length - 1));
switch ($unit) {
case 'k':
$qty *= 1024;
break;
case 'm':
$qty *= 1048576;
break;
case 'g':
$qty *= 1073741824;
break;
}
return $qty;
} | php | {
"resource": ""
} |
q252327 | Tools.getOctets | validation | public static function getOctets($option)
{
if (preg_match('/\d+k/i', $option)) {
return 1024 * (int)$option;
}
if (preg_match('/\d+m/i', $option)) {
return 1024 * 1024 * (int)$option;
}
if (preg_match('/\d+g/i', $option)) {
return 1024 * 1024 * 1024 * (int)$option;
}
return $option;
} | php | {
"resource": ""
} |
q252328 | Tools.getUserPlatform | validation | public static function getUserPlatform()
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$user_platform = 'unknown';
if (false !== stripos($user_agent, 'linux')) {
$user_platform = 'Linux';
} elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
$user_platform = 'Mac';
} elseif (preg_match('/windows|win32/i', $user_agent)) {
$user_platform = 'Windows';
}
return $user_platform;
} | php | {
"resource": ""
} |
q252329 | Tools.getUserBrowser | validation | public static function getUserBrowser()
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$user_browser = 'unknown';
if (false !== stripos($user_agent, 'MSIE') && false === stripos($user_agent, 'Opera')) {
$user_browser = 'Internet Explorer';
} elseif (false !== stripos($user_agent, 'Firefox')) {
$user_browser = 'Mozilla Firefox';
} elseif (false !== stripos($user_agent, 'Chrome')) {
$user_browser = 'Google Chrome';
} elseif (false !== stripos($user_agent, 'Safari')) {
$user_browser = 'Apple Safari';
} elseif (false !== stripos($user_agent, 'Opera')) {
$user_browser = 'Opera';
} elseif (false !== stripos($user_agent, 'Netscape')) {
$user_browser = 'Netscape';
}
return $user_browser;
} | php | {
"resource": ""
} |
q252330 | Tools.isCzechHoliday | validation | public static function isCzechHoliday($date)
{
if (!$date instanceof DateTime) {
if (\is_int($date)) {
$date = new DateTime('@' . $date);
} elseif (\is_string($date)) {
$date = new DateTime($date);
} else {
throw new RuntimeException(self::poorManTranslate('fts-shared', 'Invalid date format'));
}
}
$holidays = ['01-01', '05-01', '05-08', '07-05', '07-06', '09-28', '10-28', '11-17', '12-24', '12-25', '12-26'];
if (\in_array($date->format('m-d'), $holidays, true)) {
return true;
}
//Easter
$easterDays = easter_days($date->format('Y')); //Return number of days from base to easter sunday
$easter = new DateTime($date->format('Y') . '-03-21');
$easter->add(new \DateInterval('P' . $easterDays . 'D')); //Sunday
$easter->sub(new \DateInterval('P2D')); //Friday
if ($date->format('Y-m-d') === $easter->format('Y-m-d')) {
return true;
}
$easter->add(new \DateInterval('P3D')); //Monday
return ($easter->format('Y-m-d') === $date->format('Y-m-d'));
} | php | {
"resource": ""
} |
q252331 | Tools.getGreeting | validation | public static function getGreeting($time = null)
{
if ($time === null) {
$time = time();
} elseif (\is_string($time)) {
$time = strtotime($time);
}
switch (date('G', $time)) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return self::poorManTranslate('fts-shared', 'Good morning');
case 8:
case 9:
case 10:
case 11:
//Underscore to better translate something between morning and noon
return trim(self::poorManTranslate('fts-shared', '_Good morning'), '_');
case 12:
return self::poorManTranslate('fts-shared', 'Good noon');
case 13:
case 14:
case 15:
case 16:
return self::poorManTranslate('fts-shared', 'Good afternoon');
case 17:
case 18:
case 19:
//Underscore to better translate something between noon and evening
return trim(self::poorManTranslate('fts-shared', '_Good afternoon'), '_');
case 20:
case 21:
case 22:
case 23:
return self::poorManTranslate('fts-shared', 'Good evening');
default:
return '';
}
} | php | {
"resource": ""
} |
q252332 | Tools.gpsDistance | validation | public static function gpsDistance($lat1, $lon1, $lat2, $lon2)
{
$lat1 = deg2rad($lat1);
$lon1 = deg2rad($lon1);
$lat2 = deg2rad($lat2);
$lon2 = deg2rad($lon2);
$lonDelta = $lon2 - $lon1;
$a = ((cos($lat2) * sin($lonDelta)) ** 2) + ((cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($lonDelta)) ** 2);
$b = sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($lonDelta);
return atan2(sqrt($a), $b) * 6371.0088;
} | php | {
"resource": ""
} |
q252333 | Tools.poorManTranslate | validation | public static function poorManTranslate($category, $text, array $params = [])
{
if (class_exists('Yii')) {
return \Yii::t($category, $text, $params);
}
$pos = strrpos($category, '/');
$category = $pos === false ? $category : substr($category, $pos + 1);
$translation = @include 'messages/cs/' . $category . '.php';
if ($translation !== null && \is_array($translation) && array_key_exists($text, $translation)) {
$keys = array_keys($params);
array_walk($keys, function (&$v) {
$v = '{' . $v . '}';
});
return str_replace(array_values($params), $keys, $translation[$text]);
}
return $text;
} | php | {
"resource": ""
} |
q252334 | Tools.linkRewrite | validation | public static function linkRewrite($str, $allowUnicodeChars = false)
{
if (!\is_string($str)) {
return false;
}
$str = trim($str);
if (\function_exists('mb_strtolower')) {
$str = mb_strtolower($str, 'utf-8');
}
if (!$allowUnicodeChars) {
$str = self::replaceAccentedChars($str);
}
// Remove all non-whitelist chars.
if ($allowUnicodeChars) {
$str = preg_replace('/[^a-zA-Z0-9\s\'\:\/\[\]\-\pL]/u', '', $str);
} else {
$str = preg_replace('/[^a-zA-Z0-9\s\'\:\/\[\]\-]/', '', $str);
}
$str = preg_replace('/[\s\'\:\/\[\]\-]+/', ' ', $str);
$str = str_replace([' ', '/'], '-', $str);
// If it was not possible to lowercase the string with mb_strtolower, we do it after the transformations.
// This way we lose fewer special chars.
if (!\function_exists('mb_strtolower')) {
$str = strtolower($str);
}
return $str;
} | php | {
"resource": ""
} |
q252335 | Tools.getDateFromBirthNumber | validation | public static function getDateFromBirthNumber($no)
{
if (!preg_match('#^\s*(\d\d)(\d\d)(\d\d)[ /]*(\d\d\d)(\d?)\s*$#', $no, $matches)) {
return null;
}
list(, $year, $month, $day, $ext, $c) = $matches;
if ($c === '') {
$year += $year < 54 ? 1900 : 1800;
} else {
$mod = ($year . $month . $day . $ext) % 11;
if ($mod === 10) {
$mod = 0;
}
if ($mod !== (int)$c) {
return null;
}
$year += $year < 54 ? 2000 : 1900;
}
if ($year > 2003) {
if ($month > 70) {
$month -= 70;
}
if ($month > 20 && $month < 50) {
$month -= 20;
}
}
if ($month > 50) {
$month -= 50;
}
return new DateTime(sprintf('%04d-%02d-%02d', $year, $month, $day));
} | php | {
"resource": ""
} |
q252336 | Tools.generatePin | validation | public static function generatePin($salt, $length = 6, $useMinutes = false)
{
$seed = sha1($salt . (new \DateTime('now', new \DateTimeZone('Europe/Prague')))->format('Ymd' . ($useMinutes ? 'i' : '')), true);
for ($i = 0; $i <= (new \DateTime('now', new \DateTimeZone('Europe/Prague')))->format('G'); $i++) {
$seed = sha1($seed . $i);
}
$data = unpack('V1/V2', $seed);
$data[1] = $data[1] < 0 ? $data[1] * -1 : $data[1];
$data[2] = $data[2] < 0 ? $data[2] * -1 : $data[2];
$mask = $data[1] ^ $data[2];
if ($mask % 1000000 === 0 || $mask % 1000000 === 999999) {
return self::generatePin($salt . $seed, $length, $useMinutes);
}
return round((((float)($mask % 1000000) - 0.5 + ((float)($mask % 200) / 199)) / 999999) * (((10 ** $length) - 1) - (10 ** ($length - 1))) + (10 ** ($length - 1)));
} | php | {
"resource": ""
} |
q252337 | Tools.sendHipChatMessage | validation | public static function sendHipChatMessage($room, $token, $text, $notify = true, $format = 'text')
{
$session = curl_init();
curl_setopt($session, CURLOPT_URL, 'https://api.hipchat.com/v2/room/' . $room . '/notification?auth_token=' . $token);
curl_setopt($session, CURLOPT_POST, 1);
curl_setopt(
$session,
CURLOPT_POSTFIELDS,
http_build_query(
[
'message' => $text,
'message_format' => $format,
'notify' => $notify,
]
)
);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_exec($session);
curl_close($session);
} | php | {
"resource": ""
} |
q252338 | Tools.secondsBetweenDates | validation | public static function secondsBetweenDates($start, $end, $absolute = true, $timezone = 'Europe/Prague')
{
$timezoneObj = new \DateTimeZone($timezone);
$date = new DateTime($end, $timezoneObj);
$diff = $date->diff(new DateTime($start, $timezoneObj), $absolute);
return ($diff->invert ? -1 : 1) * (($diff->days * 86400) + ($diff->h * 3600) + ($diff->i * 60) + $diff->s);
} | php | {
"resource": ""
} |
q252339 | Tools.secondsBetweenWorkingDays | validation | public static function secondsBetweenWorkingDays($dateFrom, $dateTo, $workDayFrom, $workDayTo, $weekends = false, $holidays = false, $timeZone = 'Europe/Prague')
{
$timeZoneObj = new \DateTimeZone($timeZone);
$dateFromObj = new DateTime($dateFrom, $timeZoneObj);
$dateToObj = new DateTime($dateTo, $timeZoneObj);
$workDayFromObj = new DateTime($workDayFrom, $timeZoneObj);
$workDayToObj = new DateTime($workDayTo, $timeZoneObj);
$workDayLength = self::secondsBetweenDates($workDayFrom, $workDayTo, true, $timeZone);
$period = new \DatePeriod(
new DateTime($dateFromObj->format('Y-m-d 00:00:00'), $timeZoneObj),
new \DateInterval('P1D'),
new DateTime($dateToObj->format('Y-m-d 23:59:59'), $timeZoneObj)
);
$workedTime = 0;
foreach ($period as $date) {
/** @var DateTime $date */
if ((!$weekends && (int)$date->format('N') > 5) || (!$holidays && self::isCzechHoliday($date))) {
continue;
}
if ($date->format('Y-m-d') === $dateFromObj->format('Y-m-d')) {
//First day
$endOfDay = new DateTime($date->format('Y-m-d ' . $workDayToObj->format('H:i:s')), $timeZoneObj);
if ($dateFromObj < $endOfDay && $dateFromObj->format('Y-m-d') === $dateToObj->format('Y-m-d')) {
//Only one day - before workday end
$diff = $dateToObj->diff($dateFromObj)->format('%H:%I:%S');
} else {
$diff = $endOfDay->diff($dateFromObj)->format('%H:%I:%S');
}
$diff = explode(':', $diff);
$diff = $diff[0] * 3600 + $diff[1] * 60 + $diff[0];
$workedTime += $diff;
} elseif ($date->format('Y-m-d') === $dateToObj->format('Y-m-d')) {
//Last day
$startOfDay = new DateTime($date->format('Y-m-d ' . $workDayFromObj->format('H:i:s')), $timeZoneObj);
if ($dateToObj > $startOfDay) {
$diff = $startOfDay->diff($dateToObj)->format('%H:%I:%S');
$diff = explode(':', $diff);
$diff = $diff[0] * 3600 + $diff[1] * 60 + $diff[0];
$workedTime += $diff;
}
} else {
//Full day
$workedTime += $workDayLength;
}
}
return $workedTime;
} | php | {
"resource": ""
} |
q252340 | Tools.maxCount | validation | public static function maxCount()
{
$array = \func_get_args();
if (!\is_array($array)) {
return 0;
}
$maxCnt = 0;
foreach ($array as $item) {
if (!\is_array($item)) {
continue;
}
$cnt = \count($item);
$maxCnt = $cnt > $maxCnt ? $cnt : $maxCnt;
}
return $maxCnt;
} | php | {
"resource": ""
} |
q252341 | Tools.fillToSize | validation | public static function fillToSize(&$array, $size, $fill)
{
$cnt = \count($array);
if ($cnt >= $size) {
return;
}
$array = array_merge($array, array_fill($cnt + 1, $size - $cnt, $fill));
} | php | {
"resource": ""
} |
q252342 | Tools.countryCodeTwoToThree | validation | public static function countryCodeTwoToThree($code)
{
$codes = array_flip(self::$_countryCodes);
if (!array_key_exists($code, $codes)) {
return false;
}
return $codes[$code];
} | php | {
"resource": ""
} |
q252343 | Tools.countryCodeThreeToTwo | validation | public static function countryCodeThreeToTwo($code)
{
if (!array_key_exists($code, self::$_countryCodes)) {
return false;
}
return self::$_countryCodes[$code];
} | php | {
"resource": ""
} |
q252344 | ResultCollection.filter | validation | public function filter(ScopeInterface $scope)
{
$filtered = new self;
foreach ($this as $eachResult) {
/* @var $eachResult ResultInterface */
if ($eachResult->getScope()->isEqualTo($scope)) {
$filtered->add($eachResult);
}
}
return $filtered;
} | php | {
"resource": ""
} |
q252345 | DateTime.registerClientScript | validation | protected function registerClientScript()
{
$view = $this->getView();
DateTimePickerAssets::register($view);
$id = $this->options['id'];
$options = Json::encode($this->clientOptions);
$view->registerJs("jQuery('#$id').datetimepicker($options);");
} | php | {
"resource": ""
} |
q252346 | Select.join | validation | public function join($table, $type = null)
{
$this->join->addJoin($table, $type);
return $this;
} | php | {
"resource": ""
} |
q252347 | Select.having | validation | public function having($column, $op, $value, $isParam = true)
{
$this->having->andHaving($column, $op, $value, $isParam);
return $this;
} | php | {
"resource": ""
} |
q252348 | CachePoolThrottle.shouldThrottle | validation | public function shouldThrottle(APIRequest $request): bool
{
$item = $this->cacheItemPool->getItem($this->deriveCacheKey($request));
return $item->get() >= $this->limit;
} | php | {
"resource": ""
} |
q252349 | CachePoolThrottle.logRequest | validation | public function logRequest(APIRequest $request): void
{
$item = $this->cacheItemPool->getItem($this->deriveCacheKey($request));
if($requestCount = $item->get()) {
$item->set($requestCount + 1);
} else {
$item->set(1)->expiresAfter($this->perXSeconds);
}
$this->cacheItemPool->save($item);
} | php | {
"resource": ""
} |
q252350 | ExtensionServiceProvider.getExtensions | validation | public function getExtensions(Container $app)
{
$directories = $this->findExtensionsDirectories($app);
foreach ($directories as $directory) {
$extensionName = $directory->getRelativePathname();
$this->extensions[$extensionName]['name'] = $extensionName;
$this->extensions[$extensionName]['pathName'] = $directory->getPathName();
}
return $this->extensions;
} | php | {
"resource": ""
} |
q252351 | ExtensionServiceProvider.findExtensionsDirectories | validation | private function findExtensionsDirectories(Container $app)
{
$directories = $app['config.finder']
->ignoreUnreadableDirs()
->directories()
->name('*Extension')
->in($app['app.extensions.dir'])
->depth('< 3')
->sortByName()
;
return $directories;
} | php | {
"resource": ""
} |
q252352 | Migrator.migrate | validation | public function migrate(array $options = []): void
{
// Once we grab all of the migration files for the path, we will compare them
// against the migrations that have already been run for this package then
// run each of the outstanding migrations against a database connection.
$files = $this->getMigrationFiles(M::TYPE_UP);
$migrations = $this->pendingMigrations(
$files, $this->repository->getRan()
);
// Once we have all these migrations that are outstanding we are ready to run
// we will go ahead and run them "up". This will execute each migration as
// an operation against a database. Then we'll return this list of them.
$this->runPending($migrations, $options);
} | php | {
"resource": ""
} |
q252353 | Migrator.getMigrationFiles | validation | public function getMigrationFiles(string $type): array
{
$array = [];
foreach ($this->filesystem->listContents() as $file) {
if ($type === pathinfo($file['filename'], PATHINFO_EXTENSION)) {
$array[] = $file;
}
}
return $array;
} | php | {
"resource": ""
} |
q252354 | Migrator.runPending | validation | public function runPending(array $migrations, array $options = [])
{
// First we will just make sure that there are any migrations to run. If there
// aren't, we will just make a note of it to the developer so they're aware
// that all of the migrations have been run against this database system.
if (count($migrations) === 0) {
$this->notify->note('<info>Nothing to migrate.</info>');
return;
}
// Next, we will get the next batch number for the migrations so we can insert
// correct batch number in the database migrations repository when we store
// each migration's execution. We will also extract a few of the options.
$batch = $this->repository->getNextBatchNumber();
$step = $options['step'] ?? false;
// A blank line before top output.
$this->notify->note('');
// Once we have the array of migrations, we will spin through them and run the
// migrations "up" so the changes are made to the databases. We'll then log
// that the migration was run so we don't repeat it next time we execute.
foreach ($migrations as $file) {
$this->runUp($file, $batch);
if ($step) {
$batch++;
}
}
} | php | {
"resource": ""
} |
q252355 | Migrator.rollback | validation | public function rollback(array $options = []): void
{
// We want to pull in the last batch of migrations that ran on the previous
// migration operation. We'll then reverse those migrations and run each
// of them "down" to reverse the last migration "operation" which ran.
$migrations = $this->getMigrationsForRollback($options);
if (count($migrations) === 0) {
$this->notify->note('<info>Nothing to rollback.</info>');
return;
}
$this->rollbackMigrations($migrations);
} | php | {
"resource": ""
} |
q252356 | Migrator.reset | validation | public function reset(): void
{
// Next, we will reverse the migration list so we can run them back in the
// correct order for resetting this database. This will allow us to get
// the database back into its "empty" state ready for the migrations.
$migrations = array_reverse($this->repository->getRan());
if (count($migrations) === 0) {
$this->notify->note('<info>Nothing to rollback.</info>');
return;
}
$this->rollbackMigrations($migrations);
} | php | {
"resource": ""
} |
q252357 | Migrator.drop | validation | public function drop(): void
{
$dropped = $this->repository->drop();
if (count($dropped) === 0) {
return;
}
$this->notify->note('');
foreach ($dropped as [$type, $value]) {
$type = ucfirst($type);
$this->notify->note("<comment>{$type}</comment> \"{$value}\" <comment>dropped</comment>");
}
} | php | {
"resource": ""
} |
q252358 | Migrator.rollbackMigrations | validation | protected function rollbackMigrations(array $migrations): void
{
// A blank line before top output.
$this->notify->note('');
foreach ($this->getMigrationFiles(M::TYPE_DOWN) as $file) {
if (in_array($name = $this->getMigrationName($file), $migrations, true)) {
$this->runDown($file);
continue;
}
$this->notify->note("<fg=red>Migrate not found (in database table):</> {$name}");
}
} | php | {
"resource": ""
} |
q252359 | Migrator.runDown | validation | protected function runDown(array $file): void
{
$this->notify->note("<comment>Rolling back:</comment> {$file['basename']}");
$this->runMigration($file);
// Once we have successfully run the migration "down" we will remove it from
// the migration repository so it will be considered to have not been run
// by the application then will be able to fire by any later operation.
$this->repository->delete($this->getMigrationName($file));
$this->notify->note("<info>Rolled back:</info> {$file['basename']}");
} | php | {
"resource": ""
} |
q252360 | Migrator.runUp | validation | protected function runUp(array $file, int $batch): void
{
$this->notify->note("<comment>Migrating:</comment> {$file['basename']}");
$this->runMigration($file);
// Once we have run a migrations class, we will log that it was run in this
// repository so that we don't try to run it next time we do a migration
// in the application. A migration repository keeps the migrate order.
$this->repository->log($this->getMigrationName($file), $batch);
$this->notify->note("<info>Migrated:</info> {$file['basename']}");
} | php | {
"resource": ""
} |
q252361 | Migrator.runMigration | validation | protected function runMigration(array $file)
{
$this->repository->transaction(function (SqlMigrationRepository $repo) use ($file) {
$contents = (string) $this->filesystem->read($file['path']);
$repo->execute($contents);
});
} | php | {
"resource": ""
} |
q252362 | Migrator.pendingMigrations | validation | protected function pendingMigrations(array $files, array $ran): array
{
$array = [];
foreach ($files as $file) {
if (! in_array($this->getMigrationName($file), $ran, true)) {
$array[] = $file;
}
}
return $array;
} | php | {
"resource": ""
} |
q252363 | Neuron_GameServer_Map_MapObject.getEndLocation | validation | public function getEndLocation ()
{
$lastLocation = $this->getLocation ();
$lastDate = NOW;
foreach ($this->movements as $v)
{
if ($v->getEndTime () > $lastDate)
{
$lastDate = $v->getEndTime ();
$lastLocation = $v->getEndLocation ();
}
}
return $lastLocation;
} | php | {
"resource": ""
} |
q252364 | Neuron_GameServer_Map_MapObject.getUp | validation | public function getUp ($time = NOW)
{
// Go trough the paths to update
foreach ($this->movements as $v)
{
if ($v->isActive ($time))
{
$up = $v->getCurrentUp ($time);
if (isset ($up))
{
return $v->getCurrentUp ($time);
}
}
}
return new Neuron_GameServer_Map_Vector3 (0, 1, 0);
} | php | {
"resource": ""
} |
q252365 | NotifyFactory.create | validation | public static function create($notify)
{
switch (true) {
case $notify === NotifyInterface::STDOUT:
return new NotifyStdout();
case $notify === NotifyInterface::LOGGER:
return new NotifyLogger(PrettyLogger::create());
case $notify === NotifyInterface::BLACKHOLE:
return new NotifyBlackhole();
case $notify instanceof Output:
return new NotifyConsole($notify);
case $notify instanceof LoggerInterface:
return new NotifyLogger($notify);
default:
throw InvalidArgumentException::forNotSupportedNotifier();
}
} | php | {
"resource": ""
} |
q252366 | SettingController.index | validation | public function index(Request $request)
{
$this->settingRepository->pushCriteria(new RequestCriteria($request));
$settings = $this->settingRepository->all();
$dateFormats = DateFormatter::dropdownArray();
return view('l5starter::admin.settings.index')->with([
'dateFormats' => $dateFormats,
'settings' => $settings,
]);
} | php | {
"resource": ""
} |
q252367 | SettingController.update | validation | public function update(Request $request)
{
foreach ($request->all() as $key => $value) {
if (substr($key, 0, 8) == 'setting_') {
$skipSave = false;
$key = substr($key, 8);
if (! $skipSave) {
$this->settingRepository->save($key, $value);
}
}
}
Flash::success(trans('l5starter::messages.update.success'));
return redirect(route('admin.settings.index'));
} | php | {
"resource": ""
} |
q252368 | Mailer.renderView | validation | protected function renderView($view, $data)
{
try {
return parent::renderView($view, $data);
} catch (\InvalidArgumentException $e) {
return static::applyDataToView($view, $data);
}
} | php | {
"resource": ""
} |
q252369 | DatabaseBuilder.getClassName | validation | protected function getClassName($fileName)
{
// Get rid of prefix
$namePiece = @explode($this->config['modelsPrefix'], $fileName);
$name = isset($namePiece[1]) ? $namePiece[1] : $fileName;
// Get rid of postfix
$namePiece = @explode($this->config['modelsPostfix'], $name);
$name = isset($namePiece[1]) ? $namePiece[0] : $name;
// Get rid of .php
$namePiece = explode('.php', $name);
$name = isset($namePiece[1]) ? $namePiece[0] : $name;
return $name;
} | php | {
"resource": ""
} |
q252370 | DefaultFormatter.stringize | validation | protected function stringize(array &$arguments)
{
array_walk($arguments, function (&$value) {
if (is_object($value)) {
$value = get_class($value);
} elseif (is_scalar($value)) {
$value = (string) $value;
} else {
$value = json_encode($value, 0);
}
});
return $this;
} | php | {
"resource": ""
} |
q252371 | DefaultFormatter.matchTemplate | validation | protected function matchTemplate(
/*# string */ &$template,
array &$arguments
)/*# : string */ {
$count = substr_count($template, '%s');
$size = sizeof($arguments);
if ($count > $size) {
$arguments = $arguments + array_fill($size, $count - $size, '');
} else {
$template .= str_repeat(' %s', $size - $count);
}
return $this;
} | php | {
"resource": ""
} |
q252372 | Framework.getRootBackslash | validation | public static function getRootBackslash($pathname) {
// Remove leading slash if necessary.
if($pathname[0] == '\\') {
$pathname = substr($pathname, 1);
}
// Create array from path
$arr = explode('\\', $pathname);
// If a pathname was given (as opposed to just a filename like "myFile.php")
// Return the first part of it. Otherwise just return nothing for root.
if (count($arr) > 1) {
return $arr[0];
}
return '';
} | php | {
"resource": ""
} |
q252373 | Db_MySQL.exec | validation | public function exec()
{
// If there's a custom query to execute, do that instead of building one.
if ($this->customQuery) {
return $this->execCustom();
}
// Save copy of relevant data so we can calculate the total rows of this query
// Does not save LIMIT as this is for use with pagination.
$this->last_wheres = $this->wheres;
$this->last_distinct = $this->distinct;
$this->last_ins = $this->ins;
$this->last_groupBys = $this->groupBys;
$this->last_havings = $this->havings;
$this->last_joins = $this->joins;
// Execute this query
$this->calculate();
try {
$result = $this->db->query($this->query);
}
catch (\PDOException $e) {
if ($this->config['mode'] == 'development') {
echo $this->getQuery();
}
$this->reset();
throw $e;
}
$this->reset();
// Return Result
$dbResult = new Db_MySQLResult($result, $this->db);
return $dbResult;
} | php | {
"resource": ""
} |
q252374 | Db_MySQL.calculate | validation | protected function calculate()
{
// Determine Action
$action = false;
$actions = 0;
if($this->delete) {
$actions += 1;
$action = 'DELETE';
}
if(!empty($this->inserts)) {
$actions += 1;
$action = 'INSERT';
}
if(!empty($this->updates)) {
$actions += 1;
$action = 'UPDATE';
}
if(!empty($this->selects)) {
$actions += 1;
$action = 'SELECT';
}
if(!empty($this->create)) {
$actions += 1;
$action = 'CREATE';
}
if ($actions > 1) {
throw new \Exception("More than one query action specified! When using Cora's query builder class, only one type of query (select, update, delete, insert) can be done at a time.");
}
else {
$calcMethod = 'calculate'.$action;
$this->$calcMethod();
}
} | php | {
"resource": ""
} |
q252375 | Db_MySQL.calculateSELECT | validation | protected function calculateSELECT()
{
$this->query .= 'SELECT ';
// If distinct
if ($this->distinct) {
$this->query .= ' DISTINCT ';
}
// If SELECT
$this->queryStringFromArray('selects', '', ', ');
// Determine Table(s)
$this->queryStringFromArray('tables', ' FROM ', ', ');
// Join
$this->joinStringFromArray('joins');
// Where and IN
$this->conditionStringFromArray('wheres', ' WHERE ', ' AND ');
// GroupBy
$this->queryStringFromArray('groupBys', ' GROUP BY ', ', ');
// Having
$this->conditionStringFromArray('havings', ' HAVING ', ' AND ');
// OrderBy
$this->queryStringFromArray('orderBys', ' ORDER BY ', ', ', false);
// Limit
if ($this->limit) {
$this->query .= ' LIMIT '.$this->limit;
}
// Offset
if ($this->offset) {
$this->query .= ' OFFSET '.$this->offset;
}
} | php | {
"resource": ""
} |
q252376 | Db_MySQL.calculateUPDATE | validation | protected function calculateUPDATE()
{
$this->query .= 'UPDATE ';
// Determine Table(s)
$this->queryStringFromArray('tables', '', ', ');
// SETs
$this->queryStringFromArray('updates', ' SET ', ', ');
// Where and IN
$this->conditionStringFromArray('wheres', ' WHERE ', ' AND ');
// OrderBy
$this->queryStringFromArray('orderBys', ' ORDER BY ', ', ', false);
// Limit
if ($this->limit) {
$this->query .= ' LIMIT '.$this->limit;
}
//echo $this->query.'<br><br>';
} | php | {
"resource": ""
} |
q252377 | Db_MySQL.calculateINSERT | validation | protected function calculateINSERT()
{
$this->query .= 'INSERT INTO ';
// Determine Table(s)
$this->queryStringFromArray('tables', '', ', ');
// SETs
if (!empty($this->inserts)) {
$this->query .= ' (';
$this->queryStringFromArray('inserts', '', ', ');
$this->query .= ')';
}
// Values
$this->valueStringFromArray('values', ' VALUES ', ', ');
} | php | {
"resource": ""
} |
q252378 | Db_MySQL.calculateDELETE | validation | protected function calculateDELETE()
{
$this->query .= 'DELETE FROM ';
// Determine Table(s)
$this->queryStringFromArray('tables', '', ', ');
// Where and IN
$this->conditionStringFromArray('wheres', ' WHERE ', ' AND ');
// OrderBy
$this->queryStringFromArray('orderBys', ' ORDER BY ', ', ', false);
// Limit
if ($this->limit) {
$this->query .= ' LIMIT '.$this->limit;
}
} | php | {
"resource": ""
} |
q252379 | Db_MySQL.calculateCREATE | validation | protected function calculateCREATE()
{
$this->query .= 'CREATE TABLE IF NOT EXISTS ';
$this->query .= $this->create.' (';
$this->queryStringFromArray('fields', '', ', ', false, true);
$this->primaryKeyStringFromArray('primaryKeys', ', CONSTRAINT ');
$this->foreignKeyStringFromArray('foreignKeys', ', CONSTRAINT ');
$this->indexStringFromArray('indexes', ', INDEX ');
$this->query .= ')';
} | php | {
"resource": ""
} |
q252380 | Db_MySQL.getSetItem | validation | protected function getSetItem($dataMember, $offset, $quote = true)
{
$item = $this->{$dataMember}[$offset];
switch ($item[1]) {
case 'varchar':
$type = 'varchar(255)';
break;
default:
$type = $item[1];
}
$this->{$dataMember}[$offset][1] = $type;
return $this->getArrayItem($dataMember, $offset, $quote);
} | php | {
"resource": ""
} |
q252381 | Db_MySQL.joinStringFromArray | validation | protected function joinStringFromArray($dataMember, $sep = ' AND ')
{
if (empty($this->$dataMember)) {
return 0;
}
$count = count($this->$dataMember);
//var_dump($this->$dataMember);
for($i=0; $i<$count; $i++) {
$statement = $this->{$dataMember}[$i];
$this->query .= ' '.$statement[2].' JOIN '.$statement[0].' ON ';
$sCount = count($statement[1]);
for($j=0; $j<$sCount; $j++) {
$this->query .= $this->getArrayJoin($dataMember, $i, $j);
if ($sCount-1 != $j) {
$this->query .= $sep;
}
}
}
} | php | {
"resource": ""
} |
q252382 | Db_MySQL.getType | validation | public function getType($props)
{
$result = '';
if (isset($props['type'])) {
// If field is a string
if ($props['type'] == 'varchar' || $props['type'] == 'string') {
if (isset($props['size'])) {
$result = 'varchar('.$props['size'].')';
}
else {
$result = 'varchar(255)';
}
}
// If field is an Int
else if ($props['type'] == 'int' || $props['type'] == 'integer') {
if (isset($props['size'])) {
$result = 'int('.$props['size'].')';
}
else {
$result = 'int';
}
}
// If field is a float
else if ($props['type'] == 'float' || $props['type'] == 'double') {
if (isset($props['size']) && isset($props['precision'])) {
$result = 'float('.$props['size'].', '.$props['precision'].')';
}
else {
$result = 'float';
}
}
// If field is a date
else if ($props['type'] == 'date') {
$result = 'date';
}
// If field is a datetime
else if ($props['type'] == 'datetime') {
$result = 'datetime';
}
// If field is an enum
else if ($props['type'] == 'enum') {
if (isset($props['enum'])) {
$result = 'ENUM('.$props['enum'].')';
}
else {
$result = "ENUM('default')";
}
}
// If nothing matches, just try returning what was set.
else {
if (isset($props['size'])) {
$result = $props['type'].'('.$props['size'].')';
}
else {
$result = $props['type'];
}
}
}
else {
return 'varchar(255)';
}
return $result;
} | php | {
"resource": ""
} |
q252383 | Db_MySQL.getAttributes | validation | public function getAttributes($props)
{
$attr = '';
if (isset($props['primaryKey'])) {
$attr .= 'NOT NULL AUTO_INCREMENT ';
}
if (isset($props['defaultValue'])) {
$attr .= "DEFAULT '".$props['defaultValue']."'";
}
return $attr;
} | php | {
"resource": ""
} |
q252384 | Parser.run | validation | public function run()
{
$list = $this->getClassList();
$directCollection = new DirectCollection();
foreach ($list as $class) {
$cl = $this->processClass($class);
if ($cl !== false) {
$directCollection->add($cl);
}
}
return $directCollection;
} | php | {
"resource": ""
} |
q252385 | Parser.processClass | validation | protected function processClass($class)
{
if (!class_exists('\\' . $class)) {
throw new ExtDirectException(" '{$class}' does not exist!");
}
$annotationReader = new AnnotationReader();
AnnotationRegistry::registerLoader('class_exists');
$reflectionClass = new ReflectionClass($class);
$classAnnotation = $annotationReader->getClassAnnotation($reflectionClass, 'ExtDirect\Annotations\Direct');
if ($classAnnotation instanceof \ExtDirect\Annotations\Direct) {
$classAnnotation->setClassName($class);
$methodCollection = new RemotableCollection();
foreach ($reflectionClass->getMethods() as $reflectionMethod) {
$methodAnnotation = $annotationReader->getMethodAnnotation($reflectionMethod, 'ExtDirect\Annotations\Remotable');
if ($methodAnnotation instanceof \ExtDirect\Annotations\Remotable) {
$methodAnnotation->setMethodName($reflectionMethod->getName());
$methodCollection->add($methodAnnotation);
}
}
$classAnnotation->setMethods($methodCollection);
return $classAnnotation;
}
return false;
} | php | {
"resource": ""
} |
q252386 | Parser.scanDir | validation | protected function scanDir($dir)
{
$result = array();
$list = $this->scanDirExec($dir);
foreach ($list as $element) {
$elementPath = $dir . DIRECTORY_SEPARATOR . $element;
if (is_file($elementPath)) {
$fileInfo = pathinfo($element);
if (in_array($fileInfo['extension'], $this->getAllowedFileExtensions())) {
$result[] = $this->getNameSpace() . "\\" . $fileInfo['filename'];
}
}
}
return $result;
} | php | {
"resource": ""
} |
q252387 | Neuron_GameServer_Map_Managers_MapObjectManager.move | validation | public function move
(
Neuron_GameServer_Map_MapObject $object,
Neuron_GameServer_Map_Location $location,
Neuron_GameServer_Map_Date $start,
Neuron_GameServer_Map_Date $end
)
{
throw new Neuron_Exceptions_NotImplemented ("The move method is not implemented in this map.");
} | php | {
"resource": ""
} |
q252388 | Neuron_GameServer_Map_Managers_MapObjectManager.getFromLocation | validation | public function getFromLocation (Neuron_GameServer_Map_Location $location)
{
$area = new Neuron_GameServer_Map_Area ($location, 1);
$objects = $this->getDisplayObjects ($area);
$out = array ();
foreach ($objects as $v)
{
if ($v->getLocation ()->equals ($location))
{
$out[] = $v;
}
}
return $out;
} | php | {
"resource": ""
} |
q252389 | Neuron_GameServer_Map_Managers_MapObjectManager.getMultipleDisplayObjects | validation | public function getMultipleDisplayObjects ($areas)
{
$out = array ();
foreach ($areas as $v)
{
if (! ($v instanceof Neuron_GameServer_Map_Area))
{
throw new Neuron_Exceptions_InvalidParameter ("Parameters must be an array of area objects.");
}
foreach ($this->getDisplayObjects ($v) as $v)
{
if (! $v instanceof Neuron_GameServer_Map_MapObject)
{
throw new Neuron_Core_Error ("All map objects MUST implement Neuron_GameServer_Map_MapObject");
}
$out[] = $v;
}
}
return $out;
} | php | {
"resource": ""
} |
q252390 | ExtDirect.process | validation | protected function process(array $requestParams)
{
$request = new ExtDirectRequest($this->useCache(), $this->getApplicationPath(), $this->getApplicationNameSpace());
$response = new ExtDirectResponse();
$requestParameters = new Parameters();
try {
// parameter validation here
$request->setApplicationPath($this->getApplicationPath());
$requestParameters->setParameters($requestParams);
// inject parameters instance into request and response object to get access to all relevant params
$request->injectParameters($requestParameters);
$response->injectParameters($requestParameters);
$request->injectResponse($response);
$request->setParamMethod($this->getParamMethod());
$request->setMethodCalls($this->getMethodsToCall());
$request->run();
} catch (ExtDirectApplicationException $e) {
$result = $e->getResponse();
if (!empty($result)) {
$response->setResult(array("success" => false, "message" => $e->getMessage(), "actions" => $result));
} else {
$response->setResult(array("success" => false, "message" => $e->getMessage()));
}
} catch (\Exception $e) {
$response->setResult(array("success" => false, "message" => $e->getMessage()));
}
return $response;
} | php | {
"resource": ""
} |
q252391 | ExtDirect.setCacheState | validation | protected function setCacheState($useCache)
{
if (is_bool($useCache)) {
$this->useCache = $useCache;
} else {
// every invalid param would activate cache
$this->useCache = true;
}
} | php | {
"resource": ""
} |
q252392 | ExtDirect.getApi | validation | public function getApi()
{
if ($this->api === null) {
$this->api = new ExtDirectApi($this->useCache(), $this->getApplicationPath(), $this->getApplicationNameSpace());
}
return $this->api;
} | php | {
"resource": ""
} |
q252393 | Parameters.setParameters | validation | public function setParameters(array $request)
{
foreach ($this->getRequiredParameters() as $param) {
if (isset($request[$param])) {
// build setter method
$dynamicMethod = "set" . ucfirst($param);
if (method_exists($this, $dynamicMethod)) {
$this->$dynamicMethod($request[$param]);
} else {
throw new ExtDirectException("Method for required parameter '{$param}' not implemented");
}
} else {
throw new ExtDirectException("Required parameter '{$param}' is missing");
}
}
} | php | {
"resource": ""
} |
q252394 | Randomizer.getBoolean | validation | public function getBoolean($probability = 0.5)
{
if ((\is_int($probability) || \is_float($probability)) === false
|| $probability < 0
|| $probability > 1
) {
throw new InvalidArgumentException('Invalid probability');
}
if ($probability == 0) {
$result = false;
} else {
$random = $this->generator->getFloat(0, 1);
$result = ($probability >= $random);
}
return $result;
} | php | {
"resource": ""
} |
q252395 | Randomizer.getArrayKeyByPowers | validation | public function getArrayKeyByPowers(array $powers)
{
if (empty($powers)) {
throw new InvalidArgumentException('Empty powers set');
}
$powersSum = 0;
foreach ($powers as $power) {
if ($power < 0) {
throw new InvalidArgumentException('Negative power found');
}
$powersSum += $power;
}
if ($powersSum <= 0) {
throw new InvalidArgumentException('The sum of powers must be positive');
}
$randomValue = $this->generator->getFloat(0, $powersSum);
$currentSum = 0;
$result = null;
foreach ($powers as $key => $power) {
$currentSum += $power;
if ($currentSum >= $randomValue) {
$result = $key;
break;
}
}
return $key;
} | php | {
"resource": ""
} |
q252396 | Randomizer.getValueByPowers | validation | public function getValueByPowers(array $values, array $powers)
{
if (empty($values)
|| empty($powers)
|| \count($values) !== \count($powers)
) {
throw new InvalidArgumentException('Empty parameter or count not equal');
}
// reindex arrays
$values = \array_values($values);
$powers = \array_values($powers);
$rolledIndex = $this->getArrayKeyByPowers($powers);
return $values[$rolledIndex];
} | php | {
"resource": ""
} |
q252397 | Randomizer.getArrayValue | validation | public function getArrayValue(array $values)
{
if (empty($values)) {
throw new InvalidArgumentException('Empty parameter');
}
// reindex array
$values = \array_values($values);
return $values[$this->generator->getInt(0, count($values) - 1)];
} | php | {
"resource": ""
} |
q252398 | Plugin.handleUrl | validation | public function handleUrl($url, Event $event, Queue $queue)
{
$logger = $this->getLogger();
$logger->info('handleUrl', array('url' => $url));
$v = $this->getVideoId($url);
$logger->info('getVideoId', array('url' => $url, 'v' => $v));
if (!$v) {
return;
}
$apiUrl = $this->getApiUrl($v);
$request = $this->getApiRequest($apiUrl, $event, $queue);
$this->getEventEmitter()->emit('http.request', array($request));
} | php | {
"resource": ""
} |
q252399 | Plugin.getVideoId | validation | protected function getVideoId($url)
{
$logger = $this->getLogger();
$parsed = parse_url($url);
$logger->debug('getVideoId', array('url' => $url, 'parsed' => $parsed));
switch ($parsed['host']) {
case 'youtu.be':
return ltrim($parsed['path'], '/');
case 'www.youtube.com':
case 'youtube.com':
if (!empty($parsed['query'])) {
parse_str($parsed['query'], $query);
$logger->debug('getVideoId', array('url' => $url, 'query' => $query));
if (!empty($query['v'])) {
return $query['v'];
}
} elseif (isset($parsed['path']) && substr($parsed['path'], 0, 7) == '/embed/') {
$logger->debug('getVideoId', array('url' => $url, 'path' => $parsed['path']));
$vId = substr($parsed['path'], 7);
if (!empty($vId)) {
return $vId;
}
}
}
return null;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.