_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q254500
MigrationRunner.addHistory
test
protected function addHistory(string $version) { $this->db->table($this->table) ->insert([ 'version' => $version, 'name' => $this->name, 'group' => $this->group, 'namespace' => $this->namespace, 'time' => time(), ]); if (is_cli()) { $this->cliMessages[] = "\t" . CLI::color(lang('Migrations.added'), 'yellow') . "($this->namespace) " . $version . '_' . $this->name; } }
php
{ "resource": "" }
q254501
MigrationRunner.removeHistory
test
protected function removeHistory(string $version) { $this->db->table($this->table) ->where('version', $version) ->where('group', $this->group) ->where('namespace', $this->namespace) ->delete(); if (is_cli()) { $this->cliMessages[] = "\t" . CLI::color(lang('Migrations.removed'), 'yellow') . "($this->namespace) " . $version . '_' . $this->name; } }
php
{ "resource": "" }
q254502
MigrationRunner.ensureTable
test
public function ensureTable() { if ($this->tableChecked || $this->db->tableExists($this->table)) { return; } $forge = \Config\Database::forge($this->db); $forge->addField([ 'version' => [ 'type' => 'VARCHAR', 'constraint' => 255, 'null' => false, ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => 255, 'null' => false, ], 'group' => [ 'type' => 'VARCHAR', 'constraint' => 255, 'null' => false, ], 'namespace' => [ 'type' => 'VARCHAR', 'constraint' => 255, 'null' => false, ], 'time' => [ 'type' => 'INT', 'constraint' => 11, 'null' => false, ], ]); $forge->createTable($this->table, true); $this->tableChecked = true; }
php
{ "resource": "" }
q254503
Validation.check
test
public function check($value, string $rule, array $errors = []): bool { $this->reset(); $this->setRule('check', null, $rule, $errors); return $this->run([ 'check' => $value, ]); }
php
{ "resource": "" }
q254504
Validation.withRequest
test
public function withRequest(RequestInterface $request): ValidationInterface { if (in_array($request->getMethod(), ['put', 'patch', 'delete'])) { $this->data = $request->getRawInput(); } else { $this->data = $request->getVar() ?? []; } return $this; }
php
{ "resource": "" }
q254505
Validation.setRule
test
public function setRule(string $field, string $label = null, string $rules, array $errors = []) { $this->rules[$field] = [ 'label' => $label, 'rules' => $rules, ]; $this->customErrors = array_merge($this->customErrors, [ $field => $errors, ]); return $this; }
php
{ "resource": "" }
q254506
Validation.getRuleGroup
test
public function getRuleGroup(string $group): array { if (! isset($this->config->$group)) { throw ValidationException::forGroupNotFound($group); } if (! is_array($this->config->$group)) { throw ValidationException::forGroupNotArray($group); } return $this->config->$group; }
php
{ "resource": "" }
q254507
Validation.setRuleGroup
test
public function setRuleGroup(string $group) { $rules = $this->getRuleGroup($group); $this->rules = $rules; $errorName = $group . '_errors'; if (isset($this->config->$errorName)) { $this->customErrors = $this->config->$errorName; } }
php
{ "resource": "" }
q254508
Validation.loadRuleSets
test
protected function loadRuleSets() { if (empty($this->ruleSetFiles)) { throw ValidationException::forNoRuleSets(); } foreach ($this->ruleSetFiles as $file) { $this->ruleSetInstances[] = new $file(); } }
php
{ "resource": "" }
q254509
Validation.setError
test
public function setError(string $field, string $error): ValidationInterface { $this->errors[$field] = $error; return $this; }
php
{ "resource": "" }
q254510
Validation.getErrorMessage
test
protected function getErrorMessage(string $rule, string $field, string $label = null, string $param = null): string { // Check if custom message has been defined by user if (isset($this->customErrors[$field][$rule])) { $message = $this->customErrors[$field][$rule]; } else { // Try to grab a localized version of the message... // lang() will return the rule name back if not found, // so there will always be a string being returned. $message = lang('Validation.' . $rule); } $message = str_replace('{field}', $label ?? $field, $message); $message = str_replace('{param}', $this->rules[$param]['label'] ?? $param, $message); return $message; }
php
{ "resource": "" }
q254511
Validation.splitRules
test
protected function splitRules(string $rules): array { $non_escape_bracket = '((?<!\\\\)(?:\\\\\\\\)*[\[\]])'; $pipe_not_in_bracket = sprintf( '/\|(?=(?:[^\[\]]*%s[^\[\]]*%s)*(?![^\[\]]*%s))/', $non_escape_bracket, $non_escape_bracket, $non_escape_bracket ); $_rules = preg_split( $pipe_not_in_bracket, $rules ); return array_unique($_rules); }
php
{ "resource": "" }
q254512
Validation.reset
test
public function reset(): ValidationInterface { $this->data = []; $this->rules = []; $this->errors = []; $this->customErrors = []; return $this; }
php
{ "resource": "" }
q254513
XMLFormatter.arrayToXML
test
protected function arrayToXML(array $data, &$output) { foreach ($data as $key => $value) { if (is_array($value)) { if (! is_numeric($key)) { $subnode = $output->addChild("$key"); $this->arrayToXML($value, $subnode); } else { $subnode = $output->addChild("item{$key}"); $this->arrayToXML($value, $subnode); } } else { $output->addChild("$key", htmlspecialchars("$value")); } } }
php
{ "resource": "" }
q254514
Logger.cleanFileNames
test
protected function cleanFileNames(string $file): string { $file = str_replace(APPPATH, 'APPPATH/', $file); $file = str_replace(SYSTEMPATH, 'SYSTEMPATH/', $file); $file = str_replace(FCPATH, 'FCPATH/', $file); return $file; }
php
{ "resource": "" }
q254515
URI.setURI
test
public function setURI(string $uri = null) { if (! is_null($uri)) { $parts = parse_url($uri); if ($parts === false) { throw HTTPException::forUnableToParseURI($uri); } $this->applyParts($parts); } return $this; }
php
{ "resource": "" }
q254516
URI.getUserInfo
test
public function getUserInfo() { $userInfo = $this->user; if ($this->showPassword === true && ! empty($this->password)) { $userInfo .= ':' . $this->password; } return $userInfo; }
php
{ "resource": "" }
q254517
URI.getQuery
test
public function getQuery(array $options = []): string { $vars = $this->query; if (array_key_exists('except', $options)) { if (! is_array($options['except'])) { $options['except'] = [$options['except']]; } foreach ($options['except'] as $var) { unset($vars[$var]); } } elseif (array_key_exists('only', $options)) { $temp = []; if (! is_array($options['only'])) { $options['only'] = [$options['only']]; } foreach ($options['only'] as $var) { if (array_key_exists($var, $vars)) { $temp[$var] = $vars[$var]; } } $vars = $temp; } return empty($vars) ? '' : http_build_query($vars); }
php
{ "resource": "" }
q254518
URI.getSegment
test
public function getSegment(int $number): string { // The segment should treat the array as 1-based for the user // but we still have to deal with a zero-based array. $number -= 1; if ($number > count($this->segments)) { throw HTTPException::forURISegmentOutOfRange($number); } return $this->segments[$number] ?? ''; }
php
{ "resource": "" }
q254519
URI.setSegment
test
public function setSegment(int $number, $value) { // The segment should treat the array as 1-based for the user // but we still have to deal with a zero-based array. $number -= 1; if ($number > count($this->segments) + 1) { throw HTTPException::forURISegmentOutOfRange($number); } $this->segments[$number] = $value; $this->refreshPath(); return $this; }
php
{ "resource": "" }
q254520
URI.createURIString
test
public static function createURIString(string $scheme = null, string $authority = null, string $path = null, string $query = null, string $fragment = null): string { $uri = ''; if (! empty($scheme)) { $uri .= $scheme . '://'; } if (! empty($authority)) { $uri .= $authority; } if ($path) { $uri .= substr($uri, -1, 1) !== '/' ? '/' . ltrim($path, '/') : $path; } if ($query) { $uri .= '?' . $query; } if ($fragment) { $uri .= '#' . $fragment; } return $uri; }
php
{ "resource": "" }
q254521
URI.setAuthority
test
public function setAuthority(string $str) { $parts = parse_url($str); if (empty($parts['host']) && ! empty($parts['path'])) { $parts['host'] = $parts['path']; unset($parts['path']); } $this->applyParts($parts); return $this; }
php
{ "resource": "" }
q254522
URI.setScheme
test
public function setScheme(string $str) { $str = strtolower($str); $str = preg_replace('#:(//)?$#', '', $str); $this->scheme = $str; return $this; }
php
{ "resource": "" }
q254523
URI.setPort
test
public function setPort(int $port = null) { if (is_null($port)) { return $this; } if ($port <= 0 || $port > 65535) { throw HTTPException::forInvalidPort($port); } $this->port = $port; return $this; }
php
{ "resource": "" }
q254524
URI.setPath
test
public function setPath(string $path) { $this->path = $this->filterPath($path); $this->segments = explode('/', $this->path); return $this; }
php
{ "resource": "" }
q254525
URI.refreshPath
test
public function refreshPath() { $this->path = $this->filterPath(implode('/', $this->segments)); $this->segments = explode('/', $this->path); return $this; }
php
{ "resource": "" }
q254526
URI.setQuery
test
public function setQuery(string $query) { if (strpos($query, '#') !== false) { throw HTTPException::forMalformedQueryString(); } // Can't have leading ? if (! empty($query) && strpos($query, '?') === 0) { $query = substr($query, 1); } $temp = explode('&', $query); $parts = []; foreach ($temp as $index => $part) { list($key, $value) = $this->splitQueryPart($part); // Only 1 part? if (is_null($value)) { $parts[$key] = null; continue; } // URL Decode the value to protect // from double-encoding a URL. // Especially useful with the Pager. $parts[$this->decode($key)] = $this->decode($value); } $this->query = $parts; return $this; }
php
{ "resource": "" }
q254527
URI.decode
test
protected function decode(string $value): string { if (empty($value)) { return $value; } $decoded = urldecode($value); // This won't catch all cases, specifically // changing ' ' to '+' has the same length // but doesn't really matter for our cases here. return strlen($decoded) < strlen($value) ? $decoded : $value; }
php
{ "resource": "" }
q254528
URI.addQuery
test
public function addQuery(string $key, $value = null) { $this->query[$key] = $value; return $this; }
php
{ "resource": "" }
q254529
URI.keepQuery
test
public function keepQuery(...$params) { $temp = []; foreach ($this->query as $key => $value) { if (! in_array($key, $params)) { continue; } $temp[$key] = $value; } $this->query = $temp; return $this; }
php
{ "resource": "" }
q254530
URI.filterPath
test
protected function filterPath(string $path = null): string { $orig = $path; // Decode/normalize percent-encoded chars so // we can always have matching for Routes, etc. $path = urldecode($path); // Remove dot segments $path = $this->removeDotSegments($path); // Fix up some leading slash edge cases... if (strpos($orig, './') === 0) { $path = '/' . $path; } if (strpos($orig, '../') === 0) { $path = '/' . $path; } // Encode characters $path = preg_replace_callback( '/(?:[^' . static::CHAR_UNRESERVED . ':@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', function (array $matches) { return rawurlencode($matches[0]); }, $path ); return $path; }
php
{ "resource": "" }
q254531
URI.applyParts
test
protected function applyParts(array $parts) { if (! empty($parts['host'])) { $this->host = $parts['host']; } if (! empty($parts['user'])) { $this->user = $parts['user']; } if (! empty($parts['path'])) { $this->path = $this->filterPath($parts['path']); } if (! empty($parts['query'])) { $this->setQuery($parts['query']); } if (! empty($parts['fragment'])) { $this->fragment = $parts['fragment']; } // Scheme if (isset($parts['scheme'])) { $this->setScheme(rtrim($parts['scheme'], ':/')); } else { $this->setScheme('http'); } // Port if (isset($parts['port'])) { if (! is_null($parts['port'])) { // Valid port numbers are enforced by earlier parse_url or setPort() $port = $parts['port']; $this->port = $port; } } if (isset($parts['pass'])) { $this->password = $parts['pass']; } // Populate our segments array if (! empty($parts['path'])) { $this->segments = explode('/', trim($parts['path'], '/')); } }
php
{ "resource": "" }
q254532
URI.resolveRelativeURI
test
public function resolveRelativeURI(string $uri) { /* * NOTE: We don't use removeDotSegments in this * algorithm since it's already done by this line! */ $relative = new URI(); $relative->setURI($uri); if ($relative->getScheme() === $this->getScheme()) { $relative->setScheme(''); } $transformed = clone $relative; // 5.2.2 Transform References in a non-strict method (no scheme) if (! empty($relative->getAuthority())) { $transformed->setAuthority($relative->getAuthority()) ->setPath($relative->getPath()) ->setQuery($relative->getQuery()); } else { if ($relative->getPath() === '') { $transformed->setPath($this->getPath()); if ($relative->getQuery()) { $transformed->setQuery($relative->getQuery()); } else { $transformed->setQuery($this->getQuery()); } } else { if (strpos($relative->getPath(), '/') === 0) { $transformed->setPath($relative->getPath()); } else { $transformed->setPath($this->mergePaths($this, $relative)); } $transformed->setQuery($relative->getQuery()); } $transformed->setAuthority($this->getAuthority()); } $transformed->setScheme($this->getScheme()); $transformed->setFragment($relative->getFragment()); return $transformed; }
php
{ "resource": "" }
q254533
URI.mergePaths
test
protected function mergePaths(URI $base, URI $reference): string { if (! empty($base->getAuthority()) && empty($base->getPath())) { return '/' . ltrim($reference->getPath(), '/ '); } $path = explode('/', $base->getPath()); if (empty($path[0])) { unset($path[0]); } array_pop($path); array_push($path, $reference->getPath()); return implode('/', $path); }
php
{ "resource": "" }
q254534
URI.removeDotSegments
test
public function removeDotSegments(string $path): string { if (empty($path) || $path === '/') { return $path; } $output = []; $input = explode('/', $path); if (empty($input[0])) { unset($input[0]); $input = array_values($input); } // This is not a perfect representation of the // RFC, but matches most cases and is pretty // much what Guzzle uses. Should be good enough // for almost every real use case. foreach ($input as $segment) { if ($segment === '..') { array_pop($output); } else if ($segment !== '.' && $segment !== '') { array_push($output, $segment); } } $output = implode('/', $output); $output = ltrim($output, '/ '); if ($output !== '/') { // Add leading slash if necessary if (strpos($path, '/') === 0) { $output = '/' . $output; } // Add trailing slash if necessary if (substr($path, -1, 1) === '/') { $output .= '/'; } } return $output; }
php
{ "resource": "" }
q254535
Header.appendValue
test
public function appendValue($value = null) { if (! is_array($this->value)) { $this->value = [$this->value]; } $this->value[] = $value; return $this; }
php
{ "resource": "" }
q254536
Header.prependValue
test
public function prependValue($value = null) { if (! is_array($this->value)) { $this->value = [$this->value]; } array_unshift($this->value, $value); return $this; }
php
{ "resource": "" }
q254537
PagerRenderer.getPrevious
test
public function getPrevious() { if (! $this->hasPrevious()) { return null; } $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery('page', $this->first - 1); } else { $uri->setSegment($this->segment, $this->first - 1); } return (string) $uri; }
php
{ "resource": "" }
q254538
PagerRenderer.getNext
test
public function getNext() { if (! $this->hasNext()) { return null; } $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery('page', $this->last + 1); } else { $uri->setSegment($this->segment, $this->last + 1); } return (string) $uri; }
php
{ "resource": "" }
q254539
PagerRenderer.getFirst
test
public function getFirst(): string { $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery('page', 1); } else { $uri->setSegment($this->segment, 1); } return (string) $uri; }
php
{ "resource": "" }
q254540
PagerRenderer.getLast
test
public function getLast(): string { $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery('page', $this->pageCount); } else { $uri->setSegment($this->segment, $this->pageCount); } return (string) $uri; }
php
{ "resource": "" }
q254541
PagerRenderer.getCurrent
test
public function getCurrent(): string { $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery('page', $this->current); } else { $uri->setSegment($this->segment, $this->current); } return (string) $uri; }
php
{ "resource": "" }
q254542
Timer.start
test
public function start(string $name, float $time = null) { $this->timers[strtolower($name)] = [ 'start' => ! empty($time) ? $time : microtime(true), 'end' => null, ]; return $this; }
php
{ "resource": "" }
q254543
Timer.stop
test
public function stop(string $name) { $name = strtolower($name); if (empty($this->timers[$name])) { throw new \RuntimeException('Cannot stop timer: invalid name given.'); } $this->timers[$name]['end'] = microtime(true); return $this; }
php
{ "resource": "" }
q254544
Timer.getElapsedTime
test
public function getElapsedTime(string $name, int $decimals = 4) { $name = strtolower($name); if (empty($this->timers[$name])) { return null; } $timer = $this->timers[$name]; if (empty($timer['end'])) { $timer['end'] = microtime(true); } return (float) number_format($timer['end'] - $timer['start'], $decimals); }
php
{ "resource": "" }
q254545
Timer.getTimers
test
public function getTimers(int $decimals = 4): array { $timers = $this->timers; foreach ($timers as &$timer) { if (empty($timer['end'])) { $timer['end'] = microtime(true); } $timer['duration'] = (float) number_format($timer['end'] - $timer['start'], $decimals); } return $timers; }
php
{ "resource": "" }
q254546
BaseConnection.addTableAlias
test
public function addTableAlias(string $table) { if (! in_array($table, $this->aliasedTables)) { $this->aliasedTables[] = $table; } return $this; }
php
{ "resource": "" }
q254547
BaseConnection.query
test
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = 'CodeIgniter\\Database\\Query') { if (empty($this->connID)) { $this->initialize(); } $resultClass = str_replace('Connection', 'Result', get_class($this)); /** * @var Query $query */ $query = new $queryClass($this); $query->setQuery($sql, $binds, $setEscapeFlags); if (! empty($this->swapPre) && ! empty($this->DBPrefix)) { $query->swapPrefix($this->DBPrefix, $this->swapPre); } $startTime = microtime(true); // Always save the last query so we can use // the getLastQuery() method. $this->lastQuery = $query; // Run the query for real if (! $this->pretend && false === ($this->resultID = $this->simpleQuery($query->getQuery()))) { $query->setDuration($startTime, $startTime); // This will trigger a rollback if transactions are being used if ($this->transDepth !== 0) { $this->transStatus = false; } if ($this->DBDebug) { // We call this function in order to roll-back queries // if transactions are enabled. If we don't call this here // the error message will trigger an exit, causing the // transactions to remain in limbo. while ($this->transDepth !== 0) { $transDepth = $this->transDepth; $this->transComplete(); if ($transDepth === $this->transDepth) { log_message('error', 'Database: Failure during an automated transaction commit/rollback!'); break; } } return false; } if (! $this->pretend) { // Let others do something with this query. Events::trigger('DBQuery', $query); } return new $resultClass($this->connID, $this->resultID); } $query->setDuration($startTime); if (! $this->pretend) { // Let others do something with this query Events::trigger('DBQuery', $query); } // If $pretend is true, then we just want to return // the actual query object here. There won't be // any results to return. return $this->pretend ? $query : new $resultClass($this->connID, $this->resultID); }
php
{ "resource": "" }
q254548
BaseConnection.simpleQuery
test
public function simpleQuery(string $sql) { if (empty($this->connID)) { $this->initialize(); } return $this->execute($sql); }
php
{ "resource": "" }
q254549
BaseConnection.table
test
public function table($tableName) { if (empty($tableName)) { throw new DatabaseException('You must set the database table to be used with your query.'); } $className = str_replace('Connection', 'Builder', get_class($this)); return new $className($tableName, $this); }
php
{ "resource": "" }
q254550
BaseConnection.prepare
test
public function prepare(\Closure $func, array $options = []) { if (empty($this->connID)) { $this->initialize(); } $this->pretend(true); $sql = $func($this); $this->pretend(false); if ($sql instanceof QueryInterface) { $sql = $sql->getOriginalQuery(); } $class = str_ireplace('Connection', 'PreparedQuery', get_class($this)); /** * @var BasePreparedQuery $class */ $class = new $class($this); return $class->prepare($sql, $options); }
php
{ "resource": "" }
q254551
BaseConnection.escapeIdentifiers
test
public function escapeIdentifiers($item) { if ($this->escapeChar === '' || empty($item) || in_array($item, $this->reservedIdentifiers)) { return $item; } elseif (is_array($item)) { foreach ($item as $key => $value) { $item[$key] = $this->escapeIdentifiers($value); } return $item; } // Avoid breaking functions and literal values inside queries elseif (ctype_digit($item) || $item[0] === "'" || ( $this->escapeChar !== '"' && $item[0] === '"') || strpos($item, '(') !== false ) { return $item; } static $preg_ec = []; if (empty($preg_ec)) { if (is_array($this->escapeChar)) { $preg_ec = [ preg_quote($this->escapeChar[0], '/'), preg_quote($this->escapeChar[1], '/'), $this->escapeChar[0], $this->escapeChar[1], ]; } else { $preg_ec[0] = $preg_ec[1] = preg_quote($this->escapeChar, '/'); $preg_ec[2] = $preg_ec[3] = $this->escapeChar; } } foreach ($this->reservedIdentifiers as $id) { if (strpos($item, '.' . $id) !== false) { return preg_replace('/' . $preg_ec[0] . '?([^' . $preg_ec[1] . '\.]+)' . $preg_ec[1] . '?\./i', $preg_ec[2] . '$1' . $preg_ec[3] . '.', $item); } } return preg_replace('/' . $preg_ec[0] . '?([^' . $preg_ec[1] . '\.]+)' . $preg_ec[1] . '?(\.)?/i', $preg_ec[2] . '$1' . $preg_ec[3] . '$2', $item); }
php
{ "resource": "" }
q254552
BaseConnection.callFunction
test
public function callFunction(string $functionName, ...$params): bool { $driver = ($this->DBDriver === 'postgre' ? 'pg' : strtolower($this->DBDriver)) . '_'; if (false === strpos($driver, $functionName)) { $functionName = $driver . $functionName; } if (! function_exists($functionName)) { if ($this->DBDebug) { throw new DatabaseException('This feature is not available for the database you are using.'); } return false; } return $functionName(...$params); }
php
{ "resource": "" }
q254553
BaseConnection.listTables
test
public function listTables(bool $constrainByPrefix = false) { // Is there a cached result? if (isset($this->dataCache['table_names']) && $this->dataCache['table_names']) { return $this->dataCache['table_names']; } if (false === ($sql = $this->_listTables($constrainByPrefix))) { if ($this->DBDebug) { throw new DatabaseException('This feature is not available for the database you are using.'); } return false; } $this->dataCache['table_names'] = []; $query = $this->query($sql); foreach ($query->getResultArray() as $row) { // Do we know from which column to get the table name? if (! isset($key)) { if (isset($row['table_name'])) { $key = 'table_name'; } elseif (isset($row['TABLE_NAME'])) { $key = 'TABLE_NAME'; } else { /* We have no other choice but to just get the first element's key. * Due to array_shift() accepting its argument by reference, if * E_STRICT is on, this would trigger a warning. So we'll have to * assign it first. */ $key = array_keys($row); $key = array_shift($key); } } $this->dataCache['table_names'][] = $row[$key]; } return $this->dataCache['table_names']; }
php
{ "resource": "" }
q254554
BaseConnection.tableExists
test
public function tableExists(string $tableName): bool { return in_array($this->protectIdentifiers($tableName, true, false, false), $this->listTables()); }
php
{ "resource": "" }
q254555
BaseConnection.fieldExists
test
public function fieldExists(string $fieldName, string $tableName): bool { return in_array($fieldName, $this->getFieldNames($tableName)); }
php
{ "resource": "" }
q254556
BaseConnection.getFieldData
test
public function getFieldData(string $table) { $fields = $this->_fieldData($this->protectIdentifiers($table, true, false, false)); return $fields ?? false; }
php
{ "resource": "" }
q254557
BaseConnection.getIndexData
test
public function getIndexData(string $table) { $fields = $this->_indexData($this->protectIdentifiers($table, true, false, false)); return $fields ?? false; }
php
{ "resource": "" }
q254558
BaseConnection.getForeignKeyData
test
public function getForeignKeyData(string $table) { $fields = $this->_foreignKeyData($this->protectIdentifiers($table, true, false, false)); return $fields ?? false; }
php
{ "resource": "" }
q254559
BaseConfig.getEnvValue
test
protected function getEnvValue(string $property, string $prefix, string $shortPrefix) { $shortPrefix = ltrim($shortPrefix, '\\'); switch (true) { case array_key_exists("{$shortPrefix}.{$property}", $_ENV): return $_ENV["{$shortPrefix}.{$property}"]; break; case array_key_exists("{$shortPrefix}.{$property}", $_SERVER): return $_SERVER["{$shortPrefix}.{$property}"]; break; case array_key_exists("{$prefix}.{$property}", $_ENV): return $_ENV["{$prefix}.{$property}"]; break; case array_key_exists("{$prefix}.{$property}", $_SERVER): return $_SERVER["{$prefix}.{$property}"]; break; default: $value = getenv($property); return $value === false ? null : $value; } }
php
{ "resource": "" }
q254560
BaseConfig.registerProperties
test
protected function registerProperties() { if (! static::$moduleConfig->shouldDiscover('registrars')) { return; } if (! static::$didDiscovery) { $locator = \Config\Services::locator(); $registrarsFiles = $locator->search('Config/Registrar.php'); foreach ($registrarsFiles as $file) { $className = $locator->getClassname($file); static::$registrars[] = new $className(); } static::$didDiscovery = true; } $shortName = (new \ReflectionClass($this))->getShortName(); // Check the registrar class for a method named after this class' shortName foreach (static::$registrars as $callable) { // ignore non-applicable registrars if (! method_exists($callable, $shortName)) { continue; } $properties = $callable::$shortName(); if (! is_array($properties)) { throw new \RuntimeException('Registrars must return an array of properties and their values.'); } foreach ($properties as $property => $value) { if (isset($this->$property) && is_array($this->$property) && is_array($value)) { $this->$property = array_merge($this->$property, $value); } else { $this->$property = $value; } } } }
php
{ "resource": "" }
q254561
FileHandler.getItem
test
protected function getItem(string $key) { if (! is_file($this->path . $key)) { return false; } $data = unserialize(file_get_contents($this->path . $key)); if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl']) { unlink($this->path . $key); return false; } return $data; }
php
{ "resource": "" }
q254562
FileHandler.writeFile
test
protected function writeFile($path, $data, $mode = 'wb') { if (($fp = @fopen($path, $mode)) === false) { return false; } flock($fp, LOCK_EX); for ($result = $written = 0, $length = strlen($data); $written < $length; $written += $result) { if (($result = fwrite($fp, substr($data, $written))) === false) { break; } } flock($fp, LOCK_UN); fclose($fp); return is_int($result); }
php
{ "resource": "" }
q254563
FileHandler.getDirFileInfo
test
protected function getDirFileInfo(string $source_dir, bool $top_level_only = true, bool $_recursion = false) { static $_filedata = []; $relative_path = $source_dir; if ($fp = @opendir($source_dir)) { // reset the array and make sure $source_dir has a trailing slash on the initial call if ($_recursion === false) { $_filedata = []; $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } // Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast while (false !== ($file = readdir($fp))) { if (is_dir($source_dir . $file) && $file[0] !== '.' && $top_level_only === false) { $this->getDirFileInfo($source_dir . $file . DIRECTORY_SEPARATOR, $top_level_only, true); } elseif ($file[0] !== '.') { $_filedata[$file] = $this->getFileInfo($source_dir . $file); $_filedata[$file]['relative_path'] = $relative_path; } } closedir($fp); return $_filedata; } return false; }
php
{ "resource": "" }
q254564
FileHandler.getFileInfo
test
protected function getFileInfo(string $file, $returned_values = ['name', 'server_path', 'size', 'date']) { if (! is_file($file)) { return false; } if (is_string($returned_values)) { $returned_values = explode(',', $returned_values); } foreach ($returned_values as $key) { switch ($key) { case 'name': $fileInfo['name'] = basename($file); break; case 'server_path': $fileInfo['server_path'] = $file; break; case 'size': $fileInfo['size'] = filesize($file); break; case 'date': $fileInfo['date'] = filemtime($file); break; case 'readable': $fileInfo['readable'] = is_readable($file); break; case 'writable': $fileInfo['writable'] = is_writable($file); break; case 'executable': $fileInfo['executable'] = is_executable($file); break; case 'fileperms': $fileInfo['fileperms'] = fileperms($file); break; } } return $fileInfo; }
php
{ "resource": "" }
q254565
CodeIgniter.initialize
test
public function initialize() { // Set default timezone on the server date_default_timezone_set($this->config->appTimezone ?? 'UTC'); // Setup Exception Handling Services::exceptions() ->initialize(); $this->detectEnvironment(); $this->bootstrapEnvironment(); if (CI_DEBUG) { require_once SYSTEMPATH . 'ThirdParty/Kint/kint.php'; } }
php
{ "resource": "" }
q254566
CodeIgniter.run
test
public function run(RouteCollectionInterface $routes = null, bool $returnResponse = false) { $this->startBenchmark(); $this->getRequestObject(); $this->getResponseObject(); $this->forceSecureAccess(); $this->spoofRequestMethod(); Events::trigger('pre_system'); // Check for a cached page. Execution will stop // if the page has been cached. $cacheConfig = new Cache(); $response = $this->displayCache($cacheConfig); if ($response instanceof ResponseInterface) { if ($returnResponse) { return $response; } $this->response->pretend($this->useSafeOutput)->send(); $this->callExit(EXIT_SUCCESS); } try { return $this->handleRequest($routes, $cacheConfig, $returnResponse); } catch (FilterException $e) { $logger = Services::logger(); $logger->info('REDIRECTED ROUTE at ' . $e->getMessage()); // If the route is a 'redirect' route, it throws // the exception with the $to as the message $this->response->redirect($e->getMessage(), 'auto', $e->getCode()); $this->callExit(EXIT_SUCCESS); } catch (PageNotFoundException $e) { $this->display404errors($e); } }
php
{ "resource": "" }
q254567
CodeIgniter.handleRequest
test
protected function handleRequest(RouteCollectionInterface $routes = null, $cacheConfig, bool $returnResponse = false) { $routeFilter = $this->tryToRouteIt($routes); // Run "before" filters $filters = Services::filters(); // If any filters were specified within the routes file, // we need to ensure it's active for the current request if (! is_null($routeFilter)) { $filters->enableFilter($routeFilter, 'before'); $filters->enableFilter($routeFilter, 'after'); } $uri = $this->request instanceof CLIRequest ? $this->request->getPath() : $this->request->uri->getPath(); // Never run filters when running through Spark cli if (! defined('SPARKED')) { $possibleRedirect = $filters->run($uri, 'before'); if ($possibleRedirect instanceof RedirectResponse) { return $possibleRedirect->send(); } // If a Response instance is returned, the Response will be sent back to the client and script execution will stop if ($possibleRedirect instanceof ResponseInterface) { return $possibleRedirect->send(); } } $returned = $this->startController(); // Closure controller has run in startController(). if (! is_callable($this->controller)) { $controller = $this->createController(); // Is there a "post_controller_constructor" event? Events::trigger('post_controller_constructor'); $returned = $this->runController($controller); } else { $this->benchmark->stop('controller_constructor'); $this->benchmark->stop('controller'); } // If $returned is a string, then the controller output something, // probably a view, instead of echoing it directly. Send it along // so it can be used with the output. $this->gatherOutput($cacheConfig, $returned); // Never run filters when running through Spark cli if (! defined('SPARKED')) { $filters->setResponse($this->response); // Run "after" filters $response = $filters->run($uri, 'after'); } else { $response = $this->response; } if ($response instanceof Response) { $this->response = $response; } // Save our current URI as the previous URI in the session // for safer, more accurate use with `previous_url()` helper function. $this->storePreviousURL($this->request->uri ?? $uri); unset($uri); if (! $returnResponse) { $this->sendResponse(); } //-------------------------------------------------------------------- // Is there a post-system event? //-------------------------------------------------------------------- Events::trigger('post_system'); return $this->response; }
php
{ "resource": "" }
q254568
CodeIgniter.startBenchmark
test
protected function startBenchmark() { $this->startTime = microtime(true); $this->benchmark = Services::timer(); $this->benchmark->start('total_execution', $this->startTime); $this->benchmark->start('bootstrap'); }
php
{ "resource": "" }
q254569
CodeIgniter.getResponseObject
test
protected function getResponseObject() { $this->response = Services::response($this->config); if (! is_cli() || ENVIRONMENT === 'testing') { $this->response->setProtocolVersion($this->request->getProtocolVersion()); } // Assume success until proven otherwise. $this->response->setStatusCode(200); }
php
{ "resource": "" }
q254570
CodeIgniter.forceSecureAccess
test
protected function forceSecureAccess($duration = 31536000) { if ($this->config->forceGlobalSecureRequests !== true) { return; } force_https($duration, $this->request, $this->response); }
php
{ "resource": "" }
q254571
CodeIgniter.displayCache
test
public function displayCache($config) { if ($cachedResponse = cache()->get($this->generateCacheName($config))) { $cachedResponse = unserialize($cachedResponse); if (! is_array($cachedResponse) || ! isset($cachedResponse['output']) || ! isset($cachedResponse['headers'])) { throw new Exception('Error unserializing page cache'); } $headers = $cachedResponse['headers']; $output = $cachedResponse['output']; // Clear all default headers foreach ($this->response->getHeaders() as $key => $val) { $this->response->removeHeader($key); } // Set cached headers foreach ($headers as $name => $value) { $this->response->setHeader($name, $value); } $output = $this->displayPerformanceMetrics($output); $this->response->setBody($output); return $this->response; } return false; }
php
{ "resource": "" }
q254572
CodeIgniter.cachePage
test
public function cachePage(Cache $config) { $headers = []; foreach ($this->response->getHeaders() as $header) { $headers[$header->getName()] = $header->getValueLine(); } return cache()->save( $this->generateCacheName($config), serialize(['headers' => $headers, 'output' => $this->output]), static::$cacheTTL ); }
php
{ "resource": "" }
q254573
CodeIgniter.generateCacheName
test
protected function generateCacheName($config): string { if (is_cli() && ! (ENVIRONMENT === 'testing')) { return md5($this->request->getPath()); } $uri = $this->request->uri; if ($config->cacheQueryString) { $name = URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery() ); } else { $name = URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath() ); } return md5($name); }
php
{ "resource": "" }
q254574
CodeIgniter.displayPerformanceMetrics
test
public function displayPerformanceMetrics(string $output): string { $this->totalTime = $this->benchmark->getElapsedTime('total_execution'); $output = str_replace('{elapsed_time}', $this->totalTime, $output); return $output; }
php
{ "resource": "" }
q254575
CodeIgniter.tryToRouteIt
test
protected function tryToRouteIt(RouteCollectionInterface $routes = null) { if (empty($routes) || ! $routes instanceof RouteCollectionInterface) { require APPPATH . 'Config/Routes.php'; } // $routes is defined in Config/Routes.php $this->router = Services::router($routes); $path = $this->determinePath(); $this->benchmark->stop('bootstrap'); $this->benchmark->start('routing'); ob_start(); $this->controller = $this->router->handle($path); $this->method = $this->router->methodName(); // If a {locale} segment was matched in the final route, // then we need to set the correct locale on our Request. if ($this->router->hasLocale()) { $this->request->setLocale($this->router->getLocale()); } $this->benchmark->stop('routing'); return $this->router->getFilter(); }
php
{ "resource": "" }
q254576
CodeIgniter.startController
test
protected function startController() { $this->benchmark->start('controller'); $this->benchmark->start('controller_constructor'); // Is it routed to a Closure? if (is_object($this->controller) && (get_class($this->controller) === 'Closure')) { $controller = $this->controller; return $controller(...$this->router->params()); } // No controller specified - we don't know what to do now. if (empty($this->controller)) { throw PageNotFoundException::forEmptyController(); } // Try to autoload the class if (! class_exists($this->controller, true) || $this->method[0] === '_') { throw PageNotFoundException::forControllerNotFound($this->controller, $this->method); } else if (! method_exists($this->controller, '_remap') && ! is_callable([$this->controller, $this->method], false) ) { throw PageNotFoundException::forMethodNotFound($this->method); } }
php
{ "resource": "" }
q254577
CodeIgniter.createController
test
protected function createController() { $class = new $this->controller(); $class->initController($this->request, $this->response, Services::logger()); $this->benchmark->stop('controller_constructor'); return $class; }
php
{ "resource": "" }
q254578
CodeIgniter.runController
test
protected function runController($class) { if (method_exists($class, '_remap')) { $output = $class->_remap($this->method, ...$this->router->params()); } else { $output = $class->{$this->method}(...$this->router->params()); } $this->benchmark->stop('controller'); return $output; }
php
{ "resource": "" }
q254579
CodeIgniter.gatherOutput
test
protected function gatherOutput($cacheConfig = null, $returned = null) { $this->output = ob_get_contents(); // If buffering is not null. // Clean (erase) the output buffer and turn off output buffering if (ob_get_length()) { ob_end_clean(); } if ($returned instanceof DownloadResponse) { $this->response = $returned; return; } // If the controller returned a response object, // we need to grab the body from it so it can // be added to anything else that might have been // echoed already. // We also need to save the instance locally // so that any status code changes, etc, take place. if ($returned instanceof Response) { $this->response = $returned; $returned = $returned->getBody(); } if (is_string($returned)) { $this->output .= $returned; } // Cache it without the performance metrics replaced // so that we can have live speed updates along the way. if (static::$cacheTTL > 0) { $this->cachePage($cacheConfig); } $this->output = $this->displayPerformanceMetrics($this->output); $this->response->setBody($this->output); }
php
{ "resource": "" }
q254580
CodeIgniter.storePreviousURL
test
public function storePreviousURL($uri) { // This is mainly needed during testing... if (is_string($uri)) { $uri = new URI($uri); } if (isset($_SESSION)) { $_SESSION['_ci_previous_url'] = (string) $uri; } }
php
{ "resource": "" }
q254581
CodeIgniter.spoofRequestMethod
test
public function spoofRequestMethod() { if (is_cli()) { return; } // Only works with POSTED forms if ($this->request->getMethod() !== 'post') { return; } $method = $this->request->getPost('_method'); if (empty($method)) { return; } $this->request = $this->request->setMethod($method); }
php
{ "resource": "" }
q254582
CacheFactory.getHandler
test
public static function getHandler($config, string $handler = null, string $backup = null) { if (! isset($config->validHandlers) || ! is_array($config->validHandlers)) { throw CacheException::forInvalidHandlers(); } if (! isset($config->handler) || ! isset($config->backupHandler)) { throw CacheException::forNoBackup(); } $handler = ! empty($handler) ? $handler : $config->handler; $backup = ! empty($backup) ? $backup : $config->backupHandler; if (! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers)) { throw CacheException::forHandlerNotFound(); } // Get an instance of our handler. $adapter = new $config->validHandlers[$handler]($config); if (! $adapter->isSupported()) { $adapter = new $config->validHandlers[$backup]($config); if (! $adapter->isSupported()) { // Log stuff here, don't throw exception. No need to raise a fuss. // Fall back to the dummy adapter. $adapter = new $config->validHandlers['dummy'](); } } $adapter->initialize(); return $adapter; }
php
{ "resource": "" }
q254583
BaseBuilder.createAliasFromTable
test
protected function createAliasFromTable(string $item): string { if (strpos($item, '.') !== false) { $item = explode('.', $item); return end($item); } return $item; }
php
{ "resource": "" }
q254584
BaseBuilder.whereNotIn
test
public function whereNotIn(string $key = null, array $values = null, bool $escape = null) { return $this->_whereIn($key, $values, true, 'AND ', $escape); }
php
{ "resource": "" }
q254585
BaseBuilder._whereIn
test
protected function _whereIn(string $key = null, array $values = null, bool $not = false, string $type = 'AND ', bool $escape = null) { if ($key === null || $values === null) { return $this; } is_bool($escape) || $escape = $this->db->protectIdentifiers; $ok = $key; if ($escape === true) { $key = $this->db->protectIdentifiers($key); } $not = ($not) ? ' NOT' : ''; $where_in = array_values($values); $ok = $this->setBind($ok, $where_in, $escape); $prefix = empty($this->QBWhere) ? $this->groupGetType('') : $this->groupGetType($type); $where_in = [ 'condition' => $prefix . $key . $not . " IN :{$ok}:", 'escape' => false, ]; $this->QBWhere[] = $where_in; return $this; }
php
{ "resource": "" }
q254586
BaseBuilder._like_statement
test
protected function _like_statement(string $prefix = null, string $column, string $not = null, string $bind, bool $insensitiveSearch = false): string { $like_statement = "{$prefix} {$column} {$not} LIKE :{$bind}:"; if ($insensitiveSearch === true) { $like_statement = "{$prefix} LOWER({$column}) {$not} LIKE :{$bind}:"; } return $like_statement; }
php
{ "resource": "" }
q254587
BaseBuilder.groupStart
test
public function groupStart(string $not = '', string $type = 'AND ') { $type = $this->groupGetType($type); $this->QBWhereGroupStarted = true; $prefix = empty($this->QBWhere) ? '' : $type; $where = [ 'condition' => $prefix . $not . str_repeat(' ', ++ $this->QBWhereGroupCount) . ' (', 'escape' => false, ]; $this->QBWhere[] = $where; return $this; }
php
{ "resource": "" }
q254588
BaseBuilder.groupEnd
test
public function groupEnd() { $this->QBWhereGroupStarted = false; $where = [ 'condition' => str_repeat(' ', $this->QBWhereGroupCount -- ) . ')', 'escape' => false, ]; $this->QBWhere[] = $where; return $this; }
php
{ "resource": "" }
q254589
BaseBuilder.offset
test
public function offset(int $offset) { if (! empty($offset)) { $this->QBOffset = (int) $offset; } return $this; }
php
{ "resource": "" }
q254590
BaseBuilder.set
test
public function set($key, string $value = '', bool $escape = null) { $key = $this->objectToArray($key); if (! is_array($key)) { $key = [$key => $value]; } $escape = is_bool($escape) ? $escape : $this->db->protectIdentifiers; foreach ($key as $k => $v) { if ($escape) { $bind = $this->setBind($k, $v, $escape); $this->QBSet[$this->db->protectIdentifiers($k, false, $escape)] = ":$bind:"; } else { $this->QBSet[$this->db->protectIdentifiers($k, false, $escape)] = $v; } } return $this; }
php
{ "resource": "" }
q254591
BaseBuilder.getCompiledSelect
test
public function getCompiledSelect(bool $reset = true): string { $select = $this->compileSelect(); if ($reset === true) { $this->resetSelect(); } return $this->compileFinalQuery($select); }
php
{ "resource": "" }
q254592
BaseBuilder.compileFinalQuery
test
protected function compileFinalQuery(string $sql): string { $query = new Query($this->db); $query->setQuery($sql, $this->binds, false); if (! empty($this->db->swapPre) && ! empty($this->db->DBPrefix)) { $query->swapPrefix($this->db->DBPrefix, $this->db->swapPre); } return $query->getQuery(); }
php
{ "resource": "" }
q254593
BaseBuilder.countAll
test
public function countAll(bool $reset = true, bool $test = false) { $table = $this->QBFrom[0]; $sql = $this->countString . $this->db->escapeIdentifiers('numrows') . ' FROM ' . $this->db->protectIdentifiers($table, true, null, false); if ($test) { return $sql; } $query = $this->db->query($sql, null, false); if (empty($query->getResult())) { return 0; } $query = $query->getRow(); if ($reset === true) { $this->resetSelect(); } return (int) $query->numrows; }
php
{ "resource": "" }
q254594
BaseBuilder.countAllResults
test
public function countAllResults(bool $reset = true, bool $test = false) { // ORDER BY usage is often problematic here (most notably // on Microsoft SQL Server) and ultimately unnecessary // for selecting COUNT(*) ... $orderBy = []; if (! empty($this->QBOrderBy)) { $orderBy = $this->QBOrderBy; $this->QBOrderBy = null; } $sql = ($this->QBDistinct === true) ? $this->countString . $this->db->protectIdentifiers('numrows') . "\nFROM (\n" . $this->compileSelect() . "\n) CI_count_all_results" : $this->compileSelect($this->countString . $this->db->protectIdentifiers('numrows')); if ($test) { return $sql; } $result = $this->db->query($sql, $this->binds, false); if ($reset === true) { $this->resetSelect(); } // If we've previously reset the QBOrderBy values, get them back elseif (! isset($this->QBOrderBy)) { $this->QBOrderBy = $orderBy ?? []; } $row = (! $result instanceof ResultInterface) ? null : $result->getRow(); if (empty($row)) { return 0; } return (int) $row->numrows; }
php
{ "resource": "" }
q254595
BaseBuilder._insertBatch
test
protected function _insertBatch(string $table, array $keys, array $values): string { return 'INSERT INTO ' . $table . ' (' . implode(', ', $keys) . ') VALUES ' . implode(', ', $values); }
php
{ "resource": "" }
q254596
BaseBuilder.getCompiledInsert
test
public function getCompiledInsert(bool $reset = true): string { if ($this->validateInsert() === false) { return false; } $sql = $this->_insert( $this->db->protectIdentifiers( $this->QBFrom[0], true, null, false ), array_keys($this->QBSet), array_values($this->QBSet) ); if ($reset === true) { $this->resetWrite(); } return $this->compileFinalQuery($sql); }
php
{ "resource": "" }
q254597
BaseBuilder.getCompiledUpdate
test
public function getCompiledUpdate(bool $reset = true): string { if ($this->validateUpdate() === false) { return false; } $sql = $this->_update($this->QBFrom[0], $this->QBSet); if ($reset === true) { $this->resetWrite(); } return $this->compileFinalQuery($sql); }
php
{ "resource": "" }
q254598
BaseBuilder.getCompiledDelete
test
public function getCompiledDelete(bool $reset = true): string { $table = $this->QBFrom[0]; $sql = $this->delete($table, '', $reset, true); return $this->compileFinalQuery($sql); }
php
{ "resource": "" }
q254599
BaseBuilder.decrement
test
public function decrement(string $column, int $value = 1) { $column = $this->db->protectIdentifiers($column); $sql = $this->_update($this->QBFrom[0], [$column => "{$column}-{$value}"]); return $this->db->query($sql, $this->binds, false); }
php
{ "resource": "" }