_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q247400
CheckboxColumn.createUrl
validation
public function createUrl($action, $model, $key, $index) { if ($this->urlCreator instanceof Closure) { return call_user_func($this->urlCreator, $action, $model, $key, $index); } else { $params[0] = $this->controller ? $this->controller . '/' . $action : $action; return Url::toRoute($params); } }
php
{ "resource": "" }
q247401
FolderSearch.setProperties
validation
public function setProperties(array $properties) { $this->properties = []; foreach ($properties as $item) { $this->addPropertyRequest($item); } return $this; }
php
{ "resource": "" }
q247402
FolderSearch.addPropertyRequest
validation
public function addPropertyRequest($item) { if (!($item instanceof PropertyRequest)) { if (is_array($item)) { try { $item = new PropertyRequest($item); } catch (\Exception $e) { trigger_error('Could not auto-instantiate PropertyRequest. ' . $e->getMessage(), E_USER_WARNING); } } else { trigger_error('Array parameter item is not of expected type "PropertyRequest"!', E_USER_WARNING); } } $this->properties[] = $item; return $this; }
php
{ "resource": "" }
q247403
Timer.start
validation
public function start() { if ($this->isRunning()) { return; } $this->data["realmem_start"] = memory_get_usage(true); $this->data["emalloc_start"] = memory_get_usage(); $this->started = microtime(true); $this->running = true; }
php
{ "resource": "" }
q247404
Timer.getMemUsage
validation
public function getMemUsage($realmem = false) { if ($this->isRunning()) { $this->stop(); $this->start(); } return ($realmem !== false) ? $this->data["realmem"] : $this->data["emalloc"]; }
php
{ "resource": "" }
q247405
MetaData.setData
validation
public function setData($data) { if (is_array($data)) { $this->data = $data; return $this; } $this->data = json_decode($data, true); if (null === $this->data) { $this->data = $data; } return $this; }
php
{ "resource": "" }
q247406
MoodboardTemplateResponse.setOptions
validation
public function setOptions($options) { if (is_array($options)) { $this->options = $options; return $this; } $this->options = json_decode($options, true); if (null === $this->options) { $this->options = $options; } return $this; }
php
{ "resource": "" }
q247407
Printer.writeProgress
validation
protected function writeProgress($progress) { // Record progress so it can be written later instead of at start of line. $this->progress = !$this->flawless && $progress === '.' // If a previous error or exception occurred, replace '.' with red '!'. ? $this->formatWithColor('fg-red', '!') : $progress ; ++$this->numTestsRun; }
php
{ "resource": "" }
q247408
Printer.writePerformance
validation
protected function writePerformance($time) { $ms = round($time * 1000); foreach (self::$performanceThresholds as $colour => $threshold) { if ($ms > $threshold) { break; } } $this->writeWithColor($colour, " ($ms ms)"); }
php
{ "resource": "" }
q247409
Printer.writeAssertionFailure
validation
protected function writeAssertionFailure($assertionFailure) { $this->writeNewLine(); foreach (explode("\n", $assertionFailure) as $line) { $this->writeWithColor('fg-red', $line); } }
php
{ "resource": "" }
q247410
Printer.writeException
validation
protected function writeException($exception) { $this->writeNewLine(); do { $exceptionStack[] = $exception; } while ($exception = $exception->getPreviousWrapped()); // Parse nested exception trace line by line. foreach (explode("\n", $exception = array_shift($exceptionStack)) as $line) { // Print exception name and message. if ($exception && false !== $pos = strpos($line, $exception->getClassName() . ': ')) { $whitespace = str_repeat(' ', ($pos += strlen($exception->getClassName())) + 2); $this->writeWithColor('bg-red,fg-white', $whitespace); // Exception name. $this->writeWithColor('bg-red,fg-white', sprintf(' %s ', substr($line, 0, $pos)), false); // Exception message. $this->writeWithColor('fg-red', substr($line, $pos + 1)); $this->writeWithColor('bg-red,fg-white', $whitespace); $exception = array_shift($exceptionStack); continue; } $this->writeWithColor('fg-red', $line); } }
php
{ "resource": "" }
q247411
Printer.onAddError
validation
protected function onAddError(\Exception $e) { $this->writeProgressWithColor('fg-red,bold', 'E'); $this->exception = $e; $this->lastTestFailed = true; $this->flawless = false; }
php
{ "resource": "" }
q247412
Printer.onAddFailure
validation
protected function onAddFailure($e) { $this->writeProgressWithColor('fg-red,bold', 'F'); $this->failure = $e; $this->lastTestFailed = true; $this->flawless = false; }
php
{ "resource": "" }
q247413
Schema.setConfig
validation
public function setConfig( $host, $name = 'schema', DriverInterface $driver = null ) { $this->driver = \is_null($driver) ? new Driver\Json() : $driver; $this->path = $host; $this->name = $name; $this->file = $host . DIRECTORY_SEPARATOR . $name . '.' . $this->driver->getExtension(); return $this; }
php
{ "resource": "" }
q247414
Schema.read
validation
public function read($path, $file) { return $this->driver->read($this->root . $path, $file); }
php
{ "resource": "" }
q247415
Schema.delete
validation
protected function delete($path, $file) { return $this->driver->delete($this->root . $path, $file); }
php
{ "resource": "" }
q247416
Request.rightJoin
validation
public function rightJoin($table, $column, $operator = null, $value = null) { if ($column instanceof \Closure) { $where = new Where(); call_user_func_array($column, [ &$where ]); } else { $where = ( new Where()) ->where($column, $operator, $value); } $this->request[ 'rightJoin' ][ $table ][ 'table' ] = $table; $this->request[ 'rightJoin' ][ $table ][ 'where' ] = $where; return $this; }
php
{ "resource": "" }
q247417
Request.arrayUniqueMultidimensional
validation
public static function arrayUniqueMultidimensional(array $input) { /* Sérialise les données du tableaux. */ $serialized = array_map('serialize', $input); /* Supprime les doublons sérialisés. */ $unique = array_unique($serialized); /* Redonne les clés au tableau */ $output = array_intersect_key($input, $unique); /* Renvoie le tableau avec ses clés ré-indexé */ return array_values($output); }
php
{ "resource": "" }
q247418
Request.executeDelete
validation
protected function executeDelete() { foreach ($this->tableData as $key => $row) { if ($this->where && !$this->where->execute($row)) { continue; } unset($this->tableData[ $key ]); } $this->tableData = array_values($this->tableData); }
php
{ "resource": "" }
q247419
Request.keySort
validation
private function keySort($a, $b, $c = null) { $d = $c !== null ? $c : 1; if ($a == $b) { return 0; } return ($a > $b) ? 1 * $d : -1 * $d; }
php
{ "resource": "" }
q247420
Request.loadAllColumnsSchema
validation
private function loadAllColumnsSchema() { $schema = $this->tableSchema[ 'fields' ]; foreach ($this->request[ 'leftJoin' ] as $value) { $schemaTable = $this->schema->getSchemaTable($value[ 'table' ]); $schema = array_merge($schema, $schemaTable[ 'fields' ]); } foreach ($this->request[ 'rightJoin' ] as $value) { $schemaTable = $this->schema->getSchemaTable($value[ 'table' ]); $schema = array_merge($schema, $schemaTable[ 'fields' ]); } $this->request[ 'allColumnsSchema' ] = $schema; }
php
{ "resource": "" }
q247421
BugsnagHandler.write
validation
protected function write(array $record) { $severity = $this->getSeverity($record['level']); if (isset($record['context']['exception'])) { $this->client->notifyException( $record['context']['exception'], function (\Bugsnag\Report $report) use ($record, $severity) { $report->setSeverity($severity); if (isset($record['extra'])) { $report->setMetaData($record['extra']); } } ); } else { $this->client->notifyError( (string) $record['message'], (string) $record['formatted'], function (\Bugsnag\Report $report) use ($record, $severity) { $report->setSeverity($severity); if (isset($record['extra'])) { $report->setMetaData($record['extra']); } } ); } }
php
{ "resource": "" }
q247422
BugsnagHandler.getSeverity
validation
protected function getSeverity($errorCode) { if (isset($this->severityMapping[$errorCode])) { return $this->severityMapping[$errorCode]; } else { return $this->severityMapping[Logger::ERROR]; } }
php
{ "resource": "" }
q247423
Response.redirect
validation
public static function redirect($url = '', $status = 301, $headers = []) { $Response = new Response(); $Response->status($status); if (!empty($headers)) { $Response->headers($headers); } $Response->headers([ 'Location' => (new Router())->makeUrl($url), ]); return $Response; }
php
{ "resource": "" }
q247424
Messages.add
validation
public function add($type, $message, $redirect = null) { if (!isset($type) or !isset($message[0])) { return false; } // Replace any shorthand codes with their full version if (strlen(trim($type)) === 1) { $type = str_replace(['h', 'i', 'w', 'e', 's'], ['help', 'info', 'warning', 'error', 'success'], $type); } $router = new Router(); try { if (!in_array($type, $this->msgTypes)) { // Make sure it's a valid message type throw new BaseException('"' . strip_tags($type) . '" is not a valid message type!', 501); } } catch (BaseException $e) { $msg = null; if (ini_get('display_errors') === "on") { $msg .= '<pre>'; $msg .= 'Message: <b>' . $e->getMessage() . '</b><br><br>'; $msg .= 'Accept: ' . $_SERVER['HTTP_ACCEPT'] . '<br>'; if (isset($_SERVER['HTTP_REFERER'])) { $msg .= 'Referer: ' . $_SERVER['HTTP_REFERER'] . '<br><br>'; } $msg .= 'Request Method: ' . $_SERVER['REQUEST_METHOD'] . '<br><br>'; $msg .= 'Current file Path: <b>' . $this->router->currentPath() . '</b><br>'; $msg .= 'File Exception: ' . $e->getFile() . ':' . $e->getLine() . '<br><br>'; $msg .= 'Trace: <br>' . $e->getTraceAsString() . '<br>'; $msg .= '</pre>'; return Response::create($msg)->display(); } return Response::create($e->getMessage())->status(501)->display(); } $get = $this->driver->get('flash_messages'); $get[$type][] = $message; $this->driver->set('flash_messages', $get); if (!is_null($redirect)) { return $router->redirect($redirect, 301); } return true; }
php
{ "resource": "" }
q247425
Messages.display
validation
public function display($type = 'all', $print = false) { $messages = ''; $data = ''; if (in_array($type, $this->msgTypes)) { // Print a certain type of message? $flashMessages = $this->driver->get('flash_messages'); foreach ($flashMessages[$type] as $msg) { $messages .= $msg; } $data .= $messages; // Clear the viewed messages $this->clear($type); } elseif ($type === 'all') { // Print ALL queued messages $flashMessages = $this->driver->get('flash_messages'); foreach ($flashMessages as $type => $msgArray) { $messages = ''; foreach ($msgArray as $msg) { $messages .= $msg; } $data .= $messages; } // Clear ALL of the messages $this->clear(); } else { // Invalid Message Type? return false; } // Print everything to the screen or return the data if ($print) { echo $data; return null; } return $data; }
php
{ "resource": "" }
q247426
Messages.clear
validation
public function clear($type = 'all') { if ($type === 'all') { $this->driver->remove('flash_messages'); } else { $flashMessages = $this->driver->get('flash_messages'); unset($flashMessages[$type]); $this->driver->set('flash_messages', $flashMessages); } return true; }
php
{ "resource": "" }
q247427
TwigView.renderInclude
validation
public function renderInclude($name, $path = null) { $twigConfig = Config::load('twig'); $pathFile = pathFile($name); $folder = $pathFile[0]; $name = $pathFile[1]; $path = $twigConfig->get('setTemplateDir') . DIRECTORY_SEPARATOR . $folder . $name . $twigConfig->get('fileExtension', '.twig'); try { if (!is_file($path)) { throw new ViewException('Can not open template ' . $name . ' in: ' . $path); } $renderInclude = $this->twig->render($name, $this->assign); } catch (ViewException $e) { echo $e->getMessage() . '<br /> File: ' . $e->getFile() . '<br /> Code line: ' . $e->getLine() . '<br /> Trace: ' . $e->getTraceAsString(); exit(); } return $renderInclude; }
php
{ "resource": "" }
q247428
View.assign
validation
public function assign($name, $value) { if (!isset($this->view)) { throw new ViewException('Please Define view engine in app/View.php', 500); } return $this->view->assign($name, $value); }
php
{ "resource": "" }
q247429
View.render
validation
public function render($data, $type = null) { if (empty($type) or $type === 'html') { return Response::Create($this->renderInclude($data)); } elseif ($type === 'jsonp') { return $this->renderJSONP($data); } else { return $this->renderJSON($data); } }
php
{ "resource": "" }
q247430
View.renderJSONP
validation
public function renderJSONP($data) { $callback = null; if (isset($_GET['callback'])) { $callback = $_GET['callback']; } exit(Response::Create($callback . '(' . json_encode($data) . ')')->headers(['Content-Type' => 'application/jsonp'])->display()); }
php
{ "resource": "" }
q247431
View.renderJSON
validation
public function renderJSON($data, $status = 200) { exit(Response::Create(json_encode($data))->status($status)->headers(['Content-Type' => 'application/json'])->display()); }
php
{ "resource": "" }
q247432
Core.run
validation
public function run($controller = null, $action = null, $args = []) { $this->router = $this->router->boot($this); if (is_null($controller ?? null) and is_null($action ?? null)) { $this->router->parseGets(); $controller = $this->router->controller; $action = $this->router->action; $namespace = $this->router->namespace; } $loader = new Loader($this->baseClass); $Controller = $loader->loadController($controller, $namespace ?? '\\'); $response = []; if (method_exists($Controller, 'start')) { $response[] = ['start', []]; } if (method_exists($Controller, 'init')) { $response[] = ['init', []]; } if (method_exists($Controller, $action) or is_callable([$Controller, $action])) { $response[] = [$action, $args]; } if (method_exists($Controller, 'end')) { $response[] = ['end', []]; } foreach ($response as $key => $data) { $run = call_user_func_array([$Controller, $data[0]], $data[1]); if ($run instanceof Response) { if (isset($this->debug)) { $this->debug->addHeader(['X-DF-Debug-Controller' => $controller]); $this->debug->addHeader(['X-DF-Debug-Method' => $action]); $run->headers($this->debug->getHeader()); } return $run->display(); } } return true; }
php
{ "resource": "" }
q247433
ManagerModule.loadRoutes
validation
protected function loadRoutes($path) { $this->app->config['router']['routes'] = array_merge($this->app->config['router']['routes'] ?? [], (require $path)['routes']); }
php
{ "resource": "" }
q247434
ManagerModule.loadModels
validation
protected function loadModels($path) { $this->app->config['model'] = array_unique(array_merge($this->app->config['model'] ?? [], $path)); }
php
{ "resource": "" }
q247435
ManagerModule.loadControllers
validation
protected function loadControllers($path) { $this->app->config['controller'] = array_unique(array_merge($this->app->config['controller'] ?? [], $path)); }
php
{ "resource": "" }
q247436
Router.findControllerFiles
validation
protected function findControllerFiles() { $result = []; foreach ($this->controllerDirs as $dir) { $directoryIterator = new \RecursiveDirectoryIterator($dir); $iterator = new \RecursiveIteratorIterator($directoryIterator); $files = new \RegexIterator($iterator, '/\.php$/i', \RecursiveRegexIterator::GET_MATCH); foreach ($files as $k => $v) { $result[$k] = filemtime($k); } } return $result; }
php
{ "resource": "" }
q247437
Router.isActive
validation
public function isActive(string $url) { if ($this->makeUrl($url, true) === str_replace($this->uri, '', $_SERVER['REQUEST_URI'])) { return true; } return false; }
php
{ "resource": "" }
q247438
Router.parseParams
validation
protected function parseParams($routing, $params) { $return = null; foreach ($params as $key => $value) { $return .= str_replace(['[name]', '[value]'], [$key, $value], $routing); } return $return; }
php
{ "resource": "" }
q247439
Router.parseGets
validation
public function parseGets() { $request = preg_replace('!' . $this->uri . '(.*)$!i', '$1', $_SERVER['REQUEST_URI']); if (defined('MOD_REWRITE') and MOD_REWRITE === true) { if (substr($request, -1) != '/') { $request .= '/'; } $parseUrl = $this->parseUrl($request); $this->namespace = $parseUrl['v']['namespace'] ?? ''; parse_str($parseUrl['sVars'], $gets); $this->controller = !empty($gets['task']) ? $gets['task'] : $this->routeMap['NAME_CONTROLLER']; unset($gets['task']); $this->action = !empty($gets['action']) ? $gets['action'] : $this->routeMap['NAME_METHOD']; unset($gets['action']); $_GET = array_merge($_GET, $gets); } else { $this->controller = !empty($_GET['task']) ? $_GET['task'] : $this->routeMap['NAME_CONTROLLER']; $this->action = !empty($_GET['action']) ? $_GET['action'] : $this->routeMap['NAME_METHOD']; } $_GET['task'] = $this->controller; $_GET['action'] = $this->action; }
php
{ "resource": "" }
q247440
Router.transformParam
validation
protected function transformParam($param, $k) { if (isset($this->routeMapParse[$k][$param]) and !is_array($this->routeMapParse[$k][$param])) { return $this->routeMapParse[$k][$param]; } else { return '(.+?)'; } }
php
{ "resource": "" }
q247441
Router.currentPath
validation
public function currentPath() { $request = preg_replace('!' . $this->uri . '(.*)$!i', '$1', $_SERVER['REQUEST_URI']); if (defined('MOD_REWRITE') and MOD_REWRITE === true) { if (substr($request, -1) != '/') { $request .= '/'; } $parseUrl = $this->parseUrl($request); $gets = $parseUrl['sVars']; } else { $gets = $_SERVER['QUERY_STRING']; } return $gets; }
php
{ "resource": "" }
q247442
Router.addRoute
validation
public function addRoute($newRoute) { $this->routeMap['routes'] = array_merge($this->routeMap['routes'], $newRoute); $this->routeMapParse = array_merge($this->routeMapParse, $newRoute); }
php
{ "resource": "" }
q247443
Model.methodFail
validation
public function methodFail($errors = null) { if ($errors === null) { return $this->methodResult(false); } if (!is_array($errors)) { $errors = [$errors]; } return $this->methodResult(false, ['errors' => $errors]); }
php
{ "resource": "" }
q247444
EventHandler.start
validation
public static function start($apiKey, $notifyOnWarning = false, array $options = array()) { if (!isset(self::$instance)) { $config = new Configuration($apiKey, $options); $client = new Client($config); self::$instance = new self($client, $notifyOnWarning); if (null !== $config->get('errorReportingLevel')) { self::$instance->addErrorFilter(new ErrorReporting($config)); } self::$instance->addExceptionFilter(new AirbrakeExceptionFilter()); set_error_handler(array(self::$instance, 'onError')); set_exception_handler(array(self::$instance, 'onException')); register_shutdown_function(array(self::$instance, 'onShutdown')); } return self::$instance; }
php
{ "resource": "" }
q247445
EventHandler.onError
validation
public function onError($type, $message, $file = null, $line = null, $context = null) { // This will catch silenced @ function calls and keep them quiet. if (ini_get('error_reporting') == 0) { return true; } if (isset($this->fatalErrors[$type])) { throw new Exception($message); } if ($this->shouldNotifyError($type, $message, $file, $line, $context)) { // Make sure we pass in the current backtrace, minus this function call. $backtrace = debug_backtrace(); array_shift($backtrace); $this->airbrakeClient->notifyOnError($message, $backtrace); return true; } return true; }
php
{ "resource": "" }
q247446
EventHandler.onException
validation
public function onException(\Exception $exception) { if ($this->shouldNotifyException($exception)) { $this->airbrakeClient->notifyOnException($exception); } return true; }
php
{ "resource": "" }
q247447
EventHandler.onShutdown
validation
public function onShutdown() { // If the instance was unset, then we shouldn't run. if (self::$instance == null) { return; } // This will help prevent multiple calls to this, incase the shutdown handler was declared // multiple times. This only should occur in unit tests, when the handlers are created // and removed repeatedly. As we cannot remove shutdown handlers, this prevents us from // calling it 1000 times at the end. self::$instance = null; // Get the last error if there was one, if not, let's get out of here. if (!$error = error_get_last()) { return; } // Don't notify on warning if not configured to. if (!$this->shouldNotifyError($error['type'], $error['message'], $error['file'], $error['line'])) { return; } // Build a fake backtrace, so we at least can show where we came from. $backtrace = array( array( 'file' => $error['file'], 'line' => $error['line'], 'function' => '', 'args' => array(), ) ); $this->airbrakeClient->notifyOnError('[Improper Shutdown] '.$error['message'], $backtrace); }
php
{ "resource": "" }
q247448
Record.set
validation
public function set($key, $value) { if ($this->exists($key)) { $this->dataStore[$key] = $value; } }
php
{ "resource": "" }
q247449
Record.load
validation
public function load($data) { if (!is_array($data) && !$data instanceof \stdClass) { return; } foreach ($data as $key => $value) { $this->set($key, $value); } }
php
{ "resource": "" }
q247450
Client.notifyOnError
validation
public function notifyOnError($message, array $backtrace = null, $extraParams = null) { if (!$backtrace) { $backtrace = debug_backtrace(); if (count($backtrace) > 1) { array_shift($backtrace); } } $notice = new Notice; $notice->load(array( 'errorClass' => 'PHP::Error', 'backtrace' => $backtrace, 'errorMessage' => $message, 'extraParameters' => $extraParams, )); return $this->notify($notice); }
php
{ "resource": "" }
q247451
Client.notifyOnException
validation
public function notifyOnException(Exception $e, $extraParams = null) { $notice = new Notice; $notice->load(array( 'errorClass' => get_class($e), 'backtrace' => $this->cleanBacktrace($e->getTrace() ?: debug_backtrace()), 'errorMessage' => $e->getMessage().' in '.$this->cleanFilePath($e->getFile()).' on line '.$e->getLine(), 'extraParameters' => $extraParams, )); return $this->notify($notice); }
php
{ "resource": "" }
q247452
Client.cleanBacktrace
validation
protected function cleanBacktrace($backtrace) { foreach ($backtrace as &$item) { if (isset($item['file'])) { $item['file'] = $this->cleanFilePath($item['file']); } unset($item['args']); } return $backtrace; }
php
{ "resource": "" }
q247453
Notice.array2Node
validation
protected function array2Node($parentNode, $key, $params) { if (count($params) == 0) { return; } $node = $parentNode->addChild($key); foreach ($params as $key => $value) { if (is_array($value) || is_object($value)) { $value = json_encode((array) $value); } // htmlspecialchars() is needed to prevent html characters from breaking the node. $node->addChild('var', htmlspecialchars($value)) ->addAttribute('key', $key); } }
php
{ "resource": "" }
q247454
Filter.filter
validation
public function filter(&$array) { $current = &$array; $keys = array_keys($this->keyParts); $lastElement = end($keys); /** * This code is ugly and complicated because PHP has no way of unsetting * arbitrary depths inside arrays. * * The intended functionality is if you create a filter like: * 'form[subform][id]' then $_POST['form']['subform']['id'] will be * unset. This format was chosen because it's also how you would * represent that structure inside a form element name in your markup. * * It all works by keeping a reference to the current depth of the array, * iterating over key_parts (see splitKeyName), checking if the iterated * value exists as a key of the current reference and then setting the * current reference to be that key. If it's the last element of the * iteration then this value needs to be filtered and is removed. */ foreach ($this->keyParts as $index => $keyPart) { if (!isset($current[$keyPart])) { break; } if ($index == $lastElement) { unset($current[$keyPart]); break; } $current = &$current[$keyPart]; } }
php
{ "resource": "" }
q247455
Configuration.initialize
validation
protected function initialize() { if ($this->get('serverData') === null) { $this->set('serverData', (array) $_SERVER); } if ($this->get('getData') === null) { $this->set('getData', (array) $_GET); } if ($this->get('postData') === null) { $this->set('postData', (array) $_POST); } if ($this->get('sessionData') === null && isset($_SESSION)) { $this->set('sessionData', (array) $_SESSION); } $serverData = $this->get('serverData'); if (!$this->get('projectRoot')) { $projectRoot = isset($serverData['_']) ? $serverData['_'] : $serverData['DOCUMENT_ROOT']; $this->set('projectRoot', $projectRoot); } if (!$this->get('url')) { if (isset($serverData['REDIRECT_URL'])) { $this->set('url', $serverData['REDIRECT_URL']); } elseif (isset($serverData['SCRIPT_NAME'])) { $this->set('url', $serverData['SCRIPT_NAME']); } } if (!$this->get('hostname')) { $this->set('hostname', isset($serverData['HTTP_HOST']) ? $serverData['HTTP_HOST'] : 'No Host'); } $protocol = $this->get('secure') ? 'https' : 'http'; $endPoint = $this->get('apiEndPoint') ?: $protocol . '://' . $this->get('host') . $this->get('resource'); $this->set('apiEndPoint', $endPoint); }
php
{ "resource": "" }
q247456
Configuration.getParameters
validation
public function getParameters() { $parameters = $this->getUnfilteredParameters(); foreach ($this->parameterFilters as $filter) { /** @var \Airbrake\Filter\FilterInterface $filter */ $filter->filter($parameters); } return $parameters; }
php
{ "resource": "" }
q247457
Utils.realmNameToSlug
validation
public static function realmNameToSlug(string $name): string { $name = \mb_strtolower($name, 'UTF-8'); $slug = \str_replace(static::$replaceTable[0], static::$replaceTable[1], $name); $slug = \preg_replace(static::$regexTable[0], static::$regexTable[1], $slug); return \trim((string) $slug, '-'); }
php
{ "resource": "" }
q247458
Utils.thumbnailToId
validation
public static function thumbnailToId(string $thumbnailUrl): string { if (1 !== \preg_match('/\/([\d]+)\/([\d]+)(\-avatar\.jpg)$/', $thumbnailUrl, $match)) { throw new \RuntimeException(\vsprintf('Invalid thumbnail URL "%s"', [ $thumbnailUrl, ])); } return ltrim($match[1].$match[2], '0'); }
php
{ "resource": "" }
q247459
ThreeScaleAuthorizeResponseUsageReport.getPeriodStart
validation
public function getPeriodStart() { if (is_null($this->parsedPeriodStart)) { $this->parsedPeriodStart = strtotime($this->periodStart); } return $this->parsedPeriodStart; }
php
{ "resource": "" }
q247460
ThreeScaleAuthorizeResponseUsageReport.getPeriodEnd
validation
public function getPeriodEnd() { if (is_null($this->parsedPeriodEnd)) { $this->parsedPeriodEnd = strtotime($this->periodEnd); } return $this->parsedPeriodEnd; }
php
{ "resource": "" }
q247461
ThreeScaleClient.authorize
validation
public function authorize($appId, $appKey = null, $credentials_or_service_id, $usage = null) { $url = $this->getHost() . "/transactions/authorize.xml"; $params = array('app_id' => $appId); if ($credentials_or_service_id instanceof ThreeScaleClientCredentials ) { $params['service_token'] = $credentials_or_service_id->service_token; $params['service_id'] = $credentials_or_service_id->service_id; } else { $params['provider_key'] = $this->getProviderKey(); $params['service_id'] = $credentials_or_service_id; } if ($appKey) { $params['app_key'] = $appKey; } if ($usage) { $params['usage'] = $usage; } $httpResponse = $this->httpClient->get($url, $params); if (self::isHttpSuccess($httpResponse)) { return $this->buildAuthorizeResponse($httpResponse->body); } else { return $this->processError($httpResponse); } }
php
{ "resource": "" }
q247462
ThreeScaleClient.setHttpClient
validation
public function setHttpClient($httpClient) { if (is_null($httpClient)) { $httpClient = new Curl; $threeScaleVersion = new ThreeScaleVersion(); $version = $threeScaleVersion->getVersion(); $httpClient->options['CURLOPT_FOLLOWLOCATION'] = false; $httpClient->headers['X-3scale-User-Agent'] = 'plugin-php-v'. $version; } $this->httpClient = $httpClient; }
php
{ "resource": "" }
q247463
AbstractFileProvider.getElevation
validation
public function getElevation($latitude, $longitude) { if ($latitude === 0.0 && $longitude === 0.0) { return false; } if (!$this->locationIsInBounds($latitude, $longitude)) { throw new InvalidArgumentException( sprintf('Location (%f, %f) is out of bounds ([-%f, %f], [-%f, %f]).', $latitude, $longitude, static::MAX_LATITUDE, static::MAX_LATITUDE, static::MAX_LONGITUDE, static::MAX_LONGITUDE ) ); } $filename = $this->getFilenameFor($latitude, $longitude); if ($this->CurrentFilename !== $filename) { $this->openResource($filename); } return $this->getElevationFromResource($latitude, $longitude); }
php
{ "resource": "" }
q247464
AclModule.getMenuPresence
validation
public function getMenuPresence() { return [ 'id' => 'simple-acl', 'type' => MenuPresenceType::GROUP, 'label' => 'Access Control', 'children' => [ [ 'id' => 'simple-acl-users', 'type' => MenuPresenceType::ACTION, 'label' => 'Users', 'permissions' => 'acl.users.show', 'action' => $this->core->prefixRoute('acl.users.index'), 'parameters' => [], ], [ 'id' => 'simple-acl-create-user', 'type' => MenuPresenceType::ACTION, 'label' => 'New User', 'permissions' => 'acl.users.create', 'action' => $this->core->prefixRoute('acl.users.create'), 'parameters' => [], ], [ 'id' => 'simple-acl-roles', 'type' => MenuPresenceType::ACTION, 'label' => 'Roles', 'permissions' => 'acl.roles.show', 'action' => $this->core->prefixRoute('acl.roles.index'), 'parameters' => [], ], ] ]; }
php
{ "resource": "" }
q247465
Disk.removeDir
validation
public function removeDir(): bool { if (!$this->isDir()) { throw new AccessDeniedException(sprintf('unable to remove directory for path: "%s"', $this->path->raw), 500); } try { $iterator = $this->getIterator(true, \RecursiveIteratorIterator::CHILD_FIRST); /** @var \SplFileInfo $file */ foreach ($iterator as $splFile) { // file not readable if (!$splFile->isReadable()) { throw new AccessDeniedException(sprintf('unable to access file for path: "%s"', $splFile->getPathname()), 500); } // try to remove files/dirs/links switch ($splFile->getType()) { case 'dir': rmdir($splFile->getRealPath()); break; case 'link': unlink($splFile->getPathname()); break; default: unlink($splFile->getRealPath()); } } return rmdir($this->path->raw); } finally { $this->selfdestruct = false; $this->path->reload(); } }
php
{ "resource": "" }
q247466
Disk.cd
validation
public function cd(array $path): void { array_unshift($path, $this->path); $this->path = new Path($path); }
php
{ "resource": "" }
q247467
AdditionalService.isValid
validation
public function isValid() { // alternative pickup point if($this->service_code == 2106) { if($this->getSpecifier('pickup_point_id') === null) return false; } // cash on delivery (Postiennakko/Bussiennakko) if($this->service_code == 3101) { $expected_params = array('amount', 'account', 'reference', 'codbic'); foreach($expected_params as $param) { if($this->getSpecifier($param) === null) return false; } } // multipacket shipment requires package count if($this->service_code == 3102) { if($this->getSpecifier('count') === null) return false; if(!is_numeric($this->getSpecifier('count'))) return false; } if($this->service_code == 3111) { if($this->getSpecifier('insurancevalue') === null) return false; } if($this->service_code == 3120) { if($this->getSpecifier('deliverytime')) return false; } if($this->service_code == 3143) { if($this->getSpecifier('lqweight') === null or $this->getSpecifier('lqcount') === null) return false; } if(!is_numeric($this->service_code)) { return false; } return true; }
php
{ "resource": "" }
q247468
FileSystem.removeOnFree
validation
public function removeOnFree(bool $activate = true): self { $this->storage->removeOnFree($activate); return $this; }
php
{ "resource": "" }
q247469
GeoTIFFReader.goToIFDEntries
validation
protected function goToIFDEntries() { fseek($this->FileResource, 4); $ifdOffsetFormat = $this->isLittleEndian() ? 'VIFDoffset' : 'NIFDoffset'; $data = unpack($ifdOffsetFormat, fread($this->FileResource, 4)); fseek($this->FileResource, $data['IFDoffset']); }
php
{ "resource": "" }
q247470
PermissionsController.available
validation
public function available() { return $this->core->api()->response( $this->makeContainer( $this->core->modules()->getAllPermissions() ) ); }
php
{ "resource": "" }
q247471
PermissionsController.module
validation
public function module($key) { if ( ! $this->core->modules()->has($key)) { abort(404, 'Module not loaded'); } return $this->core->api()->response( $this->makeContainer( $this->core->modules()->getModulePermissions($key) ) ); }
php
{ "resource": "" }
q247472
PermissionsController.used
validation
public function used() { return $this->core->api()->response( $this->makeContainer( $this->core->auth()->getAllPermissions() ) ); }
php
{ "resource": "" }
q247473
Shipment.setPickupPoint
validation
public function setPickupPoint($pickup_point_id) { $service = new AdditionalService(); $service->setServiceCode(2106); // alternative pickup point $service->addSpecifier('pickup_point_id', $pickup_point_id); $this->addAdditionalService($service); }
php
{ "resource": "" }
q247474
SimpleXMLElement.addChild
validation
public function addChild($key, $value = null, $namespace = null) { if ( $value != null ) { $value = htmlspecialchars($value, ENT_XML1); } return parent::addChild($key, $value, $namespace); }
php
{ "resource": "" }
q247475
Binary.applyAccessMode
validation
protected function applyAccessMode(int $mode): void { if ($this->mode === self::MODE_CLOSED) { // set new mode $this->mode = $mode; return; } elseif ($mode === $this->mode) { // nothing to do return; } // mode-switching detected throw new AccessDeniedException('unable to switch access-mode for existing binary file handle', 500); }
php
{ "resource": "" }
q247476
Directory.mkdir
validation
public function mkdir(): self { if (!$this->storage->isDir()) { if (!$this->storage->mkdir()) { throw new AccessDeniedException(sprintf('unable to create directory at: "%s"', $this->storage->path()->raw), 500); } } return $this; }
php
{ "resource": "" }
q247477
PathFinder.try
validation
public static function try(array $paths): Storage { foreach ($paths as $diskpath) { if (is_string($diskpath)) { if (file_exists($diskpath)) { return new Storage\Disk($diskpath); } } elseif ($diskpath instanceof Path) { if ($diskpath->fileInfo()->isFile() || $diskpath->fileInfo()->isDir()) { return new Storage\Disk($diskpath); } } elseif ($diskpath instanceof Storage) { if ($diskpath->isFile() || $diskpath->isDir()) { return $diskpath; } } elseif ($diskpath instanceof FileSystem) { if ($diskpath->isFile() || $diskpath->isDir()) { return $diskpath->storage(); } } else { throw new UnexpectedValueException(sprintf('invalid search-path of type \'%s\'', is_object($diskpath) ? get_class($diskpath) : gettype($diskpath)), 500); } } throw new FileNotFoundException('file not found', 404); }
php
{ "resource": "" }
q247478
Width.getOptions
validation
private static function getOptions() { return [ '1/6' => Craft::t('width-fieldtype', '1/6'), '1/5' => Craft::t('width-fieldtype', '1/5'), '1/4' => Craft::t('width-fieldtype', '1/4'), '1/3' => Craft::t('width-fieldtype', '1/3'), '2/5' => Craft::t('width-fieldtype', '2/5'), '1/2' => Craft::t('width-fieldtype', '1/2'), '3/5' => Craft::t('width-fieldtype', '3/5'), '2/3' => Craft::t('width-fieldtype', '2/3'), '3/4' => Craft::t('width-fieldtype', '3/4'), '4/5' => Craft::t('width-fieldtype', '4/5'), '5/6' => Craft::t('width-fieldtype', '5/6'), 'full' => Craft::t('width-fieldtype', 'Full'), ]; }
php
{ "resource": "" }
q247479
File.write
validation
public function write(string $content, bool $append = false, int $mode = LOCK_EX): self { $this->checkFileWritePermissions(); if (!$this->storage->writeFile($content, $append, $mode)) { throw new AccessDeniedException('unable to write file-content', 403); } return $this; }
php
{ "resource": "" }
q247480
MimeType.getExtensionFor
validation
public static function getExtensionFor(string $mimetype): ?string { $extensions = static::getExtensions(); if (false !== $match = array_search($mimetype, $extensions, true)) { return $match; } return null; }
php
{ "resource": "" }
q247481
MimeType.getMimeFor
validation
public static function getMimeFor(string $extension): ?string { $extensions = static::getExtensions(); if (isset($extensions[$extension])) { return $extensions[$extension]; } return null; }
php
{ "resource": "" }
q247482
Path.normalizePathComponents
validation
protected function normalizePathComponents(): array { $components = []; // fetch key of first and last item $keys = array_keys($this->components); $positionStart = reset($keys); $positionEnd = end($keys); // iterate through all path-components foreach ($this->components as $position => $component) { // parse single path-component $path = self::normalize($component, $position === $positionStart, $position === $positionEnd); // normalize path $path = str_replace(['/', '\\', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR], DIRECTORY_SEPARATOR, $path); if ($position === $positionStart && $path === DIRECTORY_SEPARATOR) { $components[] = DIRECTORY_SEPARATOR; } elseif ($position === $positionStart) { $components[] = rtrim($path, DIRECTORY_SEPARATOR); } else { $components[] = trim($path, DIRECTORY_SEPARATOR); } } return $components; }
php
{ "resource": "" }
q247483
Path.reload
validation
public function reload(): self { // we don't need to reload if the path isn't loaded in the first place if ($this->loaded === false) { return $this; } // reset path- and fileInfo-cache clearstatcache(false, $this->raw); $this->loaded = false; return $this; }
php
{ "resource": "" }
q247484
Path.isInOpenBasedir
validation
public function isInOpenBasedir() : bool { if (!$this->loaded) { $this->resolvePath(); } /** * fetch openBaseDir * @var string[] */ static $openBaseDirs = null; if ($openBaseDirs === null) { $openBaseDirs = array_filter(explode(':', trim(ini_get('open_basedir'))), function ($dir): bool { return !empty($dir); }); } // no basedir specified, therefor assume system is local only if (empty($openBaseDirs)) { return true; } // check against open_basedir paths foreach ((array) $openBaseDirs as $dir) { $dir = realpath($dir); if (stripos($this->raw, $dir) === 0) { return true; } } return false; }
php
{ "resource": "" }
q247485
RolesController.getPermissionGroupIndex
validation
protected function getPermissionGroupIndex($groups) { $index = []; foreach ($groups as $key => $presence) { $permissions = $presence->permissions(); if ( ! $permissions) { continue; } if ( ! is_array($permissions)) { $permissions = [ $permissions ]; } foreach ($permissions as $permission) { $index[ $permission ] = $key; } } return $index; }
php
{ "resource": "" }
q247486
DirectoryIterator.storages
validation
public function storages(): \Generator { /** @var Storage $storage */ foreach ($this->storage->list($this->recursive) as $storage) { // apply early lowlevel filters foreach ($this->storageFilters as $filter) { if (!call_user_func($filter, $storage)) { continue 2; // continue outer storage-loop } } yield $storage; } }
php
{ "resource": "" }
q247487
DirectoryIterator.files
validation
public function files(?int $constraints = null): \Generator { foreach ($this->all($constraints) as $file) { if (!$file->isDir()) { yield $file; } } }
php
{ "resource": "" }
q247488
DirectoryIterator.dirs
validation
public function dirs(?int $constraints = null): \Generator { foreach ($this->all($constraints) as $directory) { if ($directory->isDir()) { yield $directory; } } }
php
{ "resource": "" }
q247489
PermissionRepository.getAll
validation
public function getAll() { $permissions = $this->modules->getAllPermissions(); $permissions = array_merge($permissions, $this->getCustom()); return array_unique($permissions); }
php
{ "resource": "" }
q247490
PermissionRepository.prepareForPresentation
validation
protected function prepareForPresentation() { if ($this->prepared) { return; } $this->permissionGroups = new Collection; $this->ungroupedPermissions = []; $this->groupedPermissionIndex = []; $this->loadPermissionsFromModules() ->loadCustomPermissions() ->loadCustomPermissionGroups() ->addUngroupedPermissionGroup() ->filterEmptyGroups(); }
php
{ "resource": "" }
q247491
PermissionRepository.filterNestedEmptyGroups
validation
protected function filterNestedEmptyGroups(AclPresenceInterface $presence) { if ($presence['type'] !== AclPresenceType::GROUP) { return 1; } $permissions = $presence->permissions(); if ( ! $permissions) { return 0; } if (is_string($permissions)) { return 1; } return count($permissions); }
php
{ "resource": "" }
q247492
PermissionRepository.createGroupPresence
validation
protected function createGroupPresence($id, $label, array $children = []) { return new AclPresence([ 'type' => AclPresenceType::GROUP, 'id' => $id, 'label' => $label, 'children' => $children, ]); }
php
{ "resource": "" }
q247493
PermissionRepository.createUngroupedGroupPresence
validation
protected function createUngroupedGroupPresence($id = null) { $id = $id ?: 'automatic-ungrouped-permissions'; return new AclPresence([ 'type' => AclPresenceType::GROUP, 'id' => $id, 'label' => 'acl.ungrouped-permissions', 'translated' => true, ]); }
php
{ "resource": "" }
q247494
PermissionRepository.normalizeAclPresence
validation
protected function normalizeAclPresence($data) { if ($data instanceof AclPresenceInterface) { $data = [ $data ]; } elseif (is_array($data) && ! Arr::isAssoc($data)) { $presences = []; // If presences are just groupless permissions return them as-is foreach ($data as $nestedData) { if (is_string($nestedData)) { $presences[] = $nestedData; } else { $presences[] = new AclPresence($nestedData); } } $data = $presences; } else { $data = [ new AclPresence($data) ]; } /** @var AclPresenceInterface[]|string[] $data */ return $data; }
php
{ "resource": "" }
q247495
Client.fetchShippingLabels
validation
public function fetchShippingLabels($trackingCodes) { $id = str_replace('.', '', microtime(true)); $xml = new \SimpleXMLElement('<eChannel/>'); $routing = $xml->addChild('ROUTING'); $routing->addChild('Routing.Account', $this->api_key); $routing->addChild('Routing.Id', $id); $routing->addChild('Routing.Key', md5("{$this->api_key}{$id}{$this->secret}")); $label = $xml->addChild('PrintLabel'); $label['responseFormat'] = 'File'; foreach($trackingCodes as $trackingCode) { $label->addChild('TrackingCode', $trackingCode); } $response = $this->doPost('/prinetti/get-shipping-label', null, $xml->asXML()); $response_xml = @simplexml_load_string($response); if(!$response_xml) { throw new \Exception("Failed to load response xml"); } $this->response = $response_xml; if($response_xml->{'response.status'} != 0) { throw new \Exception("Error: {$response_xml->{'response.status'}}, {$response_xml->{'response.message'}}"); } return $response_xml; }
php
{ "resource": "" }
q247496
Client.searchPickupPoints
validation
public function searchPickupPoints($postcode = null, $street_address = null, $country = null, $service_provider = null, $limit = 5) { if ( ($postcode == null && $street_address == null) || (trim($postcode) == '' && trim($street_address) == '') ) { return '[]'; } $post_params = array( 'postcode' => (string) $postcode, 'address' => (string) $street_address, 'country' => (string) $country, 'service_provider' => (string) $service_provider, 'limit' => (int) $limit ); return $this->doPost('/pickup-points/search', $post_params); }
php
{ "resource": "" }
q247497
Client.searchPickupPointsByText
validation
public function searchPickupPointsByText($query_text, $service_provider = null, $limit = 5) { if ( $query_text == null || trim($query_text) == '' ) { return '[]'; } $post_params = array( 'query' => (string) $query_text, 'service_provider' => (string) $service_provider, 'limit' => (int) $limit ); return $this->doPost('/pickup-points/search', $post_params); }
php
{ "resource": "" }
q247498
SimpleRbacAuthorize.authorize
validation
public function authorize($user, Request $request) { $roleField = $this->_config['roleField']; if (!isset($user[$roleField])) { throw new RuntimeException(sprintf('The role field `%s` does not exist!', $roleField)); } if (is_string($user[$roleField])) { $user[$roleField] = array($user[$roleField]); } if ($this->authorizeByPrefix($user[$roleField], $request)) { return true; } if ($this->authorizeByControllerAndAction($user, $request)) { return true; } return false; }
php
{ "resource": "" }
q247499
SimpleRbacAuthorize.authorizeByControllerAndAction
validation
public function authorizeByControllerAndAction($user, Request $request) { $roleField = $this->_config['roleField']; extract($this->getControllerNameAndAction($request)); $actionMap = $this->getActionMap(); if (isset($actionMap[$name]['*'])) { if ($this->_isAllowedRole($user[$roleField], $actionMap[$name]['*'])) { return true; } } if (isset($actionMap[$name][$action])) { if ($this->_isAllowedRole($user[$roleField], $actionMap[$name][$action])) { return true; } } if ($this->config('undefinedActionsAreAllowed') === true) { return true; } return false; }
php
{ "resource": "" }