_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q254900 | Protocol.checkLen | test | protected static function checkLen(string $type, string $bytes): void
{
$expectedLength = 0;
switch ($type) {
case self::BIT_B64:
$expectedLength = 8;
break;
case self::BIT_B32:
$expectedLength = 4;
break;
case self::BIT_B16:
$expectedLength = 2;
break;
case self::BIT_B16_SIGNED:
$expectedLength = 2;
break;
case self::BIT_B8:
$expectedLength = 1;
break;
}
$length = strlen($bytes);
if ($length !== $expectedLength) {
throw new ProtocolException('unpack failed. string(raw) length is ' . $length . ' , TO ' . $type);
}
} | php | {
"resource": ""
} |
q254901 | Protocol.isSystemLittleEndian | test | public static function isSystemLittleEndian(): bool
{
// If we don't know if our system is big endian or not yet...
if (self::$isLittleEndianSystem === null) {
[$endianTest] = array_values(unpack('L1L', pack('V', 1)));
self::$isLittleEndianSystem = (int) $endianTest === 1;
}
return self::$isLittleEndianSystem;
} | php | {
"resource": ""
} |
q254902 | Protocol.getApiVersion | test | public function getApiVersion(int $apikey): int
{
switch ($apikey) {
case self::METADATA_REQUEST:
return self::API_VERSION0;
case self::PRODUCE_REQUEST:
if (version_compare($this->version, '0.10.0') >= 0) {
return self::API_VERSION2;
}
if (version_compare($this->version, '0.9.0') >= 0) {
return self::API_VERSION1;
}
return self::API_VERSION0;
case self::FETCH_REQUEST:
if (version_compare($this->version, '0.10.0') >= 0) {
return self::API_VERSION2;
}
if (version_compare($this->version, '0.9.0') >= 0) {
return self::API_VERSION1;
}
return self::API_VERSION0;
case self::OFFSET_REQUEST:
// TODO: make it compatible with V1 of OFFSET_REQUEST
// if (version_compare($this->version, '0.10.1.0') >= 0) {
// return self::API_VERSION1;
// } else {
// return self::API_VERSION0;
// }
return self::API_VERSION0;
case self::GROUP_COORDINATOR_REQUEST:
return self::API_VERSION0;
case self::OFFSET_COMMIT_REQUEST:
if (version_compare($this->version, '0.9.0') >= 0) {
return self::API_VERSION2;
}
if (version_compare($this->version, '0.8.2') >= 0) {
return self::API_VERSION1;
}
return self::API_VERSION0; // supported in 0.8.1 or later
case self::OFFSET_FETCH_REQUEST:
if (version_compare($this->version, '0.8.2') >= 0) {
return self::API_VERSION1; // Offset Fetch Request v1 will fetch offset from Kafka
}
return self::API_VERSION0;//Offset Fetch Request v0 will fetch offset from zookeeper
case self::JOIN_GROUP_REQUEST:
if (version_compare($this->version, '0.10.1.0') >= 0) {
return self::API_VERSION1;
}
return self::API_VERSION0; // supported in 0.9.0.0 and greater
case self::SYNC_GROUP_REQUEST:
return self::API_VERSION0;
case self::HEART_BEAT_REQUEST:
return self::API_VERSION0;
case self::LEAVE_GROUP_REQUEST:
return self::API_VERSION0;
case self::LIST_GROUPS_REQUEST:
return self::API_VERSION0;
case self::DESCRIBE_GROUPS_REQUEST:
return self::API_VERSION0;
}
// default
return self::API_VERSION0;
} | php | {
"resource": ""
} |
q254903 | Protocol.getApiText | test | public static function getApiText(int $apikey): string
{
$apis = [
self::PRODUCE_REQUEST => 'ProduceRequest',
self::FETCH_REQUEST => 'FetchRequest',
self::OFFSET_REQUEST => 'OffsetRequest',
self::METADATA_REQUEST => 'MetadataRequest',
self::OFFSET_COMMIT_REQUEST => 'OffsetCommitRequest',
self::OFFSET_FETCH_REQUEST => 'OffsetFetchRequest',
self::GROUP_COORDINATOR_REQUEST => 'GroupCoordinatorRequest',
self::JOIN_GROUP_REQUEST => 'JoinGroupRequest',
self::HEART_BEAT_REQUEST => 'HeartbeatRequest',
self::LEAVE_GROUP_REQUEST => 'LeaveGroupRequest',
self::SYNC_GROUP_REQUEST => 'SyncGroupRequest',
self::DESCRIBE_GROUPS_REQUEST => 'DescribeGroupsRequest',
self::LIST_GROUPS_REQUEST => 'ListGroupsRequest',
self::SASL_HAND_SHAKE_REQUEST => 'SaslHandShakeRequest',
self::API_VERSIONS_REQUEST => 'ApiVersionsRequest',
];
return $apis[$apikey] ?? 'Unknown message';
} | php | {
"resource": ""
} |
q254904 | Router.before | test | public function before($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->beforeRoutes[$method][] = [
'pattern' => $pattern,
'fn' => $fn,
];
}
} | php | {
"resource": ""
} |
q254905 | Router.match | test | public function match($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->afterRoutes[$method][] = [
'pattern' => $pattern,
'fn' => $fn,
];
}
} | php | {
"resource": ""
} |
q254906 | Router.mount | test | public function mount($baseRoute, $fn)
{
// Track current base route
$curBaseRoute = $this->baseRoute;
// Build new base route string
$this->baseRoute .= $baseRoute;
// Call the callable
call_user_func($fn);
// Restore original base route
$this->baseRoute = $curBaseRoute;
} | php | {
"resource": ""
} |
q254907 | Router.getRequestMethod | test | public function getRequestMethod()
{
// Take the method as found in $_SERVER
$method = $_SERVER['REQUEST_METHOD'];
// If it's a HEAD request override it to being GET and prevent any output, as per HTTP Specification
// @url http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_start();
$method = 'GET';
}
// If it's a POST request, check for a method override header
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$headers = $this->getRequestHeaders();
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], ['PUT', 'DELETE', 'PATCH'])) {
$method = $headers['X-HTTP-Method-Override'];
}
}
return $method;
} | php | {
"resource": ""
} |
q254908 | Router.getBasePath | test | public function getBasePath()
{
// Check if server base path is defined, if not define it.
if ($this->serverBasePath === null) {
$this->serverBasePath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
}
return $this->serverBasePath;
} | php | {
"resource": ""
} |
q254909 | Router.map | test | public function map($pattern, $callback, $pass_route = false) {
$url = $pattern;
$methods = array('*');
if (strpos($pattern, ' ') !== false) {
list($method, $url) = explode(' ', trim($pattern), 2);
$methods = explode('|', $method);
}
$this->routes[] = new Route($url, $callback, $methods, $pass_route);
} | php | {
"resource": ""
} |
q254910 | Router.route | test | public function route(Request $request) {
$url_decoded = urldecode( $request->url );
while ($route = $this->current()) {
if ($route !== false && $route->matchMethod($request->method) && $route->matchUrl($url_decoded, $this->case_sensitive)) {
return $route;
}
$this->next();
}
return false;
} | php | {
"resource": ""
} |
q254911 | Router.current | test | public function current() {
return isset($this->routes[$this->index]) ? $this->routes[$this->index] : false;
} | php | {
"resource": ""
} |
q254912 | Route.matchUrl | test | public function matchUrl($url, $case_sensitive = false) {
// Wildcard or exact match
if ($this->pattern === '*' || $this->pattern === $url) {
return true;
}
$ids = array();
$last_char = substr($this->pattern, -1);
// Get splat
if ($last_char === '*') {
$n = 0;
$len = strlen($url);
$count = substr_count($this->pattern, '/');
for ($i = 0; $i < $len; $i++) {
if ($url[$i] == '/') $n++;
if ($n == $count) break;
}
$this->splat = (string)substr($url, $i+1);
}
// Build the regex for matching
$regex = str_replace(array(')','/*'), array(')?','(/?|/.*?)'), $this->pattern);
$regex = preg_replace_callback(
'#@([\w]+)(:([^/\(\)]*))?#',
function($matches) use (&$ids) {
$ids[$matches[1]] = null;
if (isset($matches[3])) {
return '(?P<'.$matches[1].'>'.$matches[3].')';
}
return '(?P<'.$matches[1].'>[^/\?]+)';
},
$regex
);
// Fix trailing slash
if ($last_char === '/') {
$regex .= '?';
}
// Allow trailing slash
else {
$regex .= '/?';
}
// Attempt to match route and named parameters
if (preg_match('#^'.$regex.'(?:\?.*)?$#'.(($case_sensitive) ? '' : 'i'), $url, $matches)) {
foreach ($ids as $k => $v) {
$this->params[$k] = (array_key_exists($k, $matches)) ? urldecode($matches[$k]) : null;
}
$this->regex = $regex;
return true;
}
return false;
} | php | {
"resource": ""
} |
q254913 | Dispatcher.run | test | public function run($name, array $params = array()) {
$output = '';
// Run pre-filters
if (!empty($this->filters[$name]['before'])) {
$this->filter($this->filters[$name]['before'], $params, $output);
}
// Run requested method
$output = $this->execute($this->get($name), $params);
// Run post-filters
if (!empty($this->filters[$name]['after'])) {
$this->filter($this->filters[$name]['after'], $params, $output);
}
return $output;
} | php | {
"resource": ""
} |
q254914 | Dispatcher.get | test | public function get($name) {
return isset($this->events[$name]) ? $this->events[$name] : null;
} | php | {
"resource": ""
} |
q254915 | Dispatcher.clear | test | public function clear($name = null) {
if ($name !== null) {
unset($this->events[$name]);
unset($this->filters[$name]);
}
else {
$this->events = array();
$this->filters = array();
}
} | php | {
"resource": ""
} |
q254916 | Dispatcher.filter | test | public function filter($filters, &$params, &$output) {
$args = array(&$params, &$output);
foreach ($filters as $callback) {
$continue = $this->execute($callback, $args);
if ($continue === false) break;
}
} | php | {
"resource": ""
} |
q254917 | Dispatcher.execute | test | public static function execute($callback, array &$params = array()) {
if (is_callable($callback)) {
return is_array($callback) ?
self::invokeMethod($callback, $params) :
self::callFunction($callback, $params);
}
else {
throw new \Exception('Invalid callback specified.');
}
} | php | {
"resource": ""
} |
q254918 | Dispatcher.callFunction | test | public static function callFunction($func, array &$params = array()) {
// Call static method
if (is_string($func) && strpos($func, '::') !== false) {
return call_user_func_array($func, $params);
}
switch (count($params)) {
case 0:
return $func();
case 1:
return $func($params[0]);
case 2:
return $func($params[0], $params[1]);
case 3:
return $func($params[0], $params[1], $params[2]);
case 4:
return $func($params[0], $params[1], $params[2], $params[3]);
case 5:
return $func($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array($func, $params);
}
} | php | {
"resource": ""
} |
q254919 | Dispatcher.invokeMethod | test | public static function invokeMethod($func, array &$params = array()) {
list($class, $method) = $func;
$instance = is_object($class);
switch (count($params)) {
case 0:
return ($instance) ?
$class->$method() :
$class::$method();
case 1:
return ($instance) ?
$class->$method($params[0]) :
$class::$method($params[0]);
case 2:
return ($instance) ?
$class->$method($params[0], $params[1]) :
$class::$method($params[0], $params[1]);
case 3:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2]) :
$class::$method($params[0], $params[1], $params[2]);
case 4:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2], $params[3]) :
$class::$method($params[0], $params[1], $params[2], $params[3]);
case 5:
return ($instance) ?
$class->$method($params[0], $params[1], $params[2], $params[3], $params[4]) :
$class::$method($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array($func, $params);
}
} | php | {
"resource": ""
} |
q254920 | Request.init | test | public function init($properties = array()) {
// Set all the defined properties
foreach ($properties as $name => $value) {
$this->$name = $value;
}
// Get the requested URL without the base directory
if ($this->base != '/' && strlen($this->base) > 0 && strpos($this->url, $this->base) === 0) {
$this->url = substr($this->url, strlen($this->base));
}
// Default url
if (empty($this->url)) {
$this->url = '/';
}
// Merge URL query parameters with $_GET
else {
$_GET += self::parseQuery($this->url);
$this->query->setData($_GET);
}
// Check for JSON input
if (strpos($this->type, 'application/json') === 0) {
$body = $this->getBody();
if ($body != '') {
$data = json_decode($body, true);
if ($data != null) {
$this->data->setData($data);
}
}
}
} | php | {
"resource": ""
} |
q254921 | Request.getBody | test | public static function getBody() {
static $body;
if (!is_null($body)) {
return $body;
}
$method = self::getMethod();
if ($method == 'POST' || $method == 'PUT' || $method == 'PATCH') {
$body = file_get_contents('php://input');
}
return $body;
} | php | {
"resource": ""
} |
q254922 | Request.getMethod | test | public static function getMethod() {
$method = self::getVar('REQUEST_METHOD', 'GET');
if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
}
elseif (isset($_REQUEST['_method'])) {
$method = $_REQUEST['_method'];
}
return strtoupper($method);
} | php | {
"resource": ""
} |
q254923 | Request.getProxyIpAddress | test | public static function getProxyIpAddress() {
static $forwarded = array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED'
);
$flags = \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE;
foreach ($forwarded as $key) {
if (array_key_exists($key, $_SERVER)) {
sscanf($_SERVER[$key], '%[^,]', $ip);
if (filter_var($ip, \FILTER_VALIDATE_IP, $flags) !== false) {
return $ip;
}
}
}
return '';
} | php | {
"resource": ""
} |
q254924 | Request.parseQuery | test | public static function parseQuery($url) {
$params = array();
$args = parse_url($url);
if (isset($args['query'])) {
parse_str($args['query'], $params);
}
return $params;
} | php | {
"resource": ""
} |
q254925 | Response.status | test | public function status($code = null) {
if ($code === null) {
return $this->status;
}
if (array_key_exists($code, self::$codes)) {
$this->status = $code;
}
else {
throw new \Exception('Invalid status code.');
}
return $this;
} | php | {
"resource": ""
} |
q254926 | Response.header | test | public function header($name, $value = null) {
if (is_array($name)) {
foreach ($name as $k => $v) {
$this->headers[$k] = $v;
}
}
else {
$this->headers[$name] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q254927 | Response.cache | test | public function cache($expires) {
if ($expires === false) {
$this->headers['Expires'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
$this->headers['Cache-Control'] = array(
'no-store, no-cache, must-revalidate',
'post-check=0, pre-check=0',
'max-age=0'
);
$this->headers['Pragma'] = 'no-cache';
}
else {
$expires = is_int($expires) ? $expires : strtotime($expires);
$this->headers['Expires'] = gmdate('D, d M Y H:i:s', $expires) . ' GMT';
$this->headers['Cache-Control'] = 'max-age='.($expires - time());
if (isset($this->headers['Pragma']) && $this->headers['Pragma'] == 'no-cache'){
unset($this->headers['Pragma']);
}
}
return $this;
} | php | {
"resource": ""
} |
q254928 | Response.send | test | public function send() {
if (ob_get_length() > 0) {
ob_end_clean();
}
if (!headers_sent()) {
$this->sendHeaders();
}
echo $this->body;
$this->sent = true;
} | php | {
"resource": ""
} |
q254929 | Engine.init | test | public function init() {
static $initialized = false;
$self = $this;
if ($initialized) {
$this->vars = array();
$this->loader->reset();
$this->dispatcher->reset();
}
// Register default components
$this->loader->register('request', '\flight\net\Request');
$this->loader->register('response', '\flight\net\Response');
$this->loader->register('router', '\flight\net\Router');
$this->loader->register('view', '\flight\template\View', array(), function($view) use ($self) {
$view->path = $self->get('flight.views.path');
$view->extension = $self->get('flight.views.extension');
});
// Register framework methods
$methods = array(
'start','stop','route','halt','error','notFound',
'render','redirect','etag','lastModified','json','jsonp'
);
foreach ($methods as $name) {
$this->dispatcher->set($name, array($this, '_'.$name));
}
// Default configuration settings
$this->set('flight.base_url', null);
$this->set('flight.case_sensitive', false);
$this->set('flight.handle_errors', true);
$this->set('flight.log_errors', false);
$this->set('flight.views.path', './views');
$this->set('flight.views.extension', '.php');
// Startup configuration
$this->before('start', function() use ($self) {
// Enable error handling
if ($self->get('flight.handle_errors')) {
set_error_handler(array($self, 'handleError'));
set_exception_handler(array($self, 'handleException'));
}
// Set case-sensitivity
$self->router()->case_sensitive = $self->get('flight.case_sensitive');
});
$initialized = true;
} | php | {
"resource": ""
} |
q254930 | Engine.handleError | test | public function handleError($errno, $errstr, $errfile, $errline) {
if ($errno & error_reporting()) {
throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
}
} | php | {
"resource": ""
} |
q254931 | Engine.handleException | test | public function handleException($e) {
if ($this->get('flight.log_errors')) {
error_log($e->getMessage());
}
$this->error($e);
} | php | {
"resource": ""
} |
q254932 | Engine.map | test | public function map($name, $callback) {
if (method_exists($this, $name)) {
throw new \Exception('Cannot override an existing framework method.');
}
$this->dispatcher->set($name, $callback);
} | php | {
"resource": ""
} |
q254933 | Engine.register | test | public function register($name, $class, array $params = array(), $callback = null) {
if (method_exists($this, $name)) {
throw new \Exception('Cannot override an existing framework method.');
}
$this->loader->register($name, $class, $params, $callback);
} | php | {
"resource": ""
} |
q254934 | Engine.get | test | public function get($key = null) {
if ($key === null) return $this->vars;
return isset($this->vars[$key]) ? $this->vars[$key] : null;
} | php | {
"resource": ""
} |
q254935 | Engine.clear | test | public function clear($key = null) {
if (is_null($key)) {
$this->vars = array();
}
else {
unset($this->vars[$key]);
}
} | php | {
"resource": ""
} |
q254936 | Engine._start | test | public function _start() {
$dispatched = false;
$self = $this;
$request = $this->request();
$response = $this->response();
$router = $this->router();
// Allow filters to run
$this->after('start', function() use ($self) {
$self->stop();
});
// Flush any existing output
if (ob_get_length() > 0) {
$response->write(ob_get_clean());
}
// Enable output buffering
ob_start();
// Route the request
while ($route = $router->route($request)) {
$params = array_values($route->params);
// Add route info to the parameter list
if ($route->pass) {
$params[] = $route;
}
// Call route handler
$continue = $this->dispatcher->execute(
$route->callback,
$params
);
$dispatched = true;
if (!$continue) break;
$router->next();
$dispatched = false;
}
if (!$dispatched) {
$this->notFound();
}
} | php | {
"resource": ""
} |
q254937 | Engine._stop | test | public function _stop($code = null) {
$response = $this->response();
if (!$response->sent()) {
if ($code !== null) {
$response->status($code);
}
$response->write(ob_get_clean());
$response->send();
}
} | php | {
"resource": ""
} |
q254938 | Engine._route | test | public function _route($pattern, $callback, $pass_route = false) {
$this->router()->map($pattern, $callback, $pass_route);
} | php | {
"resource": ""
} |
q254939 | Engine._halt | test | public function _halt($code = 200, $message = '') {
$this->response()
->clear()
->status($code)
->write($message)
->send();
exit();
} | php | {
"resource": ""
} |
q254940 | Engine._error | test | public function _error($e) {
$msg = sprintf('<h1>500 Internal Server Error</h1>'.
'<h3>%s (%s)</h3>'.
'<pre>%s</pre>',
$e->getMessage(),
$e->getCode(),
$e->getTraceAsString()
);
try {
$this->response()
->clear()
->status(500)
->write($msg)
->send();
}
catch (\Throwable $t) { // PHP 7.0+
exit($msg);
} catch(\Exception $e) { // PHP < 7
exit($msg);
}
} | php | {
"resource": ""
} |
q254941 | Engine._redirect | test | public function _redirect($url, $code = 303) {
$base = $this->get('flight.base_url');
if ($base === null) {
$base = $this->request()->base;
}
// Append base url to redirect url
if ($base != '/' && strpos($url, '://') === false) {
$url = $base . preg_replace('#/+#', '/', '/' . $url);
}
$this->response()
->clear()
->status($code)
->header('Location', $url)
->send();
} | php | {
"resource": ""
} |
q254942 | Engine._json | test | public function _json(
$data,
$code = 200,
$encode = true,
$charset = 'utf-8',
$option = 0
) {
$json = ($encode) ? json_encode($data, $option) : $data;
$this->response()
->status($code)
->header('Content-Type', 'application/json; charset='.$charset)
->write($json)
->send();
} | php | {
"resource": ""
} |
q254943 | Engine._jsonp | test | public function _jsonp(
$data,
$param = 'jsonp',
$code = 200,
$encode = true,
$charset = 'utf-8',
$option = 0
) {
$json = ($encode) ? json_encode($data, $option) : $data;
$callback = $this->request()->query[$param];
$this->response()
->status($code)
->header('Content-Type', 'application/javascript; charset='.$charset)
->write($callback.'('.$json.');')
->send();
} | php | {
"resource": ""
} |
q254944 | Engine._etag | test | public function _etag($id, $type = 'strong') {
$id = (($type === 'weak') ? 'W/' : '').$id;
$this->response()->header('ETag', $id);
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
$_SERVER['HTTP_IF_NONE_MATCH'] === $id) {
$this->halt(304);
}
} | php | {
"resource": ""
} |
q254945 | Engine._lastModified | test | public function _lastModified($time) {
$this->response()->header('Last-Modified', gmdate('D, d M Y H:i:s \G\M\T', $time));
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) === $time) {
$this->halt(304);
}
} | php | {
"resource": ""
} |
q254946 | Loader.register | test | public function register($name, $class, array $params = array(), $callback = null) {
unset($this->instances[$name]);
$this->classes[$name] = array($class, $params, $callback);
} | php | {
"resource": ""
} |
q254947 | Loader.load | test | public function load($name, $shared = true) {
$obj = null;
if (isset($this->classes[$name])) {
list($class, $params, $callback) = $this->classes[$name];
$exists = isset($this->instances[$name]);
if ($shared) {
$obj = ($exists) ?
$this->getInstance($name) :
$this->newInstance($class, $params);
if (!$exists) {
$this->instances[$name] = $obj;
}
}
else {
$obj = $this->newInstance($class, $params);
}
if ($callback && (!$shared || !$exists)) {
$ref = array(&$obj);
call_user_func_array($callback, $ref);
}
}
return $obj;
} | php | {
"resource": ""
} |
q254948 | Loader.getInstance | test | public function getInstance($name) {
return isset($this->instances[$name]) ? $this->instances[$name] : null;
} | php | {
"resource": ""
} |
q254949 | Loader.newInstance | test | public function newInstance($class, array $params = array()) {
if (is_callable($class)) {
return call_user_func_array($class, $params);
}
switch (count($params)) {
case 0:
return new $class();
case 1:
return new $class($params[0]);
case 2:
return new $class($params[0], $params[1]);
case 3:
return new $class($params[0], $params[1], $params[2]);
case 4:
return new $class($params[0], $params[1], $params[2], $params[3]);
case 5:
return new $class($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
try {
$refClass = new \ReflectionClass($class);
return $refClass->newInstanceArgs($params);
} catch (\ReflectionException $e) {
throw new \Exception("Cannot instantiate {$class}", 0, $e);
}
}
} | php | {
"resource": ""
} |
q254950 | Loader.loadClass | test | public static function loadClass($class) {
$class_file = str_replace(array('\\', '_'), '/', $class).'.php';
foreach (self::$dirs as $dir) {
$file = $dir.'/'.$class_file;
if (file_exists($file)) {
require $file;
return;
}
}
} | php | {
"resource": ""
} |
q254951 | Loader.addDirectory | test | public static function addDirectory($dir) {
if (is_array($dir) || is_object($dir)) {
foreach ($dir as $value) {
self::addDirectory($value);
}
}
else if (is_string($dir)) {
if (!in_array($dir, self::$dirs)) self::$dirs[] = $dir;
}
} | php | {
"resource": ""
} |
q254952 | View.fetch | test | public function fetch($file, $data = null) {
ob_start();
$this->render($file, $data);
$output = ob_get_clean();
return $output;
} | php | {
"resource": ""
} |
q254953 | View.getTemplate | test | public function getTemplate($file) {
$ext = $this->extension;
if (!empty($ext) && (substr($file, -1 * strlen($ext)) != $ext)) {
$file .= $ext;
}
if ((substr($file, 0, 1) == '/')) {
return $file;
}
return $this->path.'/'.$file;
} | php | {
"resource": ""
} |
q254954 | CycleDetector.isCyclic | test | public function isCyclic(Graph $graph)
{
// prepare stack
$recursionStack = [];
foreach ($graph->all() as $node) {
$recursionStack[$node->getKey()] = false;
}
// start analysis
$isCyclic = false;
foreach ($graph->getEdges() as $edge) {
if ($r = $this->detectCycle($edge->getFrom(), $recursionStack)) {
$edge->cyclic = true;
$isCyclic = true;
}
$recursionStack[$node->getKey()] = false;
}
$graph->resetVisits();
return $isCyclic;
} | php | {
"resource": ""
} |
q254955 | SizeOfTree.getAverageHeightOfGraph | test | public function getAverageHeightOfGraph()
{
$ns = [];
foreach ($this->graph->getRootNodes() as $node) {
array_push($ns, $this->getLongestBranch($node));
}
return round(array_sum($ns) / max(1, sizeof($ns)), 2);
} | php | {
"resource": ""
} |
q254956 | ConfigFileReaderJson.collapseArray | test | private function collapseArray(array $arr)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$result = [];
foreach ($iterator as $leafValue) {
$keys = [];
foreach (range(0, $iterator->getDepth()) as $depth) {
$keys[] = $iterator->getSubIterator($depth)->key();
}
$result[join('-', $keys)] = $leafValue;
}
return $result;
} | php | {
"resource": ""
} |
q254957 | Finder.fetch | test | public function fetch(array $paths)
{
$files = array();
foreach ($paths as $path) {
if (is_dir($path)) {
$path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$directory = new RecursiveDirectoryIterator($path, $this->flags);
$iterator = new RecursiveIteratorIterator($directory);
$filterRegex = sprintf(
'`^%s%s%s$`',
preg_quote($path, '`'),
!empty($this->excludedDirs) ? '((?!' . implode('|', array_map('preg_quote', $this->excludedDirs)) . ').)+' : '.+',
'\.(' . implode('|', $this->extensions) . ')'
);
$filteredIterator = new RegexIterator(
$iterator,
$filterRegex,
\RecursiveRegexIterator::GET_MATCH
);
foreach ($filteredIterator as $file) {
$files[] = $file[0];
}
} elseif (is_file($path)) {
$files[] = $path;
}
}
return $files;
} | php | {
"resource": ""
} |
q254958 | LcomVisitor.traverse | test | private function traverse(TreeNode $node)
{
if ($node->visited) {
return 0;
}
$node->visited = true;
foreach ($node->getAdjacents() as $adjacent) {
$this->traverse($adjacent);
}
return 1;
} | php | {
"resource": ""
} |
q254959 | Graph.getRootNodes | test | public function getRootNodes()
{
$roots = [];
foreach ($this->all() as $node) {
$isRoot = true;
foreach ($node->getEdges() as $edge) {
if ($edge->getTo() == $node) {
$isRoot = false;
}
}
if ($isRoot) {
array_push($roots, $node);
}
}
return $roots;
} | php | {
"resource": ""
} |
q254960 | Composer.getComposerLockInstalled | test | protected function getComposerLockInstalled($rootPackageRequirements)
{
$rawInstalled = [[]];
// Find composer.lock file
$finder = new Finder(['lock'], $this->config->get('exclude'));
$files = $finder->fetch($this->config->get('files'));
// List all composer.lock found in the project.
foreach ($files as $filename) {
if (false === \strpos($filename, 'composer.lock')) {
continue;
}
$composerLockJson = (object)\json_decode(\file_get_contents($filename));
if (!isset($composerLockJson->packages)) {
continue;
}
$installed = [];
foreach ($composerLockJson->packages as $package) {
if (!\in_array($package->name, $rootPackageRequirements, true)) {
continue;
}
$installed[$package->name] = \preg_replace('#[^.\d]#', '', $package->version);
}
$rawInstalled[] = $installed;
}
return \call_user_func_array('array_merge', $rawInstalled);
} | php | {
"resource": ""
} |
q254961 | ProgressBar.advance | test | public function advance()
{
$this->current++;
if ($this->hasAnsi()) {
$percent = round($this->current / $this->max * 100);
$this->output->write("\x0D");
$this->output->write("\x1B[2K");
$this->output->write(sprintf('... %s%% ...', $percent));
} else {
$this->output->write('.');
}
} | php | {
"resource": ""
} |
q254962 | ProgressBar.hasAnsi | test | protected function hasAnsi()
{
if (DIRECTORY_SEPARATOR === '\\') {
return
0 >= version_compare('10.0.10586',
PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD)
|| false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM');
}
return function_exists('posix_isatty') && @posix_isatty($this->stream);
} | php | {
"resource": ""
} |
q254963 | I18nTextDomainFixerSniff.process_no_parameters | test | public function process_no_parameters( $stackPtr, $group_name, $matched_content ) {
$target_param = $this->target_functions[ $matched_content ];
if ( 1 !== $target_param ) {
// Only process the no param case as fixable if the text domain is expected to be the first parameter.
$this->phpcsFile->addWarning( 'Missing $domain arg and preceding argument(s)', $stackPtr, 'MissingArgs' );
return;
}
$opener = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true );
if ( \T_OPEN_PARENTHESIS !== $this->tokens[ $opener ]['code']
|| isset( $this->tokens[ $opener ]['parenthesis_closer'] ) === false
) {
// Parse error or live coding.
return;
}
$fix = $this->phpcsFile->addFixableError( 'Missing $domain arg', $stackPtr, 'MissingArgDomain' );
if ( true === $fix ) {
$closer = $this->tokens[ $opener ]['parenthesis_closer'];
$replacement = " '{$this->new_text_domain}' ";
if ( $this->tokens[ $opener ]['line'] !== $this->tokens[ $closer ]['line'] ) {
$replacement = trim( $replacement );
$addBefore = ( $closer - 1 );
if ( \T_WHITESPACE === $this->tokens[ ( $closer - 1 ) ]['code']
&& $this->tokens[ $closer - 1 ]['line'] === $this->tokens[ $closer ]['line']
) {
if ( isset( $this->tokens[ ( $closer - 1 ) ]['orig_content'] ) ) {
$replacement = $this->tokens[ ( $closer - 1 ) ]['orig_content']
. "\t"
. $replacement;
} else {
$replacement = $this->tokens[ ( $closer - 1 ) ]['content']
. str_repeat( ' ', $this->tab_width )
. $replacement;
}
--$addBefore;
} else {
// We don't know whether the code uses tabs or spaces, so presume WPCS, i.e. tabs.
$replacement = "\t" . $replacement;
}
$replacement = $this->phpcsFile->eolChar . $replacement;
$this->phpcsFile->fixer->addContentBefore( $addBefore, $replacement );
} elseif ( \T_WHITESPACE === $this->tokens[ ( $closer - 1 ) ]['code'] ) {
$this->phpcsFile->fixer->replaceToken( ( $closer - 1 ), $replacement );
} else {
$this->phpcsFile->fixer->addContentBefore( $closer, $replacement );
}
}
} | php | {
"resource": ""
} |
q254964 | Sniff.process | test | public function process( File $phpcsFile, $stackPtr ) {
$this->init( $phpcsFile );
return $this->process_token( $stackPtr );
} | php | {
"resource": ""
} |
q254965 | Sniff.init | test | protected function init( File $phpcsFile ) {
$this->phpcsFile = $phpcsFile;
$this->tokens = $phpcsFile->getTokens();
} | php | {
"resource": ""
} |
q254966 | Sniff.addFixableMessage | test | protected function addFixableMessage( $message, $stackPtr, $is_error = true, $code = 'Found', $data = array(), $severity = 0 ) {
return $this->throwMessage( $message, $stackPtr, $is_error, $code, $data, $severity, true );
} | php | {
"resource": ""
} |
q254967 | Sniff.merge_custom_array | test | public static function merge_custom_array( $custom, $base = array(), $flip = true ) {
if ( true === $flip ) {
$base = array_filter( $base );
}
if ( empty( $custom ) || ! \is_array( $custom ) ) {
return $base;
}
if ( true === $flip ) {
$custom = array_fill_keys( $custom, false );
}
if ( empty( $base ) ) {
return $custom;
}
return array_merge( $base, $custom );
} | php | {
"resource": ""
} |
q254968 | Sniff.get_last_ptr_on_line | test | protected function get_last_ptr_on_line( $stackPtr ) {
$tokens = $this->tokens;
$currentLine = $tokens[ $stackPtr ]['line'];
$nextPtr = ( $stackPtr + 1 );
while ( isset( $tokens[ $nextPtr ] ) && $tokens[ $nextPtr ]['line'] === $currentLine ) {
$nextPtr++;
// Do nothing, we just want the last token of the line.
}
// We've made it to the next line, back up one to the last in the previous line.
// We do this for micro-optimization of the above loop.
$lastPtr = ( $nextPtr - 1 );
return $lastPtr;
} | php | {
"resource": ""
} |
q254969 | Sniff.is_assignment | test | protected function is_assignment( $stackPtr ) {
static $valid = array(
\T_VARIABLE => true,
\T_CLOSE_SQUARE_BRACKET => true,
);
// Must be a variable, constant or closing square bracket (see below).
if ( ! isset( $valid[ $this->tokens[ $stackPtr ]['code'] ] ) ) {
return false;
}
$next_non_empty = $this->phpcsFile->findNext(
Tokens::$emptyTokens,
( $stackPtr + 1 ),
null,
true,
null,
true
);
// No token found.
if ( false === $next_non_empty ) {
return false;
}
// If the next token is an assignment, that's all we need to know.
if ( isset( Tokens::$assignmentTokens[ $this->tokens[ $next_non_empty ]['code'] ] ) ) {
return true;
}
// Check if this is an array assignment, e.g., `$var['key'] = 'val';` .
if ( \T_OPEN_SQUARE_BRACKET === $this->tokens[ $next_non_empty ]['code']
&& isset( $this->tokens[ $next_non_empty ]['bracket_closer'] )
) {
return $this->is_assignment( $this->tokens[ $next_non_empty ]['bracket_closer'] );
}
return false;
} | php | {
"resource": ""
} |
q254970 | Sniff.is_token_namespaced | test | protected function is_token_namespaced( $stackPtr ) {
$prev = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true, null, true );
if ( false === $prev ) {
return false;
}
if ( \T_NS_SEPARATOR !== $this->tokens[ $prev ]['code'] ) {
return false;
}
$before_prev = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $prev - 1 ), null, true, null, true );
if ( false === $before_prev ) {
return false;
}
if ( \T_STRING !== $this->tokens[ $before_prev ]['code']
&& \T_NAMESPACE !== $this->tokens[ $before_prev ]['code']
) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q254971 | Sniff.is_only_sanitized | test | protected function is_only_sanitized( $stackPtr ) {
// If it isn't being sanitized at all.
if ( ! $this->is_sanitized( $stackPtr ) ) {
return false;
}
// If this isn't set, we know the value must have only been casted, because
// is_sanitized() would have returned false otherwise.
if ( ! isset( $this->tokens[ $stackPtr ]['nested_parenthesis'] ) ) {
return true;
}
// At this point we're expecting the value to have not been casted. If it
// was, it wasn't *only* casted, because it's also in a function.
if ( $this->is_safe_casted( $stackPtr ) ) {
return false;
}
// The only parentheses should belong to the sanitizing function. If there's
// more than one set, this isn't *only* sanitization.
return ( \count( $this->tokens[ $stackPtr ]['nested_parenthesis'] ) === 1 );
} | php | {
"resource": ""
} |
q254972 | Sniff.is_safe_casted | test | protected function is_safe_casted( $stackPtr ) {
// Get the last non-empty token.
$prev = $this->phpcsFile->findPrevious(
Tokens::$emptyTokens,
( $stackPtr - 1 ),
null,
true
);
if ( false === $prev ) {
return false;
}
// Check if it is a safe cast.
return isset( $this->safe_casts[ $this->tokens[ $prev ]['code'] ] );
} | php | {
"resource": ""
} |
q254973 | Sniff.get_array_access_keys | test | protected function get_array_access_keys( $stackPtr, $all = true ) {
$keys = array();
if ( \T_VARIABLE !== $this->tokens[ $stackPtr ]['code'] ) {
return $keys;
}
$current = $stackPtr;
do {
// Find the next non-empty token.
$open_bracket = $this->phpcsFile->findNext(
Tokens::$emptyTokens,
( $current + 1 ),
null,
true
);
// If it isn't a bracket, this isn't an array-access.
if ( false === $open_bracket
|| \T_OPEN_SQUARE_BRACKET !== $this->tokens[ $open_bracket ]['code']
|| ! isset( $this->tokens[ $open_bracket ]['bracket_closer'] )
) {
break;
}
$key = $this->phpcsFile->getTokensAsString(
( $open_bracket + 1 ),
( $this->tokens[ $open_bracket ]['bracket_closer'] - $open_bracket - 1 )
);
$keys[] = trim( $key );
$current = $this->tokens[ $open_bracket ]['bracket_closer'];
} while ( isset( $this->tokens[ $current ] ) && true === $all );
return $keys;
} | php | {
"resource": ""
} |
q254974 | Sniff.get_array_access_key | test | protected function get_array_access_key( $stackPtr ) {
$keys = $this->get_array_access_keys( $stackPtr, false );
if ( isset( $keys[0] ) ) {
return $keys[0];
}
return false;
} | php | {
"resource": ""
} |
q254975 | Sniff.is_comparison | test | protected function is_comparison( $stackPtr, $include_coalesce = true ) {
$comparisonTokens = Tokens::$comparisonTokens;
if ( false === $include_coalesce ) {
unset( $comparisonTokens[ \T_COALESCE ] );
}
// We first check if this is a switch statement (switch ( $var )).
if ( isset( $this->tokens[ $stackPtr ]['nested_parenthesis'] ) ) {
$nested_parenthesis = $this->tokens[ $stackPtr ]['nested_parenthesis'];
$close_parenthesis = end( $nested_parenthesis );
if (
isset( $this->tokens[ $close_parenthesis ]['parenthesis_owner'] )
&& \T_SWITCH === $this->tokens[ $this->tokens[ $close_parenthesis ]['parenthesis_owner'] ]['code']
) {
return true;
}
}
// Find the previous non-empty token. We check before the var first because
// yoda conditions are usually expected.
$previous_token = $this->phpcsFile->findPrevious(
Tokens::$emptyTokens,
( $stackPtr - 1 ),
null,
true
);
if ( isset( $comparisonTokens[ $this->tokens[ $previous_token ]['code'] ] ) ) {
return true;
}
// Maybe the comparison operator is after this.
$next_token = $this->phpcsFile->findNext(
Tokens::$emptyTokens,
( $stackPtr + 1 ),
null,
true
);
// This might be an opening square bracket in the case of arrays ($var['a']).
while ( false !== $next_token && \T_OPEN_SQUARE_BRACKET === $this->tokens[ $next_token ]['code'] ) {
$next_token = $this->phpcsFile->findNext(
Tokens::$emptyTokens,
( $this->tokens[ $next_token ]['bracket_closer'] + 1 ),
null,
true
);
}
if ( false !== $next_token && isset( $comparisonTokens[ $this->tokens[ $next_token ]['code'] ] ) ) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q254976 | Sniff.is_in_array_comparison | test | protected function is_in_array_comparison( $stackPtr ) {
$function_ptr = $this->is_in_function_call( $stackPtr, $this->arrayCompareFunctions, true, true );
if ( false === $function_ptr ) {
return false;
}
$function_name = $this->tokens[ $function_ptr ]['content'];
if ( true === $this->arrayCompareFunctions[ $function_name ] ) {
return true;
}
if ( $this->get_function_call_parameter_count( $function_ptr ) >= $this->arrayCompareFunctions[ $function_name ] ) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q254977 | Sniff.get_use_type | test | protected function get_use_type( $stackPtr ) {
// USE keywords inside closures.
$next = $this->phpcsFile->findNext( \T_WHITESPACE, ( $stackPtr + 1 ), null, true );
if ( \T_OPEN_PARENTHESIS === $this->tokens[ $next ]['code'] ) {
return 'closure';
}
// USE keywords for traits.
$valid_scopes = array(
'T_CLASS' => true,
'T_ANON_CLASS' => true,
'T_TRAIT' => true,
);
if ( false !== $this->valid_direct_scope( $stackPtr, $valid_scopes ) ) {
return 'trait';
}
// USE keywords for classes to import to a namespace.
return 'class';
} | php | {
"resource": ""
} |
q254978 | Sniff.get_interpolated_variables | test | protected function get_interpolated_variables( $string ) {
$variables = array();
if ( preg_match_all( '/(?P<backslashes>\\\\*)\$(?P<symbol>\w+)/', $string, $match_sets, \PREG_SET_ORDER ) ) {
foreach ( $match_sets as $matches ) {
if ( ! isset( $matches['backslashes'] ) || ( \strlen( $matches['backslashes'] ) % 2 ) === 0 ) {
$variables[] = $matches['symbol'];
}
}
}
return $variables;
} | php | {
"resource": ""
} |
q254979 | Sniff.does_function_call_have_parameters | test | public function does_function_call_have_parameters( $stackPtr ) {
// Check for the existence of the token.
if ( false === isset( $this->tokens[ $stackPtr ] ) ) {
return false;
}
// Is this one of the tokens this function handles ?
if ( false === \in_array( $this->tokens[ $stackPtr ]['code'], array( \T_STRING, \T_ARRAY, \T_OPEN_SHORT_ARRAY ), true ) ) {
return false;
}
$next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true );
// Deal with short array syntax.
if ( 'T_OPEN_SHORT_ARRAY' === $this->tokens[ $stackPtr ]['type'] ) {
if ( false === isset( $this->tokens[ $stackPtr ]['bracket_closer'] ) ) {
return false;
}
if ( $next_non_empty === $this->tokens[ $stackPtr ]['bracket_closer'] ) {
// No parameters.
return false;
} else {
return true;
}
}
// Deal with function calls & long arrays.
// Next non-empty token should be the open parenthesis.
if ( false === $next_non_empty && \T_OPEN_PARENTHESIS !== $this->tokens[ $next_non_empty ]['code'] ) {
return false;
}
if ( false === isset( $this->tokens[ $next_non_empty ]['parenthesis_closer'] ) ) {
return false;
}
$close_parenthesis = $this->tokens[ $next_non_empty ]['parenthesis_closer'];
$next_next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), ( $close_parenthesis + 1 ), true );
if ( $next_next_non_empty === $close_parenthesis ) {
// No parameters.
return false;
}
return true;
} | php | {
"resource": ""
} |
q254980 | Sniff.get_function_call_parameter_count | test | public function get_function_call_parameter_count( $stackPtr ) {
if ( false === $this->does_function_call_have_parameters( $stackPtr ) ) {
return 0;
}
return \count( $this->get_function_call_parameters( $stackPtr ) );
} | php | {
"resource": ""
} |
q254981 | Sniff.get_function_call_parameter | test | public function get_function_call_parameter( $stackPtr, $param_offset ) {
$parameters = $this->get_function_call_parameters( $stackPtr );
if ( false === isset( $parameters[ $param_offset ] ) ) {
return false;
}
return $parameters[ $param_offset ];
} | php | {
"resource": ""
} |
q254982 | Sniff.find_array_open_close | test | protected function find_array_open_close( $stackPtr ) {
/*
* Determine the array opener & closer.
*/
if ( \T_ARRAY === $this->tokens[ $stackPtr ]['code'] ) {
if ( isset( $this->tokens[ $stackPtr ]['parenthesis_opener'] ) ) {
$opener = $this->tokens[ $stackPtr ]['parenthesis_opener'];
if ( isset( $this->tokens[ $opener ]['parenthesis_closer'] ) ) {
$closer = $this->tokens[ $opener ]['parenthesis_closer'];
}
}
} else {
// Short array syntax.
$opener = $stackPtr;
if ( isset( $this->tokens[ $stackPtr ]['bracket_closer'] ) ) {
$closer = $this->tokens[ $stackPtr ]['bracket_closer'];
}
}
if ( isset( $opener, $closer ) ) {
return array(
'opener' => $opener,
'closer' => $closer,
);
}
return false;
} | php | {
"resource": ""
} |
q254983 | Sniff.determine_namespace | test | public function determine_namespace( $stackPtr ) {
// Check for the existence of the token.
if ( ! isset( $this->tokens[ $stackPtr ] ) ) {
return '';
}
// Check for scoped namespace {}.
if ( ! empty( $this->tokens[ $stackPtr ]['conditions'] ) ) {
$namespacePtr = $this->phpcsFile->getCondition( $stackPtr, \T_NAMESPACE );
if ( false !== $namespacePtr ) {
$namespace = $this->get_declared_namespace_name( $namespacePtr );
if ( false !== $namespace ) {
return $namespace;
}
// We are in a scoped namespace, but couldn't determine the name.
// Searching for a global namespace is futile.
return '';
}
}
/*
* Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
* Keeping in mind that:
* - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
* - the namespace keyword can also be used as part of a function/method call and such.
* - that a non-named namespace resolves to the global namespace.
*/
$previousNSToken = $stackPtr;
$namespace = false;
do {
$previousNSToken = $this->phpcsFile->findPrevious( \T_NAMESPACE, ( $previousNSToken - 1 ) );
// Stop if we encounter a scoped namespace declaration as we already know we're not in one.
if ( ! empty( $this->tokens[ $previousNSToken ]['scope_condition'] )
&& $this->tokens[ $previousNSToken ]['scope_condition'] === $previousNSToken
) {
break;
}
$namespace = $this->get_declared_namespace_name( $previousNSToken );
} while ( false === $namespace && false !== $previousNSToken );
// If we still haven't got a namespace, return an empty string.
if ( false === $namespace ) {
return '';
}
return $namespace;
} | php | {
"resource": ""
} |
q254984 | Sniff.get_declared_namespace_name | test | public function get_declared_namespace_name( $stackPtr ) {
// Check for the existence of the token.
if ( false === $stackPtr || ! isset( $this->tokens[ $stackPtr ] ) ) {
return false;
}
if ( \T_NAMESPACE !== $this->tokens[ $stackPtr ]['code'] ) {
return false;
}
$nextToken = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true );
if ( \T_NS_SEPARATOR === $this->tokens[ $nextToken ]['code'] ) {
// Not a namespace declaration, but use of, i.e. `namespace\someFunction();`.
return false;
}
if ( \T_OPEN_CURLY_BRACKET === $this->tokens[ $nextToken ]['code'] ) {
// Declaration for global namespace when using multiple namespaces in a file.
// I.e.: `namespace {}`.
return '';
}
// Ok, this should be a namespace declaration, so get all the parts together.
$acceptedTokens = array(
\T_STRING => true,
\T_NS_SEPARATOR => true,
);
$validTokens = $acceptedTokens + Tokens::$emptyTokens;
$namespaceName = '';
while ( isset( $validTokens[ $this->tokens[ $nextToken ]['code'] ] ) ) {
if ( isset( $acceptedTokens[ $this->tokens[ $nextToken ]['code'] ] ) ) {
$namespaceName .= trim( $this->tokens[ $nextToken ]['content'] );
}
++$nextToken;
}
return $namespaceName;
} | php | {
"resource": ""
} |
q254985 | Sniff.is_class_constant | test | public function is_class_constant( $stackPtr ) {
if ( ! isset( $this->tokens[ $stackPtr ] ) || \T_CONST !== $this->tokens[ $stackPtr ]['code'] ) {
return false;
}
// Note: traits can not declare constants.
$valid_scopes = array(
'T_CLASS' => true,
'T_ANON_CLASS' => true,
'T_INTERFACE' => true,
);
return is_int( $this->valid_direct_scope( $stackPtr, $valid_scopes ) );
} | php | {
"resource": ""
} |
q254986 | Sniff.is_class_property | test | public function is_class_property( $stackPtr ) {
if ( ! isset( $this->tokens[ $stackPtr ] ) || \T_VARIABLE !== $this->tokens[ $stackPtr ]['code'] ) {
return false;
}
// Note: interfaces can not declare properties.
$valid_scopes = array(
'T_CLASS' => true,
'T_ANON_CLASS' => true,
'T_TRAIT' => true,
);
$scopePtr = $this->valid_direct_scope( $stackPtr, $valid_scopes );
if ( false !== $scopePtr ) {
// Make sure it's not a method parameter.
if ( empty( $this->tokens[ $stackPtr ]['nested_parenthesis'] ) ) {
return true;
} else {
$parenthesis = array_keys( $this->tokens[ $stackPtr ]['nested_parenthesis'] );
$deepest_open = array_pop( $parenthesis );
if ( $deepest_open < $scopePtr
|| isset( $this->tokens[ $deepest_open ]['parenthesis_owner'] ) === false
|| \T_FUNCTION !== $this->tokens[ $this->tokens[ $deepest_open ]['parenthesis_owner'] ]['code']
) {
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q254987 | Sniff.valid_direct_scope | test | protected function valid_direct_scope( $stackPtr, array $valid_scopes ) {
if ( empty( $this->tokens[ $stackPtr ]['conditions'] ) ) {
return false;
}
/*
* Check only the direct wrapping scope of the token.
*/
$conditions = array_keys( $this->tokens[ $stackPtr ]['conditions'] );
$ptr = array_pop( $conditions );
if ( ! isset( $this->tokens[ $ptr ] ) ) {
return false;
}
if ( isset( $valid_scopes[ $this->tokens[ $ptr ]['type'] ] ) ) {
return $ptr;
}
return false;
} | php | {
"resource": ""
} |
q254988 | ValidHookNameSniff.prepare_regex | test | protected function prepare_regex() {
$extra = '';
if ( '' !== $this->additionalWordDelimiters && \is_string( $this->additionalWordDelimiters ) ) {
$extra = preg_quote( $this->additionalWordDelimiters, '`' );
}
return sprintf( $this->punctuation_regex, $extra );
} | php | {
"resource": ""
} |
q254989 | ValidHookNameSniff.transform | test | protected function transform( $string, $regex, $transform_type = 'full' ) {
switch ( $transform_type ) {
case 'case':
return strtolower( $string );
case 'punctuation':
return preg_replace( $regex, '_', $string );
case 'full':
default:
return preg_replace( $regex, '_', strtolower( $string ) );
}
} | php | {
"resource": ""
} |
q254990 | ValidHookNameSniff.transform_complex_string | test | protected function transform_complex_string( $string, $regex, $transform_type = 'full' ) {
$output = preg_split( '`([\{\}\$\[\] ])`', $string, -1, \PREG_SPLIT_DELIM_CAPTURE );
$is_variable = false;
$has_braces = false;
$braces = 0;
foreach ( $output as $i => $part ) {
if ( \in_array( $part, array( '$', '{' ), true ) ) {
$is_variable = true;
if ( '{' === $part ) {
$has_braces = true;
$braces++;
}
continue;
}
if ( true === $is_variable ) {
if ( '[' === $part ) {
$has_braces = true;
$braces++;
}
if ( \in_array( $part, array( '}', ']' ), true ) ) {
$braces--;
}
if ( false === $has_braces && ' ' === $part ) {
$is_variable = false;
$output[ $i ] = $this->transform( $part, $regex, $transform_type );
}
if ( ( true === $has_braces && 0 === $braces ) && false === \in_array( $output[ ( $i + 1 ) ], array( '{', '[' ), true ) ) {
$has_braces = false;
$is_variable = false;
}
continue;
}
$output[ $i ] = $this->transform( $part, $regex, $transform_type );
}
return implode( '', $output );
} | php | {
"resource": ""
} |
q254991 | DeprecatedClassesSniff.getGroups | test | public function getGroups() {
// Make sure all array keys are lowercase.
$this->deprecated_classes = array_change_key_case( $this->deprecated_classes, CASE_LOWER );
return array(
'deprecated_classes' => array(
'classes' => array_keys( $this->deprecated_classes ),
),
);
} | php | {
"resource": ""
} |
q254992 | DiscouragedConstantsSniff.process_arbitrary_tstring | test | public function process_arbitrary_tstring( $stackPtr ) {
$content = $this->tokens[ $stackPtr ]['content'];
if ( ! isset( $this->discouraged_constants[ $content ] ) ) {
return;
}
$next = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true );
if ( false !== $next && \T_OPEN_PARENTHESIS === $this->tokens[ $next ]['code'] ) {
// Function call or declaration.
return;
}
$prev = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true );
if ( false !== $prev && isset( $this->preceding_tokens_to_ignore[ $this->tokens[ $prev ]['code'] ] ) ) {
// Not the use of a constant.
return;
}
if ( $this->is_token_namespaced( $stackPtr ) === true ) {
// Namespaced constant of the same name.
return;
}
if ( false !== $prev
&& \T_CONST === $this->tokens[ $prev ]['code']
&& true === $this->is_class_constant( $prev )
) {
// Class constant of the same name.
return;
}
/*
* Deal with a number of variations of use statements.
*/
for ( $i = $stackPtr; $i > 0; $i-- ) {
if ( $this->tokens[ $i ]['line'] !== $this->tokens[ $stackPtr ]['line'] ) {
break;
}
}
$first_on_line = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $i + 1 ), null, true );
if ( false !== $first_on_line && \T_USE === $this->tokens[ $first_on_line ]['code'] ) {
$next_on_line = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $first_on_line + 1 ), null, true );
if ( false !== $next_on_line ) {
if ( ( \T_STRING === $this->tokens[ $next_on_line ]['code']
&& 'const' === $this->tokens[ $next_on_line ]['content'] )
|| \T_CONST === $this->tokens[ $next_on_line ]['code'] // Happens in some PHPCS versions.
) {
$has_ns_sep = $this->phpcsFile->findNext( \T_NS_SEPARATOR, ( $next_on_line + 1 ), $stackPtr );
if ( false !== $has_ns_sep ) {
// Namespaced const (group) use statement.
return;
}
} else {
// Not a const use statement.
return;
}
}
}
// Ok, this is really one of the discouraged constants.
$this->phpcsFile->addWarning(
'Found usage of constant "%s". Use %s instead.',
$stackPtr,
$this->string_to_errorcode( $content . 'UsageFound' ),
array(
$content,
$this->discouraged_constants[ $content ],
)
);
} | php | {
"resource": ""
} |
q254993 | DiscouragedConstantsSniff.process_parameters | test | public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
$function_name = strtolower( $matched_content );
$target_param = $this->target_functions[ $function_name ];
// Was the target parameter passed ?
if ( ! isset( $parameters[ $target_param ] ) ) {
return;
}
$raw_content = $this->strip_quotes( $parameters[ $target_param ]['raw'] );
if ( isset( $this->discouraged_constants[ $raw_content ] ) ) {
$this->phpcsFile->addWarning(
'Found declaration of constant "%s". Use %s instead.',
$stackPtr,
$this->string_to_errorcode( $raw_content . 'DeclarationFound' ),
array(
$raw_content,
$this->discouraged_constants[ $raw_content ],
)
);
}
} | php | {
"resource": ""
} |
q254994 | CapitalPDangitSniff.retrieve_misspellings | test | protected function retrieve_misspellings( $match_stack ) {
$mispelled = array();
foreach ( $match_stack as $match ) {
// Deal with multi-dimensional arrays when capturing offset.
if ( \is_array( $match ) ) {
$match = $match[0];
}
if ( 'WordPress' !== $match ) {
$mispelled[] = $match;
}
}
return $mispelled;
} | php | {
"resource": ""
} |
q254995 | PostsPerPageSniff.callback | test | public function callback( $key, $val, $line, $group ) {
$this->posts_per_page = (int) $this->posts_per_page;
if ( $val > $this->posts_per_page ) {
return 'Detected high pagination limit, `%s` is set to `%s`';
}
return false;
} | php | {
"resource": ""
} |
q254996 | PHPCSHelper.set_config_data | test | public static function set_config_data( $key, $value, $temp = false ) {
Config::setConfigData( $key, $value, $temp );
} | php | {
"resource": ""
} |
q254997 | PHPCSHelper.get_tab_width | test | public static function get_tab_width( File $phpcsFile ) {
$tab_width = 4;
if ( isset( $phpcsFile->config->tabWidth ) && $phpcsFile->config->tabWidth > 0 ) {
$tab_width = $phpcsFile->config->tabWidth;
}
return $tab_width;
} | php | {
"resource": ""
} |
q254998 | GlobalVariablesOverrideSniff.process_global_statement | test | protected function process_global_statement( $stackPtr, $in_function_scope ) {
/*
* Collect the variables to watch for.
*/
$search = array();
$ptr = ( $stackPtr + 1 );
while ( isset( $this->tokens[ $ptr ] ) ) {
$var = $this->tokens[ $ptr ];
// Halt the loop at end of statement.
if ( \T_SEMICOLON === $var['code'] ) {
break;
}
if ( \T_VARIABLE === $var['code'] ) {
if ( isset( $this->wp_globals[ substr( $var['content'], 1 ) ] ) ) {
$search[] = $var['content'];
}
}
$ptr++;
}
unset( $var );
if ( empty( $search ) ) {
return;
}
/*
* Search for assignments to the imported global variables within the relevant scope.
*/
$start = $ptr;
if ( true === $in_function_scope ) {
$function_cond = $this->phpcsFile->getCondition( $stackPtr, \T_FUNCTION );
$closure_cond = $this->phpcsFile->getCondition( $stackPtr, \T_CLOSURE );
$scope_cond = max( $function_cond, $closure_cond ); // If false, it will evaluate as zero, so this is fine.
if ( isset( $this->tokens[ $scope_cond ]['scope_closer'] ) === false ) {
// Live coding or parse error.
return;
}
$end = $this->tokens[ $scope_cond ]['scope_closer'];
} else {
// Global statement in the global namespace with file is being treated as scoped.
$end = ( $this->phpcsFile->numTokens + 1 );
}
for ( $ptr = $start; $ptr < $end; $ptr++ ) {
// Skip over nested functions, classes and the likes.
if ( isset( $this->skip_over[ $this->tokens[ $ptr ]['code'] ] ) ) {
if ( ! isset( $this->tokens[ $ptr ]['scope_closer'] ) ) {
// Live coding or parse error.
break;
}
$ptr = $this->tokens[ $ptr ]['scope_closer'];
continue;
}
if ( \T_VARIABLE !== $this->tokens[ $ptr ]['code'] ) {
continue;
}
if ( \in_array( $this->tokens[ $ptr ]['content'], $search, true ) === false ) {
// Not one of the variables we're interested in.
continue;
}
// Don't throw false positives for static class properties.
if ( $this->is_class_object_call( $ptr ) === true ) {
continue;
}
if ( true === $this->is_assignment( $ptr ) ) {
$this->maybe_add_error( $ptr );
continue;
}
// Check if this is a variable assignment within a `foreach()` declaration.
if ( $this->is_foreach_as( $ptr ) === true ) {
$this->maybe_add_error( $ptr );
}
}
} | php | {
"resource": ""
} |
q254999 | GlobalVariablesOverrideSniff.add_error | test | protected function add_error( $stackPtr, $data = array() ) {
if ( empty( $data ) ) {
$data[] = $this->tokens[ $stackPtr ]['content'];
}
$this->phpcsFile->addError(
'Overriding WordPress globals is prohibited. Found assignment to %s',
$stackPtr,
'Prohibited',
$data
);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.