_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q254800
Config.get
test
public static function get(string $name, bool $getShared = true) { $class = $name; if (($pos = strrpos($name, '\\')) !== false) { $class = substr($name, $pos + 1); } if (! $getShared) { return self::createClass($name); } if (! isset( self::$instances[$class] )) { self::$instances[$class] = self::createClass($name); } return self::$instances[$class]; }
php
{ "resource": "" }
q254801
Config.createClass
test
private static function createClass(string $name) { if (class_exists($name)) { return new $name(); } $locator = Services::locator(); $file = $locator->locateFile($name, 'Config'); if (empty($file)) { return null; } $name = $locator->getClassname($file); if (empty($name)) { return null; } return new $name(); }
php
{ "resource": "" }
q254802
BaseService.getSharedInstance
test
protected static function getSharedInstance(string $key, ...$params) { // Returns mock if exists if (isset(static::$mocks[$key])) { return static::$mocks[$key]; } if (! isset(static::$instances[$key])) { // Make sure $getShared is false array_push($params, false); static::$instances[$key] = static::$key(...$params); } return static::$instances[$key]; }
php
{ "resource": "" }
q254803
BaseService.autoloader
test
public static function autoloader(bool $getShared = true) { if ($getShared) { if (empty(static::$instances['autoloader'])) { static::$instances['autoloader'] = new Autoloader(); } return static::$instances['autoloader']; } return new Autoloader(); }
php
{ "resource": "" }
q254804
BaseService.locator
test
public static function locator(bool $getShared = true) { if ($getShared) { if (empty(static::$instances['locator'])) { static::$instances['locator'] = new FileLocator( static::autoloader() ); } return static::$instances['locator']; } return new FileLocator(static::autoloader()); }
php
{ "resource": "" }
q254805
BaseService.reset
test
public static function reset(bool $init_autoloader = false) { static::$mocks = []; static::$instances = []; if ($init_autoloader) { static::autoloader()->initialize(new Autoload(), new Modules()); } }
php
{ "resource": "" }
q254806
BaseService.injectMock
test
public static function injectMock(string $name, $mock) { $name = strtolower($name); static::$mocks[$name] = $mock; }
php
{ "resource": "" }
q254807
BaseService.discoverServices
test
protected static function discoverServices(string $name, array $arguments) { if (! static::$discovered) { $config = config('Modules'); if ($config->shouldDiscover('services')) { $locator = static::locator(); $files = $locator->search('Config/Services'); if (empty($files)) { // no files at all found - this would be really, really bad return null; } // Get instances of all service classes and cache them locally. foreach ($files as $file) { $classname = $locator->getClassname($file); if (! in_array($classname, ['CodeIgniter\\Config\\Services'])) { static::$services[] = new $classname(); } } } static::$discovered = true; } if (! static::$services) { // we found stuff, but no services - this would be really bad return null; } // Try to find the desired service method foreach (static::$services as $class) { if (method_exists(get_class($class), $name)) { return $class::$name(...$arguments); } } return null; }
php
{ "resource": "" }
q254808
CLI.input
test
public static function input(string $prefix = null): string { if (static::$readline_support) { return readline($prefix); } echo $prefix; return fgets(STDIN); }
php
{ "resource": "" }
q254809
CLI.prompt
test
public static function prompt(string $field, $options = null, string $validation = null): string { $extra_output = ''; $default = ''; if (is_string($options)) { $extra_output = ' [' . static::color($options, 'white') . ']'; $default = $options; } if (is_array($options) && $options) { $opts = $options; $extra_output_default = static::color($opts[0], 'white'); unset($opts[0]); if (empty($opts)) { $extra_output = $extra_output_default; } else { $extra_output = ' [' . $extra_output_default . ', ' . implode(', ', $opts) . ']'; $validation .= '|in_list[' . implode(',', $options) . ']'; $validation = trim($validation, '|'); } $default = $options[0]; } fwrite(STDOUT, $field . $extra_output . ': '); // Read the input from keyboard. $input = trim(static::input()) ?: $default; if (isset($validation)) { while (! static::validate($field, $input, $validation)) { $input = static::prompt($field, $options, $validation); } } return empty($input) ? '' : $input; }
php
{ "resource": "" }
q254810
CLI.validate
test
protected static function validate(string $field, string $value, string $rules): bool { $validation = \Config\Services::validation(null, false); $validation->setRule($field, null, $rules); $validation->run([$field => $value]); if ($validation->hasError($field)) { static::error($validation->getError($field)); return false; } return true; }
php
{ "resource": "" }
q254811
CLI.print
test
public static function print(string $text = '', string $foreground = null, string $background = null) { if ($foreground || $background) { $text = static::color($text, $foreground, $background); } static::$lastWrite = null; fwrite(STDOUT, $text); }
php
{ "resource": "" }
q254812
CLI.error
test
public static function error(string $text, string $foreground = 'light_red', string $background = null) { if ($foreground || $background) { $text = static::color($text, $foreground, $background); } fwrite(STDERR, $text . PHP_EOL); }
php
{ "resource": "" }
q254813
CLI.wait
test
public static function wait(int $seconds, bool $countdown = false) { if ($countdown === true) { $time = $seconds; while ($time > 0) { fwrite(STDOUT, $time . '... '); sleep(1); $time --; } static::write(); } else { if ($seconds > 0) { sleep($seconds); } else { // this chunk cannot be tested because of keyboard input // @codeCoverageIgnoreStart static::write(static::$wait_msg); static::input(); // @codeCoverageIgnoreEnd } } }
php
{ "resource": "" }
q254814
CLI.color
test
public static function color(string $text, string $foreground, string $background = null, string $format = null): string { if (static::isWindows() && ! isset($_SERVER['ANSICON'])) { // @codeCoverageIgnoreStart return $text; // @codeCoverageIgnoreEnd } if (! array_key_exists($foreground, static::$foreground_colors)) { throw CLIException::forInvalidColor('foreground', $foreground); } if ($background !== null && ! array_key_exists($background, static::$background_colors)) { throw CLIException::forInvalidColor('background', $background); } $string = "\033[" . static::$foreground_colors[$foreground] . 'm'; if ($background !== null) { $string .= "\033[" . static::$background_colors[$background] . 'm'; } if ($format === 'underline') { $string .= "\033[4m"; } $string .= $text . "\033[0m"; return $string; }
php
{ "resource": "" }
q254815
CLI.wrap
test
public static function wrap(string $string = null, int $max = 0, int $pad_left = 0): string { if (empty($string)) { return ''; } if ($max === 0) { $max = CLI::getWidth(); } if (CLI::getWidth() < $max) { $max = CLI::getWidth(); } $max = $max - $pad_left; $lines = wordwrap($string, $max); if ($pad_left > 0) { $lines = explode(PHP_EOL, $lines); $first = true; array_walk($lines, function (&$line, $index) use ($pad_left, &$first) { if (! $first) { $line = str_repeat(' ', $pad_left) . $line; } else { $first = false; } }); $lines = implode(PHP_EOL, $lines); } return $lines; }
php
{ "resource": "" }
q254816
CLI.getOption
test
public static function getOption(string $name) { if (! array_key_exists($name, static::$options)) { return null; } // If the option didn't have a value, simply return TRUE // so they know it was set, otherwise return the actual value. $val = static::$options[$name] === null ? true : static::$options[$name]; return $val; }
php
{ "resource": "" }
q254817
CLI.table
test
public static function table(array $tbody, array $thead = []) { // All the rows in the table will be here until the end $table_rows = []; // We need only indexes and not keys if (! empty($thead)) { $table_rows[] = array_values($thead); } foreach ($tbody as $tr) { $table_rows[] = array_values($tr); } // Yes, it really is necessary to know this count $total_rows = count($table_rows); // Store all columns lengths // $all_cols_lengths[row][column] = length $all_cols_lengths = []; // Store maximum lengths by column // $max_cols_lengths[column] = length $max_cols_lengths = []; // Read row by row and define the longest columns for ($row = 0; $row < $total_rows; $row ++) { $column = 0; // Current column index foreach ($table_rows[$row] as $col) { // Sets the size of this column in the current row $all_cols_lengths[$row][$column] = static::strlen($col); // If the current column does not have a value among the larger ones // or the value of this is greater than the existing one // then, now, this assumes the maximum length if (! isset($max_cols_lengths[$column]) || $all_cols_lengths[$row][$column] > $max_cols_lengths[$column]) { $max_cols_lengths[$column] = $all_cols_lengths[$row][$column]; } // We can go check the size of the next column... $column ++; } } // Read row by row and add spaces at the end of the columns // to match the exact column length for ($row = 0; $row < $total_rows; $row ++) { $column = 0; foreach ($table_rows[$row] as $col) { $diff = $max_cols_lengths[$column] - static::strlen($col); if ($diff) { $table_rows[$row][$column] = $table_rows[$row][$column] . str_repeat(' ', $diff); } $column ++; } } $table = ''; // Joins columns and append the well formatted rows to the table for ($row = 0; $row < $total_rows; $row ++) { // Set the table border-top if ($row === 0) { $cols = '+'; foreach ($table_rows[$row] as $col) { $cols .= str_repeat('-', static::strlen($col) + 2) . '+'; } $table .= $cols . PHP_EOL; } // Set the columns borders $table .= '| ' . implode(' | ', $table_rows[$row]) . ' |' . PHP_EOL; // Set the thead and table borders-bottom if ($row === 0 && ! empty($thead) || $row + 1 === $total_rows) { $table .= $cols . PHP_EOL; } } fwrite(STDOUT, $table); }
php
{ "resource": "" }
q254818
ResponseTrait.respond
test
public function respond($data = null, int $status = null, string $message = '') { // If data is null and status code not provided, exit and bail if ($data === null && $status === null) { $status = 404; // Create the output var here in case of $this->response([]); $output = null; } // If data is null but status provided, keep the output empty. elseif ($data === null && is_numeric($status)) { $output = null; } else { $status = empty($status) ? 200 : $status; $output = $this->format($data); } return $this->response->setBody($output) ->setStatusCode($status, $message); }
php
{ "resource": "" }
q254819
ResponseTrait.fail
test
public function fail($messages, int $status = 400, string $code = null, string $customMessage = '') { if (! is_array($messages)) { $messages = ['error' => $messages]; } $response = [ 'status' => $status, 'error' => $code === null ? $status : $code, 'messages' => $messages, ]; return $this->respond($response, $status, $customMessage); }
php
{ "resource": "" }
q254820
ResponseTrait.respondCreated
test
public function respondCreated($data = null, string $message = '') { return $this->respond($data, $this->codes['created'], $message); }
php
{ "resource": "" }
q254821
ResponseTrait.respondDeleted
test
public function respondDeleted($data = null, string $message = '') { return $this->respond($data, $this->codes['deleted'], $message); }
php
{ "resource": "" }
q254822
ResponseTrait.failUnauthorized
test
public function failUnauthorized(string $description = 'Unauthorized', string $code = null, string $message = '') { return $this->fail($description, $this->codes['unauthorized'], $code, $message); }
php
{ "resource": "" }
q254823
ResponseTrait.failServerError
test
public function failServerError(string $description = 'Internal Server Error', string $code = null, string $message = ''): Response { return $this->fail($description, $this->codes['server_error'], $code, $message); }
php
{ "resource": "" }
q254824
CSRF.before
test
public function before(RequestInterface $request) { if ($request->isCLI()) { return; } $security = Services::security(); try { $security->CSRFVerify($request); } catch (SecurityException $e) { if (config('App')->CSRFRedirect && ! $request->isAJAX()) { return redirect()->back()->with('error', $e->getMessage()); } throw $e; } }
php
{ "resource": "" }
q254825
Events.initialize
test
public static function initialize() { // Don't overwrite anything.... if (static::$initialized) { return; } $config = config('Modules'); $files = [APPPATH . 'Config/Events.php']; if ($config->shouldDiscover('events')) { $locator = Services::locator(); $files = $locator->search('Config/Events.php'); } static::$files = $files; foreach (static::$files as $file) { if (is_file($file)) { include $file; } } static::$initialized = true; }
php
{ "resource": "" }
q254826
Events.listeners
test
public static function listeners($event_name): array { if (! isset(static::$listeners[$event_name])) { return []; } // The list is not sorted if (! static::$listeners[$event_name][0]) { // Sort it! array_multisort(static::$listeners[$event_name][1], SORT_NUMERIC, static::$listeners[$event_name][2]); // Mark it as sorted already! static::$listeners[$event_name][0] = true; } return static::$listeners[$event_name][2]; }
php
{ "resource": "" }
q254827
Events.removeListener
test
public static function removeListener($event_name, callable $listener): bool { if (! isset(static::$listeners[$event_name])) { return false; } foreach (static::$listeners[$event_name][2] as $index => $check) { if ($check === $listener) { unset(static::$listeners[$event_name][1][$index]); unset(static::$listeners[$event_name][2][$index]); return true; } } return false; }
php
{ "resource": "" }
q254828
UserAgent.isReferral
test
public function isReferral(): bool { if (! isset($this->referrer)) { if (empty($_SERVER['HTTP_REFERER'])) { $this->referrer = false; } else { $referer_host = @parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); $own_host = parse_url(\base_url(), PHP_URL_HOST); $this->referrer = ($referer_host && $referer_host !== $own_host); } } return $this->referrer; }
php
{ "resource": "" }
q254829
UserAgent.setPlatform
test
protected function setPlatform(): bool { if (is_array($this->config->platforms) && $this->config->platforms) { foreach ($this->config->platforms as $key => $val) { if (preg_match('|' . preg_quote($key) . '|i', $this->agent)) { $this->platform = $val; return true; } } } $this->platform = 'Unknown Platform'; return false; }
php
{ "resource": "" }
q254830
UserAgent.setBrowser
test
protected function setBrowser(): bool { if (is_array($this->config->browsers) && $this->config->browsers) { foreach ($this->config->browsers as $key => $val) { if (preg_match('|' . $key . '.*?([0-9\.]+)|i', $this->agent, $match)) { $this->isBrowser = true; $this->version = $match[1]; $this->browser = $val; $this->setMobile(); return true; } } } return false; }
php
{ "resource": "" }
q254831
UserAgent.setRobot
test
protected function setRobot(): bool { if (is_array($this->config->robots) && $this->config->robots) { foreach ($this->config->robots as $key => $val) { if (preg_match('|' . preg_quote($key) . '|i', $this->agent)) { $this->isRobot = true; $this->robot = $val; $this->setMobile(); return true; } } } return false; }
php
{ "resource": "" }
q254832
UserAgent.setMobile
test
protected function setMobile(): bool { if (is_array($this->config->mobiles) && $this->config->mobiles) { foreach ($this->config->mobiles as $key => $val) { if (false !== (stripos($this->agent, $key))) { $this->isMobile = true; $this->mobile = $val; return true; } } } return false; }
php
{ "resource": "" }
q254833
Forge._attributeType
test
protected function _attributeType(array &$attributes) { // Reset field lengths for data types that don't support it if (isset($attributes['CONSTRAINT']) && stripos($attributes['TYPE'], 'int') !== false) { $attributes['CONSTRAINT'] = null; } switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = false; break; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = false; break; case 'DATETIME': $attributes['TYPE'] = 'TIMESTAMP'; break; default: break; } }
php
{ "resource": "" }
q254834
Kernel.initializeConfig
test
private function initializeConfig() { if (!is_dir($this->vbot->config['path'])) { mkdir($this->vbot->config['path'], 0755, true); } $this->vbot->config['storage'] = $this->vbot->config['storage'] ?: 'collection'; $this->vbot->config['path'] = realpath($this->vbot->config['path']); }
php
{ "resource": "" }
q254835
QrCode.show
test
public function show($text) { if (!array_get($this->config, 'qrcode', true)) { return false; } $output = new ConsoleOutput(); static::initQrcodeStyle($output); $pxMap[0] = Console::isWin() ? '<whitec>mm</whitec>' : '<whitec> </whitec>'; $pxMap[1] = '<blackc> </blackc>'; $text = QrCodeConsole::text($text); $length = strlen($text[0]); $output->write("\n"); foreach ($text as $line) { $output->write($pxMap[0]); for ($i = 0; $i < $length; $i++) { $type = substr($line, $i, 1); $output->write($pxMap[$type]); } $output->writeln($pxMap[0]); } }
php
{ "resource": "" }
q254836
QrCode.initQrcodeStyle
test
private static function initQrcodeStyle(OutputInterface $output) { $style = new OutputFormatterStyle('black', 'black', ['bold']); $output->getFormatter()->setStyle('blackc', $style); $style = new OutputFormatterStyle('white', 'white', ['bold']); $output->getFormatter()->setStyle('whitec', $style); }
php
{ "resource": "" }
q254837
Content.formatContent
test
public static function formatContent($content) { $content = self::emojiHandle($content); $content = self::replaceBr($content); return self::htmlDecode($content); }
php
{ "resource": "" }
q254838
MessageHandler.heartbeat
test
private function heartbeat($time) { if (time() - $time > 1800) { Text::send('filehelper', 'heart beat '.Carbon::now()->toDateTimeString()); return time(); } return $time; }
php
{ "resource": "" }
q254839
MessageHandler.handleCheckSync
test
public function handleCheckSync($retCode, $selector, $test = false) { if (in_array($retCode, [1100, 1101, 1102, 1205])) { // 微信客户端上登出或者其他设备登录 $this->vbot->console->log('vbot exit normally.'); $this->vbot->cache->forget('session.'.$this->vbot->config['session']); return false; } elseif ($retCode != 0) { $this->vbot->needActivateObserver->trigger(); } else { if (!$test) { $this->handleMessage($selector); } return true; } }
php
{ "resource": "" }
q254840
MessageHandler.log
test
private function log($message) { if ($this->vbot->messageLog && ($message['ModContactList'] || $message['AddMsgList'])) { $this->vbot->messageLog->info(json_encode($message)); } }
php
{ "resource": "" }
q254841
Server.getUuid
test
protected function getUuid() { $content = $this->vbot->http->get('https://login.weixin.qq.com/jslogin', ['query' => [ 'appid' => 'wx782c26e4c19acffb', 'fun' => 'new', 'lang' => 'zh_CN', '_' => time(), ]]); preg_match('/window.QRLogin.code = (\d+); window.QRLogin.uuid = \"(\S+?)\"/', $content, $matches); if (!$matches) { throw new FetchUuidException('fetch uuid failed.'); } $this->vbot->config['server.uuid'] = $matches[2]; }
php
{ "resource": "" }
q254842
Server.showQrCode
test
public function showQrCode() { $url = 'https://login.weixin.qq.com/l/'.$this->vbot->config['server.uuid']; $this->vbot->qrCodeObserver->trigger($url); $this->vbot->qrCode->show($url); }
php
{ "resource": "" }
q254843
Server.waitForLogin
test
protected function waitForLogin() { $retryTime = 10; $tip = 1; $this->vbot->console->log('please scan the qrCode with wechat.'); while ($retryTime > 0) { $url = sprintf('https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s', $tip, $this->vbot->config['server.uuid'], time()); $content = $this->vbot->http->get($url, ['timeout' => 35]); preg_match('/window.code=(\d+);/', $content, $matches); $code = $matches[1]; switch ($code) { case '201': $this->vbot->console->log('please confirm login in wechat.'); $tip = 0; break; case '200': preg_match('/window.redirect_uri="(https:\/\/(\S+?)\/\S+?)";/', $content, $matches); $this->vbot->config['server.uri.redirect'] = $matches[1].'&fun=new'; $url = 'https://%s/cgi-bin/mmwebwx-bin'; $this->vbot->config['server.uri.file'] = sprintf($url, 'file.'.$matches[2]); $this->vbot->config['server.uri.push'] = sprintf($url, 'webpush.'.$matches[2]); $this->vbot->config['server.uri.base'] = sprintf($url, $matches[2]); return; case '408': $tip = 1; $retryTime -= 1; sleep(1); break; default: $tip = 1; $retryTime -= 1; sleep(1); break; } } $this->vbot->console->log('login time out!', Console::ERROR); throw new LoginTimeoutException('Login time out.'); }
php
{ "resource": "" }
q254844
Server.getLogin
test
private function getLogin() { $content = $this->vbot->http->get($this->vbot->config['server.uri.redirect']); $data = (array) simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA); $this->vbot->config['server.skey'] = $data['skey']; $this->vbot->config['server.sid'] = $data['wxsid']; $this->vbot->config['server.uin'] = $data['wxuin']; $this->vbot->config['server.passTicket'] = $data['pass_ticket']; if (in_array('', [$data['wxsid'], $data['wxuin'], $data['pass_ticket']])) { throw new LoginFailedException('Login failed.'); } $this->vbot->config['server.deviceId'] = 'e'.substr(mt_rand().mt_rand(), 1, 15); $this->vbot->config['server.baseRequest'] = [ 'Uin' => $data['wxuin'], 'Sid' => $data['wxsid'], 'Skey' => $data['skey'], 'DeviceID' => $this->vbot->config['server.deviceId'], ]; $this->saveServer(); }
php
{ "resource": "" }
q254845
Server.saveServer
test
private function saveServer() { $this->vbot->cache->forever('session.'.$this->vbot->config['session'], json_encode($this->vbot->config['server'])); }
php
{ "resource": "" }
q254846
Server.beforeInitSuccess
test
private function beforeInitSuccess() { $this->vbot->console->log('current session: '.$this->vbot->config['session']); $this->vbot->console->log('init begin.'); }
php
{ "resource": "" }
q254847
Server.afterInitSuccess
test
private function afterInitSuccess($content) { $this->vbot->log->info('response:'.json_encode($content)); $this->vbot->console->log('init success.'); $this->vbot->loginSuccessObserver->trigger(); $this->vbot->console->log('init contacts begin.'); }
php
{ "resource": "" }
q254848
Server.statusNotify
test
protected function statusNotify() { $url = sprintf($this->vbot->config['server.uri.base'].'/webwxstatusnotify?lang=zh_CN&pass_ticket=%s', $this->vbot->config['server.passTicket']); $this->vbot->http->json($url, [ 'BaseRequest' => $this->vbot->config['server.baseRequest'], 'Code' => 3, 'FromUserName' => $this->vbot->myself->username, 'ToUserName' => $this->vbot->myself->username, 'ClientMsgId' => time(), ]); }
php
{ "resource": "" }
q254849
Multimedia.download
test
public static function download($message, $callback = null) { if (!$callback) { static::autoDownload($message['raw'], true); return true; } if ($callback && !is_callable($callback)) { throw new ArgumentException(); } call_user_func_array($callback, [static::getResource($message['raw'])]); return true; }
php
{ "resource": "" }
q254850
Multimedia.getResource
test
private static function getResource($message) { $url = static::getDownloadUrl($message); $content = vbot('http')->get($url, static::getDownloadOption($message)); if (!$content) { vbot('console')->log('download file failed.', Console::WARNING); } else { return $content; } }
php
{ "resource": "" }
q254851
Multimedia.autoDownload
test
protected static function autoDownload($message, $force = false) { $isDownload = vbot('config')['download.'.static::TYPE]; if ($isDownload || $force) { $resource = static::getResource($message); if ($resource) { File::saveTo(vbot('config')['user_path'].static::TYPE.DIRECTORY_SEPARATOR. static::fileName($message), $resource); } } }
php
{ "resource": "" }
q254852
Sync.checkSync
test
public function checkSync() { $content = $this->vbot->http->get($this->vbot->config['server.uri.push'].'/synccheck', ['timeout' => 35, 'query' => [ 'r' => time(), 'sid' => $this->vbot->config['server.sid'], 'uin' => $this->vbot->config['server.uin'], 'skey' => $this->vbot->config['server.skey'], 'deviceid' => $this->vbot->config['server.deviceId'], 'synckey' => $this->vbot->config['server.syncKeyStr'], '_' => time(), ]]); if (!$content) { $this->vbot->console->log('checkSync no response'); return false; } return preg_match('/window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}/', $content, $matches) ? [$matches[1], $matches[2]] : false; }
php
{ "resource": "" }
q254853
Sync.sync
test
public function sync() { $url = sprintf($this->vbot->config['server.uri.base'].'/webwxsync?sid=%s&skey=%s&lang=zh_CN&pass_ticket=%s', $this->vbot->config['server.sid'], $this->vbot->config['server.skey'], $this->vbot->config['server.passTicket'] ); $result = $this->vbot->http->json($url, [ 'BaseRequest' => $this->vbot->config['server.baseRequest'], 'SyncKey' => $this->vbot->config['server.syncKey'], 'rr' => ~time(), ], true); if ($result && $result['BaseResponse']['Ret'] == 0) { $this->generateSyncKey($result); } return $result; }
php
{ "resource": "" }
q254854
Sync.generateSyncKey
test
public function generateSyncKey($result) { $this->vbot->config['server.syncKey'] = $result['SyncKey']; $syncKey = []; if (is_array($this->vbot->config['server.syncKey.List'])) { foreach ($this->vbot->config['server.syncKey.List'] as $item) { $syncKey[] = $item['Key'].'_'.$item['Val']; } } $this->vbot->config['server.syncKeyStr'] = implode('|', $syncKey); }
php
{ "resource": "" }
q254855
Console.log
test
public function log($str, $level = 'INFO', $log = false) { if ($this->isOutput()) { if ($log && in_array($level, array_keys(Logger::getLevels()))) { $this->vbot->log->log($level, $str); } echo '['.Carbon::now()->toDateTimeString().']'."[{$level}] ".$str.PHP_EOL; } }
php
{ "resource": "" }
q254856
Console.message
test
public function message($str) { if (array_get($this->config, 'message', true)) { $this->log($str, self::MESSAGE); } }
php
{ "resource": "" }
q254857
Text.send
test
public static function send($username, $word) { if (!$word || !$username) { return false; } return static::sendMsg([ 'Type' => 1, 'Content' => $word, 'FromUserName' => vbot('myself')->username, 'ToUserName' => $username, 'LocalID' => time() * 1e4, 'ClientMsgId' => time() * 1e4, ]); }
php
{ "resource": "" }
q254858
ContactFactory.fetchAllContacts
test
public function fetchAllContacts($seq = 0) { $url = sprintf($this->vbot->config['server.uri.base'].'/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s&seq=%s', $this->vbot->config['server.passTicket'], $this->vbot->config['server.skey'], time(), $seq ); $result = $this->vbot->http->json($url, [], true, ['timeout' => 60]); if (isset($result['MemberList']) && $result['MemberList']) { $this->store($result['MemberList']); } if (isset($result['Seq']) && $result['Seq'] != 0) { $this->fetchAllContacts($result['Seq']); } }
php
{ "resource": "" }
q254859
ContactFactory.store
test
public function store($memberList) { foreach ($memberList as $contact) { if (in_array($contact['UserName'], static::SPECIAL_USERS)) { $this->vbot->specials->put($contact['UserName'], $contact); } elseif ($this->vbot->officials->isOfficial($contact['VerifyFlag'])) { $this->vbot->officials->put($contact['UserName'], $contact); } elseif (strstr($contact['UserName'], '@@') !== false) { $this->vbot->groups->put($contact['UserName'], $contact); } else { $this->vbot->friends->put($contact['UserName'], $contact); } } }
php
{ "resource": "" }
q254860
ContactFactory.fetchGroupMembers
test
public function fetchGroupMembers() { $url = sprintf($this->vbot->config['server.uri.base'].'/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s', time(), $this->vbot->config['server.passTicket'] ); $list = []; $this->vbot->groups->each(function ($item, $key) use (&$list) { $list[] = ['UserName' => $key, 'EncryChatRoomId' => '']; }); $content = $this->vbot->http->json($url, [ 'BaseRequest' => $this->vbot->config['server.baseRequest'], 'Count' => $this->vbot->groups->count(), 'List' => $list, ], true, ['timeout' => 60]); $this->storeMembers($content); }
php
{ "resource": "" }
q254861
ContactFactory.storeMembers
test
private function storeMembers($array) { if (isset($array['ContactList']) && $array['ContactList']) { foreach ($array['ContactList'] as $group) { $groupAccount = $this->vbot->groups->get($group['UserName']); $groupAccount['MemberList'] = $group['MemberList']; $groupAccount['ChatRoomId'] = $group['EncryChatRoomId']; $this->vbot->groups->put($group['UserName'], $groupAccount); foreach ($group['MemberList'] as $member) { $this->vbot->members->put($member['UserName'], $member); } } } }
php
{ "resource": "" }
q254862
ExceptionHandler.report
test
public function report(Exception $e) { if ($this->shouldntReport($e)) { return true; } if ($this->handler) { call_user_func_array($this->handler, [$e]); } }
php
{ "resource": "" }
q254863
ExceptionHandler.throwFatalException
test
private function throwFatalException(Throwable $e) { foreach ($this->fatalException as $exception) { if ($e instanceof $exception) { throw $e; } } }
php
{ "resource": "" }
q254864
OpenSSL.validateKey
test
private function validateKey($key): void { if (! is_resource($key)) { throw new InvalidArgumentException( 'It was not possible to parse your key, reason: ' . openssl_error_string() ); } $details = openssl_pkey_get_details($key); assert(is_array($details)); if (! isset($details['key']) || $details['type'] !== $this->getKeyType()) { throw new InvalidArgumentException('This key is not compatible with this signer'); } }
php
{ "resource": "" }
q254865
Parser.splitJwt
test
private function splitJwt(string $jwt): array { $data = explode('.', $jwt); if (count($data) !== 3) { throw new InvalidArgumentException('The JWT string must have two dots'); } return $data; }
php
{ "resource": "" }
q254866
Parser.parseHeader
test
private function parseHeader(string $data): array { $header = $this->decoder->jsonDecode($this->decoder->base64UrlDecode($data)); if (! is_array($header)) { throw new InvalidArgumentException('Headers must be an array'); } if (isset($header['enc'])) { throw new InvalidArgumentException('Encryption is not supported yet'); } if (! isset($header['typ'])) { throw new InvalidArgumentException('The header "typ" must be present'); } return $header; }
php
{ "resource": "" }
q254867
Parser.parseClaims
test
private function parseClaims(string $data): array { $claims = $this->decoder->jsonDecode($this->decoder->base64UrlDecode($data)); if (! is_array($claims)) { throw new InvalidArgumentException('Claims must be an array'); } if (isset($claims[RegisteredClaims::AUDIENCE])) { $claims[RegisteredClaims::AUDIENCE] = (array) $claims[RegisteredClaims::AUDIENCE]; } foreach (array_intersect(RegisteredClaims::DATE_CLAIMS, array_keys($claims)) as $claim) { $claims[$claim] = $this->convertDate((string) $claims[$claim]); } return $claims; }
php
{ "resource": "" }
q254868
Parser.parseSignature
test
private function parseSignature(array $header, string $data): Signature { if ($data === '' || ! isset($header['alg']) || $header['alg'] === 'none') { return Signature::fromEmptyData(); } $hash = $this->decoder->base64UrlDecode($data); return new Signature($hash, $data); }
php
{ "resource": "" }
q254869
LanguageNegotiator.negotiateLanguage
test
public function negotiateLanguage() { $matches = $this->getMatchesFromAcceptedLanguages(); foreach ($matches as $key => $q) { $key = ($this->configRepository->get('laravellocalization.localesMapping')[$key]) ?? $key; if (!empty($this->supportedLanguages[$key])) { return $key; } if ($this->use_intl) { $key = Locale::canonicalize($key); } // Search for acceptable locale by 'regional' => 'af_ZA' or 'lang' => 'af-ZA' match. foreach ( $this->supportedLanguages as $key_supported => $locale ) { if ( (isset($locale['regional']) && $locale['regional'] == $key) || (isset($locale['lang']) && $locale['lang'] == $key) ) { return $key_supported; } } } // If any (i.e. "*") is acceptable, return the first supported format if (isset($matches['*'])) { reset($this->supportedLanguages); return key($this->supportedLanguages); } if ($this->use_intl && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $http_accept_language = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); if (!empty($this->supportedLanguages[$http_accept_language])) { return $http_accept_language; } } if ($this->request->server('REMOTE_HOST')) { $remote_host = explode('.', $this->request->server('REMOTE_HOST')); $lang = strtolower(end($remote_host)); if (!empty($this->supportedLanguages[$lang])) { return $lang; } } return $this->defaultLocale; }
php
{ "resource": "" }
q254870
LanguageNegotiator.getMatchesFromAcceptedLanguages
test
private function getMatchesFromAcceptedLanguages() { $matches = []; if ($acceptLanguages = $this->request->header('Accept-Language')) { $acceptLanguages = explode(',', $acceptLanguages); $generic_matches = []; foreach ($acceptLanguages as $option) { $option = array_map('trim', explode(';', $option)); $l = $option[0]; if (isset($option[1])) { $q = (float) str_replace('q=', '', $option[1]); } else { $q = null; // Assign default low weight for generic values if ($l == '*/*') { $q = 0.01; } elseif (substr($l, -1) == '*') { $q = 0.02; } } // Unweighted values, get high weight by their position in the // list $q = $q ?? 1000 - \count($matches); $matches[$l] = $q; //If for some reason the Accept-Language header only sends language with country //we should make the language without country an accepted option, with a value //less than it's parent. $l_ops = explode('-', $l); array_pop($l_ops); while (!empty($l_ops)) { //The new generic option needs to be slightly less important than it's base $q -= 0.001; $op = implode('-', $l_ops); if (empty($generic_matches[$op]) || $generic_matches[$op] > $q) { $generic_matches[$op] = $q; } array_pop($l_ops); } } $matches = array_merge($generic_matches, $matches); arsort($matches, SORT_NUMERIC); } return $matches; }
php
{ "resource": "" }
q254871
RouteTranslationsCacheCommand.cacheRoutesPerLocale
test
protected function cacheRoutesPerLocale() { // Store the default routes cache, // this way the Application will detect that routes are cached. $allLocales = $this->getSupportedLocales(); array_push($allLocales, null); foreach ($allLocales as $locale) { $routes = $this->getFreshApplicationRoutes($locale); if (count($routes) == 0) { $this->error("Your application doesn't have any routes."); return; } foreach ($routes as $route) { $route->prepareForSerialization(); } $this->files->put( $this->makeLocaleRoutesPath($locale), $this->buildRouteCacheFile($routes) ); } }
php
{ "resource": "" }
q254872
RouteTranslationsCacheCommand.buildRouteCacheFile
test
protected function buildRouteCacheFile(RouteCollection $routes) { $stub = $this->files->get( realpath( __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'routes.stub' ) ); return str_replace( [ '{{routes}}', '{{translatedRoutes}}', ], [ base64_encode(serialize($routes)), $this->getLaravelLocalization()->getSerializedTranslatedRoutes(), ], $stub ); }
php
{ "resource": "" }
q254873
LaravelLocalizationServiceProvider.registerBindings
test
protected function registerBindings() { $this->app->singleton(LaravelLocalization::class, function () { return new LaravelLocalization(); }); $this->app->alias(LaravelLocalization::class, 'laravellocalization'); }
php
{ "resource": "" }
q254874
LaravelLocalizationServiceProvider.registerCommands
test
protected function registerCommands() { $this->app->singleton('laravellocalizationroutecache.cache', Commands\RouteTranslationsCacheCommand::class); $this->app->singleton('laravellocalizationroutecache.clear', Commands\RouteTranslationsClearCommand::class); $this->app->singleton('laravellocalizationroutecache.list', Commands\RouteTranslationsListCommand::class); $this->commands([ 'laravellocalizationroutecache.cache', 'laravellocalizationroutecache.clear', 'laravellocalizationroutecache.list', ]); }
php
{ "resource": "" }
q254875
LaravelLocalization.setLocale
test
public function setLocale($locale = null) { if (empty($locale) || !\is_string($locale)) { // If the locale has not been passed through the function // it tries to get it from the first segment of the url $locale = $this->request->segment(1); // If the locale is determined by env, use that // Note that this is how per-locale route caching is performed. if ( ! $locale) { $locale = $this->getForcedLocale(); } } if (!empty($this->supportedLocales[$locale])) { $this->currentLocale = $locale; } else { // if the first segment/locale passed is not valid // the system would ask which locale have to take // it could be taken by the browser // depending on your configuration $locale = null; // if we reached this point and hideDefaultLocaleInURL is true // we have to assume we are routing to a defaultLocale route. if ($this->hideDefaultLocaleInURL()) { $this->currentLocale = $this->defaultLocale; } // but if hideDefaultLocaleInURL is false, we have // to retrieve it from the browser... else { $this->currentLocale = $this->getCurrentLocale(); } } $this->app->setLocale($this->currentLocale); // Regional locale such as de_DE, so formatLocalized works in Carbon $regional = $this->getCurrentLocaleRegional(); $suffix = $this->configRepository->get('laravellocalization.utf8suffix'); if ($regional) { setlocale(LC_TIME, $regional . $suffix); setlocale(LC_MONETARY, $regional . $suffix); } return $locale; }
php
{ "resource": "" }
q254876
LaravelLocalization.getURLFromRouteNameTranslated
test
public function getURLFromRouteNameTranslated($locale, $transKeyName, $attributes = [], $forceDefaultLocation = false) { if (!$this->checkLocaleInSupportedLocales($locale)) { throw new UnsupportedLocaleException('Locale \''.$locale.'\' is not in the list of supported locales.'); } if (!\is_string($locale)) { $locale = $this->getDefaultLocale(); } $route = ''; if ($forceDefaultLocation || !($locale === $this->defaultLocale && $this->hideDefaultLocaleInURL())) { $route = '/'.$locale; } if (\is_string($locale) && $this->translator->has($transKeyName, $locale)) { $translation = $this->translator->trans($transKeyName, [], $locale); $route .= '/'.$translation; $route = $this->substituteAttributesInRoute($attributes, $route); } if (empty($route)) { // This locale does not have any key for this route name return false; } return rtrim($this->createUrlFromUri($route), '/'); }
php
{ "resource": "" }
q254877
LaravelLocalization.getSupportedLocales
test
public function getSupportedLocales() { if (!empty($this->supportedLocales)) { return $this->supportedLocales; } $locales = $this->configRepository->get('laravellocalization.supportedLocales'); if (empty($locales) || !\is_array($locales)) { throw new SupportedLocalesNotDefined(); } $this->supportedLocales = $locales; return $locales; }
php
{ "resource": "" }
q254878
LaravelLocalization.getLocalesOrder
test
public function getLocalesOrder() { $locales = $this->getSupportedLocales(); $order = $this->configRepository->get('laravellocalization.localesOrder'); uksort($locales, function ($a, $b) use ($order) { $pos_a = array_search($a, $order); $pos_b = array_search($b, $order); return $pos_a - $pos_b; }); return $locales; }
php
{ "resource": "" }
q254879
LaravelLocalization.getCurrentLocaleDirection
test
public function getCurrentLocaleDirection() { if (!empty($this->supportedLocales[$this->getCurrentLocale()]['dir'])) { return $this->supportedLocales[$this->getCurrentLocale()]['dir']; } switch ($this->getCurrentLocaleScript()) { // Other (historic) RTL scripts exist, but this list contains the only ones in current use. case 'Arab': case 'Hebr': case 'Mong': case 'Tfng': case 'Thaa': return 'rtl'; default: return 'ltr'; } }
php
{ "resource": "" }
q254880
LaravelLocalization.getCurrentLocale
test
public function getCurrentLocale() { if ($this->currentLocale) { return $this->currentLocale; } if ($this->useAcceptLanguageHeader() && !$this->app->runningInConsole()) { $negotiator = new LanguageNegotiator($this->defaultLocale, $this->getSupportedLocales(), $this->request); return $negotiator->negotiateLanguage(); } // or get application default language return $this->configRepository->get('app.locale'); }
php
{ "resource": "" }
q254881
LaravelLocalization.getCurrentLocaleRegional
test
public function getCurrentLocaleRegional() { // need to check if it exists, since 'regional' has been added // after version 1.0.11 and existing users will not have it if (isset($this->supportedLocales[$this->getCurrentLocale()]['regional'])) { return $this->supportedLocales[$this->getCurrentLocale()]['regional']; } else { return; } }
php
{ "resource": "" }
q254882
LaravelLocalization.checkLocaleInSupportedLocales
test
public function checkLocaleInSupportedLocales($locale) { $locales = $this->getSupportedLocales(); if ($locale !== false && empty($locales[$locale])) { return false; } return true; }
php
{ "resource": "" }
q254883
LaravelLocalization.getRouteNameFromAPath
test
public function getRouteNameFromAPath($path) { $attributes = $this->extractAttributes($path); $path = parse_url($path)['path']; $path = trim(str_replace('/'.$this->currentLocale.'/', '', $path), "/"); foreach ($this->translatedRoutes as $route) { if (trim($this->substituteAttributesInRoute($attributes, $this->translator->trans($route)), '/') === $path) { return $route; } } return false; }
php
{ "resource": "" }
q254884
LaravelLocalization.findTranslatedRouteByPath
test
protected function findTranslatedRouteByPath($path, $url_locale) { // check if this url is a translated url foreach ($this->translatedRoutes as $translatedRoute) { if ($this->translator->trans($translatedRoute, [], $url_locale) == rawurldecode($path)) { return $translatedRoute; } } return false; }
php
{ "resource": "" }
q254885
LaravelLocalization.findTranslatedRouteByUrl
test
protected function findTranslatedRouteByUrl($url, $attributes, $locale) { if (empty($url)) { return false; } if (isset($this->cachedTranslatedRoutesByUrl[$locale][$url])) { return $this->cachedTranslatedRoutesByUrl[$locale][$url]; } // check if this url is a translated url foreach ($this->translatedRoutes as $translatedRoute) { $routeName = $this->getURLFromRouteNameTranslated($locale, $translatedRoute, $attributes); // We can ignore extra url parts and compare only their url_path (ignore arguments that are not attributes) if (parse_url($this->getNonLocalizedURL($routeName), PHP_URL_PATH) == parse_url($this->getNonLocalizedURL($url), PHP_URL_PATH)) { $this->cachedTranslatedRoutesByUrl[$locale][$url] = $translatedRoute; return $translatedRoute; } } return false; }
php
{ "resource": "" }
q254886
LaravelLocalization.createUrlFromUri
test
public function createUrlFromUri($uri) { $uri = ltrim($uri, '/'); if (empty($this->baseUrl)) { return app('url')->to($uri); } return $this->baseUrl.$uri; }
php
{ "resource": "" }
q254887
LaravelLocalization.normalizeAttributes
test
protected function normalizeAttributes($attributes) { if (array_key_exists('data', $attributes) && \is_array($attributes['data']) && ! \count($attributes['data'])) { $attributes['data'] = null; return $attributes; } return $attributes; }
php
{ "resource": "" }
q254888
LoadsTranslatedCachedRoutes.loadCachedRoutes
test
protected function loadCachedRoutes() { $localization = $this->getLaravelLocalization(); $localization->setLocale(); $locale = $localization->getCurrentLocale(); $localeKeys = $localization->getSupportedLanguagesKeys(); // First, try to load the routes specifically cached for this locale // if they do not exist, write a warning to the log and load the default // routes instead. Note that this is guaranteed to exist, because the // 'cached routes' check in the Application checks its existence. $path = $this->makeLocaleRoutesPath($locale, $localeKeys); if ( ! file_exists($path)) { Log::warning("Routes cached, but no cached routes found for locale '{$locale}'!"); $path = $this->getDefaultCachedRoutePath(); } $this->app->booted(function () use ($path) { require $path; }); }
php
{ "resource": "" }
q254889
LoadsTranslatedCachedRoutes.makeLocaleRoutesPath
test
protected function makeLocaleRoutesPath($locale, $localeKeys) { $path = $this->getDefaultCachedRoutePath(); $localeSegment = request()->segment(1); if ( ! $localeSegment || ! in_array($localeSegment, $localeKeys)) { return $path; } return substr($path, 0, -4) . '_' . $locale . '.php'; }
php
{ "resource": "" }
q254890
Produce.encodeMessageSet
test
protected function encodeMessageSet(array $messages, int $compression = self::COMPRESSION_NONE): string { $data = ''; $next = 0; foreach ($messages as $message) { $encodedMessage = $this->encodeMessage($message); $data .= self::pack(self::BIT_B64, (string) $next) . self::encodeString($encodedMessage, self::PACK_INT32); ++$next; } if ($compression === self::COMPRESSION_NONE) { return $data; } return self::pack(self::BIT_B64, '0') . self::encodeString($this->encodeMessage($data, $compression), self::PACK_INT32); }
php
{ "resource": "" }
q254891
Produce.encodeProducePartition
test
protected function encodeProducePartition(array $values, int $compression): string { if (! isset($values['partition_id'])) { throw new ProtocolException('given produce data invalid. `partition_id` is undefined.'); } if (! isset($values['messages']) || empty($values['messages'])) { throw new ProtocolException('given produce data invalid. `messages` is undefined.'); } $data = self::pack(self::BIT_B32, (string) $values['partition_id']); $data .= self::encodeString( $this->encodeMessageSet((array) $values['messages'], $compression), self::PACK_INT32 ); return $data; }
php
{ "resource": "" }
q254892
Produce.encodeProduceTopic
test
protected function encodeProduceTopic(array $values, int $compression): string { if (! isset($values['topic_name'])) { throw new ProtocolException('given produce data invalid. `topic_name` is undefined.'); } if (! isset($values['partitions']) || empty($values['partitions'])) { throw new ProtocolException('given produce data invalid. `partitions` is undefined.'); } $topic = self::encodeString($values['topic_name'], self::PACK_INT16); $partitions = self::encodeArray($values['partitions'], [$this, 'encodeProducePartition'], $compression); return $topic . $partitions; }
php
{ "resource": "" }
q254893
Produce.produceTopicPair
test
protected function produceTopicPair(string $data, int $version): array { $offset = 0; $topicInfo = $this->decodeString($data, self::BIT_B16); $offset += $topicInfo['length']; $ret = $this->decodeArray(substr($data, $offset), [$this, 'producePartitionPair'], $version); $offset += $ret['length']; return [ 'length' => $offset, 'data' => [ 'topicName' => $topicInfo['data'], 'partitions' => $ret['data'], ], ]; }
php
{ "resource": "" }
q254894
Produce.producePartitionPair
test
protected function producePartitionPair(string $data, int $version): array { $offset = 0; $partitionId = self::unpack(self::BIT_B32, substr($data, $offset, 4)); $offset += 4; $errorCode = self::unpack(self::BIT_B16_SIGNED, substr($data, $offset, 2)); $offset += 2; $partitionOffset = self::unpack(self::BIT_B64, substr($data, $offset, 8)); $offset += 8; $timestamp = 0; if ($version === self::API_VERSION2) { $timestamp = self::unpack(self::BIT_B64, substr($data, $offset, 8)); $offset += 8; } return [ 'length' => $offset, 'data' => [ 'partition' => $partitionId, 'errorCode' => $errorCode, 'offset' => $offset, 'timestamp' => $timestamp, ], ]; }
php
{ "resource": "" }
q254895
Fetch.decodeMessageSet
test
protected function decodeMessageSet(string $data): ?array { if (strlen($data) <= 12) { return null; } $offset = 0; $roffset = self::unpack(self::BIT_B64, substr($data, $offset, 8)); $offset += 8; $messageSize = self::unpack(self::BIT_B32, substr($data, $offset, 4)); $offset += 4; $ret = $this->decodeMessage(substr($data, $offset), $messageSize); if ($ret === null) { return null; } $offset += $ret['length']; return [ 'length' => $offset, 'data' => [ 'offset' => $roffset, 'size' => $messageSize, 'message' => $ret['data'], ], ]; }
php
{ "resource": "" }
q254896
Fetch.decodeMessage
test
protected function decodeMessage(string $data, int $messageSize): ?array { if ($messageSize === 0 || strlen($data) < $messageSize) { return null; } $offset = 0; $crc = self::unpack(self::BIT_B32, substr($data, $offset, 4)); $offset += 4; $magic = self::unpack(self::BIT_B8, substr($data, $offset, 1)); ++$offset; $attr = self::unpack(self::BIT_B8, substr($data, $offset, 1)); ++$offset; $timestamp = 0; $backOffset = $offset; try { // try unpack message format v1, falling back to v0 if it fails if ($magic >= self::MESSAGE_MAGIC_VERSION1) { $timestamp = self::unpack(self::BIT_B64, substr($data, $offset, 8)); $offset += 8; } $keyRet = $this->decodeString(substr($data, $offset), self::BIT_B32); $offset += $keyRet['length']; $valueRet = $this->decodeString((string) substr($data, $offset), self::BIT_B32, $attr & Produce::COMPRESSION_CODEC_MASK); $offset += $valueRet['length']; if ($offset !== $messageSize) { throw new Exception( 'pack message fail, message len:' . $messageSize . ' , data unpack offset :' . $offset ); } } catch (Exception $e) { // try unpack message format v0 $offset = $backOffset; $timestamp = 0; $keyRet = $this->decodeString(substr($data, $offset), self::BIT_B32); $offset += $keyRet['length']; $valueRet = $this->decodeString(substr($data, $offset), self::BIT_B32); $offset += $valueRet['length']; } return [ 'length' => $offset, 'data' => [ 'crc' => $crc, 'magic' => $magic, 'attr' => $attr, 'timestamp' => $timestamp, 'key' => $keyRet['data'], 'value' => $valueRet['data'], ], ]; }
php
{ "resource": "" }
q254897
CommonSocket.createSocket
test
protected function createSocket(string $remoteSocket, $context, ?int &$errno, ?string &$errstr) { return stream_socket_client( $remoteSocket, $errno, $errstr, $this->sendTimeoutSec + ($this->sendTimeoutUsec / 1000000), STREAM_CLIENT_CONNECT, $context ); }
php
{ "resource": "" }
q254898
CommonSocket.select
test
protected function select(array $sockets, int $timeoutSec, int $timeoutUsec, bool $isRead = true) { $null = null; if ($isRead) { return @stream_select($sockets, $null, $null, $timeoutSec, $timeoutUsec); } return @stream_select($null, $sockets, $null, $timeoutSec, $timeoutUsec); }
php
{ "resource": "" }
q254899
Protocol.unpack
test
public static function unpack(string $type, string $bytes) { self::checkLen($type, $bytes); if ($type === self::BIT_B64) { $set = unpack($type, $bytes); $result = ($set[1] & 0xFFFFFFFF) << 32 | ($set[2] & 0xFFFFFFFF); } elseif ($type === self::BIT_B16_SIGNED) { // According to PHP docs: 's' = signed short (always 16 bit, machine byte order) // So lets unpack it.. $set = unpack($type, $bytes); // But if our system is little endian if (self::isSystemLittleEndian()) { // We need to flip the endianess because coming from kafka it is big endian $set = self::convertSignedShortFromLittleEndianToBigEndian($set); } $result = $set; } else { $result = unpack($type, $bytes); } return is_array($result) ? array_shift($result) : $result; }
php
{ "resource": "" }