_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q254400
ImageMagickHandler._crop
test
public function _crop() { $source = ! empty($this->resource) ? $this->resource : $this->image->getPathname(); $destination = $this->getResourcePath(); $action = ' -crop ' . $this->width . 'x' . $this->height . '+' . $this->xAxis . '+' . $this->yAxis . ' "' . $source . '" "' . $destination . '"'; $this->process($action); return $this; }
php
{ "resource": "" }
q254401
ImageMagickHandler.getVersion
test
public function getVersion(): string { $result = $this->process('-version'); // The first line has the version in it... preg_match('/(ImageMagick\s[\S]+)/', $result[0], $matches); return str_replace('ImageMagick ', '', $matches[0]); }
php
{ "resource": "" }
q254402
ImageMagickHandler.getResourcePath
test
protected function getResourcePath() { if (! is_null($this->resource)) { return $this->resource; } $this->resource = WRITEPATH . 'cache/' . time() . '_' . bin2hex(random_bytes(10)) . '.png'; return $this->resource; }
php
{ "resource": "" }
q254403
Forge.addForeignKey
test
public function addForeignKey(string $fieldName = '', string $tableName = '', string $tableField = '', string $onUpdate = '', string $onDelete = '') { if (! isset($this->fields[$fieldName])) { throw new DatabaseException(lang('Database.fieldNotExists', [$fieldName])); } $this->foreignKeys[$fieldName] = [ 'table' => $tableName, 'field' => $tableField, 'onDelete' => strtoupper($onDelete), 'onUpdate' => strtoupper($onUpdate), ]; return $this; }
php
{ "resource": "" }
q254404
Forge.dropForeignKey
test
public function dropForeignKey(string $table, string $foreign_name) { $sql = sprintf($this->dropConstraintStr, $this->db->escapeIdentifiers($this->db->DBPrefix . $table), $this->db->escapeIdentifiers($this->db->DBPrefix . $foreign_name)); if ($sql === false) { if ($this->db->DBDebug) { throw new DatabaseException('This feature is not available for the database you are using.'); } return false; } return $this->db->query($sql); }
php
{ "resource": "" }
q254405
Forge._attributeUnsigned
test
protected function _attributeUnsigned(array &$attributes, array &$field) { if (empty($attributes['UNSIGNED']) || $attributes['UNSIGNED'] !== true) { return; } // Reset the attribute in order to avoid issues if we do type conversion $attributes['UNSIGNED'] = false; if (is_array($this->unsigned)) { foreach (array_keys($this->unsigned) as $key) { if (is_int($key) && strcasecmp($attributes['TYPE'], $this->unsigned[$key]) === 0) { $field['unsigned'] = ' UNSIGNED'; return; } elseif (is_string($key) && strcasecmp($attributes['TYPE'], $key) === 0) { $field['type'] = $key; return; } } return; } $field['unsigned'] = ($this->unsigned === true) ? ' UNSIGNED' : ''; }
php
{ "resource": "" }
q254406
Forge._attributeDefault
test
protected function _attributeDefault(array &$attributes, array &$field) { if ($this->default === false) { return; } if (array_key_exists('DEFAULT', $attributes)) { if ($attributes['DEFAULT'] === null) { $field['default'] = empty($this->null) ? '' : $this->default . $this->null; // Override the NULL attribute if that's our default $attributes['NULL'] = true; $field['null'] = empty($this->null) ? '' : ' ' . $this->null; } else { $field['default'] = $this->default . $this->db->escape($attributes['DEFAULT']); } } }
php
{ "resource": "" }
q254407
Forge._processPrimaryKeys
test
protected function _processPrimaryKeys(string $table): string { $sql = ''; for ($i = 0, $c = count($this->primaryKeys); $i < $c; $i++) { if (! isset($this->fields[$this->primaryKeys[$i]])) { unset($this->primaryKeys[$i]); } } if (count($this->primaryKeys) > 0) { $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers('pk_' . $table) . ' PRIMARY KEY(' . implode(', ', $this->db->escapeIdentifiers($this->primaryKeys)) . ')'; } return $sql; }
php
{ "resource": "" }
q254408
Forge._processForeignKeys
test
protected function _processForeignKeys(string $table): string { $sql = ''; $allowActions = [ 'CASCADE', 'SET NULL', 'NO ACTION', 'RESTRICT', 'SET DEFAULT', ]; if (count($this->foreignKeys) > 0) { foreach ($this->foreignKeys as $field => $fkey) { $name_index = $table . '_' . $field . '_foreign'; $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($name_index) . ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')'; if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions)) { $sql .= ' ON DELETE ' . $fkey['onDelete']; } if ($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions)) { $sql .= ' ON UPDATE ' . $fkey['onUpdate']; } } } return $sql; }
php
{ "resource": "" }
q254409
Language.setLocale
test
public function setLocale(string $locale = null) { if (! is_null($locale)) { $this->locale = $locale; } return $this; }
php
{ "resource": "" }
q254410
Language.getLine
test
public function getLine(string $line, array $args = []) { // ignore requests with no file specified if (! strpos($line, '.')) { return $line; } // Parse out the file name and the actual alias. // Will load the language file and strings. [ $file, $parsedLine, ] = $this->parseLine($line, $this->locale); $output = $this->language[$this->locale][$file][$parsedLine] ?? null; if ($output === null && strpos($this->locale, '-')) { [$locale] = explode('-', $this->locale, 2); [ $file, $parsedLine, ] = $this->parseLine($line, $locale); $output = $this->language[$locale][$file][$parsedLine] ?? null; } // if still not found, try English if (empty($output)) { $this->parseLine($line, 'en'); $output = $this->language['en'][$file][$parsedLine] ?? null; } $output = $output ?? $line; if (! empty($args)) { $output = $this->formatMessage($output, $args); } return $output; }
php
{ "resource": "" }
q254411
Language.formatMessage
test
protected function formatMessage($message, array $args = []) { if (! $this->intlSupport || ! $args) { return $message; } if (is_array($message)) { foreach ($message as $index => $value) { $message[$index] = $this->formatMessage($value, $args); } return $message; } return \MessageFormatter::formatMessage($this->locale, $message, $args); }
php
{ "resource": "" }
q254412
Language.requireFile
test
protected function requireFile(string $path): array { $files = Services::locator()->search($path); $strings = []; foreach ($files as $file) { // On some OS's we were seeing failures // on this command returning boolean instead // of array during testing, so we've removed // the require_once for now. if (is_file($file)) { $strings[] = require $file; } } if (isset($strings[1])) { $strings = array_replace_recursive(...$strings); } elseif (isset($strings[0])) { $strings = $strings[0]; } return $strings; }
php
{ "resource": "" }
q254413
ContentSecurityPolicy.addBaseURI
test
public function addBaseURI($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'baseURI', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254414
ContentSecurityPolicy.addImageSrc
test
public function addImageSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'imageSrc', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254415
ContentSecurityPolicy.addMediaSrc
test
public function addMediaSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'mediaSrc', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254416
ContentSecurityPolicy.addManifestSrc
test
public function addManifestSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'manifestSrc', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254417
ContentSecurityPolicy.addObjectSrc
test
public function addObjectSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'objectSrc', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254418
ContentSecurityPolicy.addPluginType
test
public function addPluginType($mime, ?bool $explicitReporting = null) { $this->addOption($mime, 'pluginTypes', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254419
ContentSecurityPolicy.addSandbox
test
public function addSandbox($flags, ?bool $explicitReporting = null) { $this->addOption($flags, 'sandbox', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254420
ContentSecurityPolicy.addScriptSrc
test
public function addScriptSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'scriptSrc', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254421
ContentSecurityPolicy.addStyleSrc
test
public function addStyleSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'styleSrc', $explicitReporting ?? $this->reportOnly); return $this; }
php
{ "resource": "" }
q254422
ContentSecurityPolicy.addOption
test
protected function addOption($options, string $target, ?bool $explicitReporting = null) { // Ensure we have an array to work with... if (is_string($this->{$target})) { $this->{$target} = [$this->{$target}]; } if (is_array($options)) { foreach ($options as $opt) { $this->{$target}[$opt] = $explicitReporting ?? $this->reportOnly; } } else { $this->{$target}[$options] = $explicitReporting ?? $this->reportOnly; } }
php
{ "resource": "" }
q254423
ContentSecurityPolicy.generateNonces
test
protected function generateNonces(ResponseInterface &$response) { $body = $response->getBody(); if (empty($body)) { return; } if (! is_array($this->styleSrc)) { $this->styleSrc = [$this->styleSrc]; } if (! is_array($this->scriptSrc)) { $this->scriptSrc = [$this->scriptSrc]; } // Replace style placeholders with nonces $body = preg_replace_callback( '/{csp-style-nonce}/', function ($matches) { $nonce = bin2hex(random_bytes(12)); $this->styleSrc[] = 'nonce-' . $nonce; return "nonce=\"{$nonce}\""; }, $body ); // Replace script placeholders with nonces $body = preg_replace_callback( '/{csp-script-nonce}/', function ($matches) { $nonce = bin2hex(random_bytes(12)); $this->scriptSrc[] = 'nonce-' . $nonce; return "nonce=\"{$nonce}\""; }, $body ); $response->setBody($body); }
php
{ "resource": "" }
q254424
ContentSecurityPolicy.buildHeaders
test
protected function buildHeaders(ResponseInterface &$response) { // Ensure both headers are available and arrays... $response->setHeader('Content-Security-Policy', []); $response->setHeader('Content-Security-Policy-Report-Only', []); $directives = [ 'base-uri' => 'baseURI', 'child-src' => 'childSrc', 'connect-src' => 'connectSrc', 'default-src' => 'defaultSrc', 'font-src' => 'fontSrc', 'form-action' => 'formAction', 'frame-ancestors' => 'frameAncestors', 'img-src' => 'imageSrc', 'media-src' => 'mediaSrc', 'object-src' => 'objectSrc', 'plugin-types' => 'pluginTypes', 'script-src' => 'scriptSrc', 'style-src' => 'styleSrc', 'manifest-src' => 'manifestSrc', 'sandbox' => 'sandbox', 'report-uri' => 'reportURI', ]; // inject default base & default URIs if needed if (empty($this->baseURI)) { $this->baseURI = 'self'; } if (empty($this->defaultSrc)) { $this->defaultSrc = 'self'; } foreach ($directives as $name => $property) { // base_uri if (! empty($this->{$property})) { $this->addToHeader($name, $this->{$property}); } } // Compile our own header strings here since if we just // append it to the response, it will be joined with // commas, not semi-colons as we need. if (! empty($this->tempHeaders)) { $header = ''; foreach ($this->tempHeaders as $name => $value) { $header .= " {$name} {$value};"; } // add token only if needed if ($this->upgradeInsecureRequests) { $header .= ' upgrade-insecure-requests;'; } $response->appendHeader('Content-Security-Policy', $header); } if (! empty($this->reportOnlyHeaders)) { $header = ''; foreach ($this->reportOnlyHeaders as $name => $value) { $header .= " {$name} {$value};"; } $response->appendHeader('Content-Security-Policy-Report-Only', $header); } $this->tempHeaders = []; $this->reportOnlyHeaders = []; }
php
{ "resource": "" }
q254425
BaseCollector.getTitle
test
public function getTitle(bool $safe = false): string { if ($safe) { return str_replace(' ', '-', strtolower($this->title)); } return $this->title; }
php
{ "resource": "" }
q254426
Logs.collectLogs
test
protected function collectLogs() { if (! is_null($this->data)) { return $this->data; } return $this->data = Services::logger(true)->logCache ?? []; }
php
{ "resource": "" }
q254427
Cell.prepareParams
test
public function prepareParams($params) { if (empty($params) || ( ! is_string($params) && ! is_array($params))) { return []; } if (is_string($params)) { $new_params = []; $separator = ' '; if (strpos($params, ',') !== false) { $separator = ','; } $params = explode($separator, $params); unset($separator); foreach ($params as $p) { if (! empty($p)) { list($key, $val) = explode('=', $p); $new_params[trim($key)] = trim($val, ', '); } } $params = $new_params; unset($new_params); } if (is_array($params) && empty($params)) { return []; } return $params; }
php
{ "resource": "" }
q254428
Cell.determineClass
test
protected function determineClass(string $library): array { // We don't want to actually call static methods // by default, so convert any double colons. $library = str_replace('::', ':', $library); list($class, $method) = explode(':', $library); if (empty($class)) { throw ViewException::forNoCellClass(); } if (! class_exists($class, true)) { throw ViewException::forInvalidCellClass($class); } if (empty($method)) { $method = 'index'; } return [ $class, $method, ]; }
php
{ "resource": "" }
q254429
BaseResult.getResult
test
public function getResult(string $type = 'object'): array { if ($type === 'array') { return $this->getResultArray(); } elseif ($type === 'object') { return $this->getResultObject(); } return $this->getCustomResultObject($type); }
php
{ "resource": "" }
q254430
BaseResult.getCustomResultObject
test
public function getCustomResultObject(string $className) { if (isset($this->customResultObject[$className])) { return $this->customResultObject[$className]; } if (is_bool($this->resultID) || ! $this->resultID || $this->numRows === 0) { return []; } // Don't fetch the result set again if we already have it $_data = null; if (($c = count($this->resultArray)) > 0) { $_data = 'result_array'; } elseif (($c = count($this->resultObject)) > 0) { $_data = 'result_object'; } if ($_data !== null) { for ($i = 0; $i < $c; $i ++) { $this->customResultObject[$className][$i] = new $className(); foreach ($this->{$_data}[$i] as $key => $value) { $this->customResultObject[$className][$i]->$key = $value; } } return $this->customResultObject[$className]; } is_null($this->rowData) || $this->dataSeek(0); $this->customResultObject[$className] = []; while ($row = $this->fetchObject($className)) { $this->customResultObject[$className][] = $row; } return $this->customResultObject[$className]; }
php
{ "resource": "" }
q254431
BaseResult.getResultArray
test
public function getResultArray(): array { if (! empty($this->resultArray)) { return $this->resultArray; } // In the event that query caching is on, the result_id variable // will not be a valid resource so we'll simply return an empty // array. if (is_bool($this->resultID) || ! $this->resultID || $this->numRows === 0) { return []; } if ($this->resultObject) { foreach ($this->resultObject as $row) { $this->resultArray[] = (array) $row; } return $this->resultArray; } is_null($this->rowData) || $this->dataSeek(0); while ($row = $this->fetchAssoc()) { $this->resultArray[] = $row; } return $this->resultArray; }
php
{ "resource": "" }
q254432
BaseResult.getResultObject
test
public function getResultObject(): array { if (! empty($this->resultObject)) { return $this->resultObject; } // In the event that query caching is on, the result_id variable // will not be a valid resource so we'll simply return an empty // array. if (is_bool($this->resultID) || ! $this->resultID || $this->numRows === 0) { return []; } if ($this->resultArray) { foreach ($this->resultArray as $row) { $this->resultObject[] = (object) $row; } return $this->resultObject; } is_null($this->rowData) || $this->dataSeek(0); while ($row = $this->fetchObject()) { $this->resultObject[] = $row; } return $this->resultObject; }
php
{ "resource": "" }
q254433
BaseResult.getRow
test
public function getRow($n = 0, string $type = 'object') { if (! is_numeric($n)) { // We cache the row data for subsequent uses is_array($this->rowData) || $this->rowData = $this->getRowArray(0); // array_key_exists() instead of isset() to allow for NULL values if (empty($this->rowData) || ! array_key_exists($n, $this->rowData)) { return null; } return $this->rowData[$n]; } if ($type === 'object') { return $this->getRowObject($n); } elseif ($type === 'array') { return $this->getRowArray($n); } return $this->getCustomRowObject($n, $type); }
php
{ "resource": "" }
q254434
BaseResult.getCustomRowObject
test
public function getCustomRowObject(int $n, string $className) { isset($this->customResultObject[$className]) || $this->getCustomResultObject($className); if (empty($this->customResultObject[$className])) { return null; } if ($n !== $this->currentRow && isset($this->customResultObject[$className][$n])) { $this->currentRow = $n; } return $this->customResultObject[$className][$this->currentRow]; }
php
{ "resource": "" }
q254435
BaseResult.getRowArray
test
public function getRowArray(int $n = 0) { $result = $this->getResultArray(); if (empty($result)) { return null; } if ($n !== $this->currentRow && isset($result[$n])) { $this->currentRow = $n; } return $result[$this->currentRow]; }
php
{ "resource": "" }
q254436
BaseResult.getRowObject
test
public function getRowObject(int $n = 0) { $result = $this->getResultObject(); if (empty($result)) { return null; } if ($n !== $this->customResultObject && isset($result[$n])) { $this->currentRow = $n; } return $result[$this->currentRow]; }
php
{ "resource": "" }
q254437
BaseResult.setRow
test
public function setRow($key, $value = null) { // We cache the row data for subsequent uses if (! is_array($this->rowData)) { $this->rowData = $this->getRowArray(0); } if (is_array($key)) { foreach ($key as $k => $v) { $this->rowData[$k] = $v; } return; } if ($key !== '' && $value !== null) { $this->rowData[$key] = $value; } }
php
{ "resource": "" }
q254438
BaseResult.getFirstRow
test
public function getFirstRow(string $type = 'object') { $result = $this->getResult($type); return (empty($result)) ? null : $result[0]; }
php
{ "resource": "" }
q254439
BaseResult.getLastRow
test
public function getLastRow(string $type = 'object') { $result = $this->getResult($type); return (empty($result)) ? null : $result[count($result) - 1]; }
php
{ "resource": "" }
q254440
BaseResult.getNextRow
test
public function getNextRow(string $type = 'object') { $result = $this->getResult($type); if (empty($result)) { return null; } return isset($result[$this->currentRow + 1]) ? $result[++ $this->currentRow] : null; }
php
{ "resource": "" }
q254441
BaseResult.getUnbufferedRow
test
public function getUnbufferedRow(string $type = 'object') { if ($type === 'array') { return $this->fetchAssoc(); } elseif ($type === 'object') { return $this->fetchObject(); } return $this->fetchObject($type); }
php
{ "resource": "" }
q254442
Negotiate.match
test
protected function match(array $acceptable, string $supported, bool $enforceTypes = false): bool { $supported = $this->parseHeader($supported); if (is_array($supported) && count($supported) === 1) { $supported = $supported[0]; } // Is it an exact match? if ($acceptable['value'] === $supported['value']) { return $this->matchParameters($acceptable, $supported); } // Do we need to compare types/sub-types? Only used // by negotiateMedia(). if ($enforceTypes) { return $this->matchTypes($acceptable, $supported); } return false; }
php
{ "resource": "" }
q254443
Negotiate.matchParameters
test
protected function matchParameters(array $acceptable, array $supported): bool { if (count($acceptable['params']) !== count($supported['params'])) { return false; } foreach ($supported['params'] as $label => $value) { if (! isset($acceptable['params'][$label]) || $acceptable['params'][$label] !== $value) { return false; } } return true; }
php
{ "resource": "" }
q254444
Console.run
test
public function run(bool $useSafeOutput = false) { $path = CLI::getURI() ?: 'list'; // Set the path for the application to route to. $this->app->setPath("ci{$path}"); return $this->app->useSafeOutput($useSafeOutput)->run(); }
php
{ "resource": "" }
q254445
Console.showHeader
test
public function showHeader() { CLI::newLine(1); CLI::write(CLI::color('CodeIgniter CLI Tool', 'green') . ' - Version ' . CodeIgniter::CI_VERSION . ' - Server-Time: ' . date('Y-m-d H:i:sa')); CLI::newLine(1); }
php
{ "resource": "" }
q254446
Pager.links
test
public function links(string $group = 'default', string $template = 'default_full'): string { $this->ensureGroup($group); return $this->displayLinks($group, $template); }
php
{ "resource": "" }
q254447
Pager.makeLinks
test
public function makeLinks(int $page, int $perPage, int $total, string $template = 'default_full', int $segment = 0): string { $name = time(); $this->store($name, $page, $perPage, $total, $segment); return $this->displayLinks($name, $template); }
php
{ "resource": "" }
q254448
Pager.store
test
public function store(string $group, int $page, int $perPage, int $total, int $segment = 0) { $this->segment[$group] = $segment; $this->ensureGroup($group); $this->groups[$group]['currentPage'] = $page; $this->groups[$group]['perPage'] = $perPage; $this->groups[$group]['total'] = $total; $this->groups[$group]['pageCount'] = (int)ceil($total / $perPage); return $this; }
php
{ "resource": "" }
q254449
Pager.setPath
test
public function setPath(string $path, string $group = 'default') { $this->ensureGroup($group); $this->groups[$group]['uri']->setPath($path); return $this; }
php
{ "resource": "" }
q254450
Pager.getPageCount
test
public function getPageCount(string $group = 'default'): int { $this->ensureGroup($group); return $this->groups[$group]['pageCount']; }
php
{ "resource": "" }
q254451
Pager.getCurrentPage
test
public function getCurrentPage(string $group = 'default'): int { $this->ensureGroup($group); return $this->groups[$group]['currentPage']; }
php
{ "resource": "" }
q254452
Pager.hasMore
test
public function hasMore(string $group = 'default'): bool { $this->ensureGroup($group); return ($this->groups[$group]['currentPage'] * $this->groups[$group]['perPage']) < $this->groups[$group]['total']; }
php
{ "resource": "" }
q254453
Pager.getLastPage
test
public function getLastPage(string $group = 'default') { $this->ensureGroup($group); if (! is_numeric($this->groups[$group]['total']) || ! is_numeric($this->groups[$group]['perPage'])) { return null; } return (int)ceil($this->groups[$group]['total'] / $this->groups[$group]['perPage']); }
php
{ "resource": "" }
q254454
Pager.getPageURI
test
public function getPageURI(int $page = null, string $group = 'default', bool $returnObject = false) { $this->ensureGroup($group); /** * @var \CodeIgniter\HTTP\URI $uri */ $uri = $this->groups[$group]['uri']; $segment = $this->segment[$group] ?? 0; if ($segment) { $uri->setSegment($segment, $page); } else { $uri->addQuery('page', $page); } if ($this->only) { $query = array_intersect_key($_GET, array_flip($this->only)); if (! $segment) { $query['page'] = $page; } $uri->setQueryArray($query); } return $returnObject === true ? $uri : (string) $uri; }
php
{ "resource": "" }
q254455
Pager.getNextPageURI
test
public function getNextPageURI(string $group = 'default', bool $returnObject = false) { $this->ensureGroup($group); $last = $this->getLastPage($group); $curr = $this->getCurrentPage($group); $page = null; if (! empty($last) && ! empty($curr) && $last === $curr) { return null; } if ($last > $curr) { $page = $curr + 1; } return $this->getPageURI($page, $group, $returnObject); }
php
{ "resource": "" }
q254456
Pager.getPreviousPageURI
test
public function getPreviousPageURI(string $group = 'default', bool $returnObject = false) { $this->ensureGroup($group); $first = $this->getFirstPage($group); $curr = $this->getCurrentPage($group); $page = null; if (! empty($first) && ! empty($curr) && $first === $curr) { return null; } if ($first < $curr) { $page = $curr - 1; } return $this->getPageURI($page, $group, $returnObject); }
php
{ "resource": "" }
q254457
Pager.getPerPage
test
public function getPerPage(string $group = 'default'): int { $this->ensureGroup($group); return (int) $this->groups[$group]['perPage']; }
php
{ "resource": "" }
q254458
Pager.getDetails
test
public function getDetails(string $group = 'default'): array { if (! array_key_exists($group, $this->groups)) { throw PagerException::forInvalidPaginationGroup($group); } $newGroup = $this->groups[$group]; $newGroup['next'] = $this->getNextPageURI($group); $newGroup['previous'] = $this->getPreviousPageURI($group); $newGroup['segment'] = $this->segment[$group] ?? 0; return $newGroup; }
php
{ "resource": "" }
q254459
Pager.ensureGroup
test
protected function ensureGroup(string $group) { if (array_key_exists($group, $this->groups)) { return; } $this->groups[$group] = [ 'uri' => clone Services::request()->uri, 'hasMore' => false, 'total' => null, 'perPage' => $this->config->perPage, 'pageCount' => 1, ]; if (array_key_exists($group, $this->segment)) { try { $this->groups[$group]['currentPage'] = $this->groups[$group]['uri']->getSegment($this->segment[$group]); } catch (\CodeIgniter\HTTP\Exceptions\HTTPException $e) { $this->groups[$group]['currentPage'] = 1; } } else { $this->groups[$group]['currentPage'] = $_GET['page_' . $group] ?? $_GET['page'] ?? 1; } if ($_GET) { $this->groups[$group]['uri'] = $this->groups[$group]['uri']->setQueryArray($_GET); } }
php
{ "resource": "" }
q254460
TimeDifference.getYears
test
public function getYears(bool $raw = false) { if ($raw) { return $this->difference / YEAR; } $time = clone($this->currentTime); return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_YEAR); }
php
{ "resource": "" }
q254461
TimeDifference.getMonths
test
public function getMonths(bool $raw = false) { if ($raw) { return $this->difference / MONTH; } $time = clone($this->currentTime); return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_MONTH); }
php
{ "resource": "" }
q254462
TimeDifference.getWeeks
test
public function getWeeks(bool $raw = false) { if ($raw) { return $this->difference / WEEK; } $time = clone($this->currentTime); return (int)($time->fieldDifference($this->testTime, IntlCalendar::FIELD_DAY_OF_YEAR) / 7); }
php
{ "resource": "" }
q254463
TimeDifference.getDays
test
public function getDays(bool $raw = false) { if ($raw) { return $this->difference / DAY; } $time = clone($this->currentTime); return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_DAY_OF_YEAR); }
php
{ "resource": "" }
q254464
TimeDifference.getHours
test
public function getHours(bool $raw = false) { if ($raw) { return $this->difference / HOUR; } $time = clone($this->currentTime); return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_HOUR_OF_DAY); }
php
{ "resource": "" }
q254465
TimeDifference.getMinutes
test
public function getMinutes(bool $raw = false) { if ($raw) { return $this->difference / MINUTE; } $time = clone($this->currentTime); return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_MINUTE); }
php
{ "resource": "" }
q254466
TimeDifference.getSeconds
test
public function getSeconds(bool $raw = false) { if ($raw) { return $this->difference; } $time = clone($this->currentTime); return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_SECOND); }
php
{ "resource": "" }
q254467
TimeDifference.humanize
test
public function humanize(string $locale = null): string { $current = clone($this->currentTime); $years = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_YEAR); $months = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_MONTH); $days = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_DAY_OF_YEAR); $hours = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_HOUR_OF_DAY); $minutes = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_MINUTE); $phrase = null; if ($years !== 0) { $phrase = lang('Time.years', [abs($years)], $locale); $before = $years < 0; } else if ($months !== 0) { $phrase = lang('Time.months', [abs($months)], $locale); $before = $months < 0; } else if ($days !== 0 && (abs($days) >= 7)) { $weeks = ceil($days / 7); $phrase = lang('Time.weeks', [abs($weeks)], $locale); $before = $days < 0; } else if ($days !== 0) { $phrase = lang('Time.days', [abs($days)], $locale); $before = $days < 0; } else if ($hours !== 0) { $phrase = lang('Time.hours', [abs($hours)], $locale); $before = $hours < 0; } else if ($minutes !== 0) { $phrase = lang('Time.minutes', [abs($minutes)], $locale); $before = $minutes < 0; } else { return lang('Time.now', [], $locale); } return $before ? lang('Time.ago', [$phrase], $locale) : lang('Time.inFuture', [$phrase], $locale); }
php
{ "resource": "" }
q254468
Database.load
test
public function load(array $params = [], string $alias) { // No DB specified? Beat them senseless... if (empty($params['DBDriver'])) { throw new \InvalidArgumentException('You have not selected a database type to connect to.'); } $className = strpos($params['DBDriver'], '\\') === false ? '\CodeIgniter\Database\\' . $params['DBDriver'] . '\\Connection' : $params['DBDriver'] . '\\Connection'; $class = new $className($params); // Store the connection $this->connections[$alias] = $class; return $this->connections[$alias]; }
php
{ "resource": "" }
q254469
Database.loadForge
test
public function loadForge(ConnectionInterface $db) { $className = strpos($db->DBDriver, '\\') === false ? '\CodeIgniter\Database\\' . $db->DBDriver . '\\Forge' : $db->DBDriver . '\\Forge'; // Make sure a connection exists if (! $db->connID) { $db->initialize(); } $class = new $className($db); return $class; }
php
{ "resource": "" }
q254470
Entity.hasPropertyChanged
test
protected function hasPropertyChanged(string $key, $value = null): bool { return ! (($this->_original[$key] === null && $value === null) || $this->_original[$key] === $value); }
php
{ "resource": "" }
q254471
Entity.mapProperty
test
protected function mapProperty(string $key) { if (empty($this->_options['datamap'])) { return $key; } if (isset($this->_options['datamap'][$key]) && ! empty($this->_options['datamap'][$key])) { return $this->_options['datamap'][$key]; } return $key; }
php
{ "resource": "" }
q254472
Entity.mutateDate
test
protected function mutateDate($value) { if ($value instanceof Time) { return $value; } if ($value instanceof \DateTime) { return Time::instance($value); } if (is_numeric($value)) { return Time::createFromTimestamp($value); } if (is_string($value)) { return Time::parse($value); } return $value; }
php
{ "resource": "" }
q254473
Entity.castAsJson
test
private function castAsJson($value, bool $asArray = false) { $tmp = ! is_null($value) ? ($asArray ? [] : new \stdClass) : null; if (function_exists('json_decode')) { if ((is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0 || (strpos($value, '"') === 0 && strrpos($value, '"') === 0 ))) || is_numeric($value)) { $tmp = json_decode($value, $asArray); if (json_last_error() !== JSON_ERROR_NONE) { throw CastException::forInvalidJsonFormatException(json_last_error()); } } } return $tmp; }
php
{ "resource": "" }
q254474
Modules.shouldDiscover
test
public function shouldDiscover(string $alias) { if (! $this->enabled) { return false; } $alias = strtolower($alias); return in_array($alias, $this->activeExplorers); }
php
{ "resource": "" }
q254475
Model.findAll
test
public function findAll(int $limit = 0, int $offset = 0) { $builder = $this->builder(); if ($this->tempUseSoftDeletes === true) { $builder->where($this->table . '.' . $this->deletedField, 0); } $row = $builder->limit($limit, $offset) ->get(); $row = $row->getResult($this->tempReturnType); $row = $this->trigger('afterFind', ['data' => $row, 'limit' => $limit, 'offset' => $offset]); $this->tempReturnType = $this->returnType; $this->tempUseSoftDeletes = $this->useSoftDeletes; return $row['data']; }
php
{ "resource": "" }
q254476
Model.first
test
public function first() { $builder = $this->builder(); if ($this->tempUseSoftDeletes === true) { $builder->where($this->table . '.' . $this->deletedField, 0); } // Some databases, like PostgreSQL, need order // information to consistently return correct results. if (empty($builder->QBOrderBy) && ! empty($this->primaryKey)) { $builder->orderBy($this->table . '.' . $this->primaryKey, 'asc'); } $row = $builder->limit(1, 0) ->get(); $row = $row->getFirstRow($this->tempReturnType); $row = $this->trigger('afterFind', ['data' => $row]); $this->tempReturnType = $this->returnType; return $row['data']; }
php
{ "resource": "" }
q254477
Model.save
test
public function save($data): bool { if (empty($data)) { return true; } if (is_object($data) && isset($data->{$this->primaryKey})) { $response = $this->update($data->{$this->primaryKey}, $data); } elseif (is_array($data) && ! empty($data[$this->primaryKey])) { $response = $this->update($data[$this->primaryKey], $data); } else { $response = $this->insert($data, false); // call insert directly if you want the ID or the record object if ($response !== false) { $response = true; } } return $response; }
php
{ "resource": "" }
q254478
Model.classToArray
test
public static function classToArray($data, $primaryKey = null, string $dateFormat = 'datetime', bool $onlyChanged = true): array { if (method_exists($data, 'toRawArray')) { $properties = $data->toRawArray($onlyChanged); // Always grab the primary key otherwise updates will fail. if (! empty($properties) && ! empty($primaryKey) && ! in_array($primaryKey, $properties)) { $properties[$primaryKey] = $data->{$primaryKey}; } } else { $mirror = new ReflectionClass($data); $props = $mirror->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED); $properties = []; // Loop over each property, // saving the name/value in a new array we can return. foreach ($props as $prop) { // Must make protected values accessible. $prop->setAccessible(true); $propName = $prop->getName(); $properties[$propName] = $prop->getValue($data); } } // Convert any Time instances to appropriate $dateFormat if ($properties) { foreach ($properties as $key => $value) { if ($value instanceof Time) { switch ($dateFormat) { case 'datetime': $converted = $value->format('Y-m-d H:i:s'); break; case 'date': $converted = $value->format('Y-m-d'); break; case 'int': $converted = $value->getTimestamp(); break; default: $converted = (string)$value; } $properties[$key] = $converted; } } } return $properties; }
php
{ "resource": "" }
q254479
Model.insert
test
public function insert($data = null, bool $returnID = true) { $escape = null; $this->insertID = 0; if (empty($data)) { $data = $this->tempData['data'] ?? null; $escape = $this->tempData['escape'] ?? null; $this->tempData = []; } if (empty($data)) { throw DataException::forEmptyDataset('insert'); } // If $data is using a custom class with public or protected // properties representing the table elements, we need to grab // them as an array. if (is_object($data) && ! $data instanceof stdClass) { $data = static::classToArray($data, $this->primaryKey, $this->dateFormat, false); } // If it's still a stdClass, go ahead and convert to // an array so doProtectFields and other model methods // don't have to do special checks. if (is_object($data)) { $data = (array) $data; } // Validate data before saving. if ($this->skipValidation === false) { if ($this->validate($data) === false) { return false; } } // Save the original data so it can be passed to // any Model Event callbacks and not stripped // by doProtectFields $originalData = $data; // Must be called first so we don't // strip out created_at values. $data = $this->doProtectFields($data); // Set created_at and updated_at with same time $date = $this->setDate(); if ($this->useTimestamps && ! empty($this->createdField) && ! array_key_exists($this->createdField, $data)) { $data[$this->createdField] = $date; } if ($this->useTimestamps && ! empty($this->updatedField) && ! array_key_exists($this->updatedField, $data)) { $data[$this->updatedField] = $date; } $data = $this->trigger('beforeInsert', ['data' => $data]); // Must use the set() method to ensure objects get converted to arrays $result = $this->builder() ->set($data['data'], '', $escape) ->insert(); $this->trigger('afterInsert', ['data' => $originalData, 'result' => $result]); // If insertion failed, get our of here if (! $result) { return $result; } $this->insertID = $this->db->insertID(); // otherwise return the insertID, if requested. return $returnID ? $this->insertID : $result; }
php
{ "resource": "" }
q254480
Model.insertBatch
test
public function insertBatch(array $set = null, bool $escape = null, int $batchSize = 100, bool $testing = false) { if (is_array($set) && $this->skipValidation === false) { foreach ($set as $row) { if ($this->validate($row) === false) { return false; } } } return $this->builder()->insertBatch($set, $escape, $batchSize, $testing); }
php
{ "resource": "" }
q254481
Model.builder
test
protected function builder(string $table = null) { if ($this->builder instanceof BaseBuilder) { return $this->builder; } // We're going to force a primary key to exist // so we don't have overly convoluted code, // and future features are likely to require them. if (empty($this->primaryKey)) { throw ModelException::forNoPrimaryKey(get_class($this)); } $table = empty($table) ? $this->table : $table; // Ensure we have a good db connection if (! $this->db instanceof BaseConnection) { $this->db = Database::connect($this->DBGroup); } $this->builder = $this->db->table($table); return $this->builder; }
php
{ "resource": "" }
q254482
Model.doProtectFields
test
protected function doProtectFields(array $data): array { if ($this->protectFields === false) { return $data; } if (empty($this->allowedFields)) { throw DataException::forInvalidAllowedFields(get_class($this)); } if (is_array($data) && count($data)) { foreach ($data as $key => $val) { if (! in_array($key, $this->allowedFields)) { unset($data[$key]); } } } return $data; }
php
{ "resource": "" }
q254483
Model.cleanValidationRules
test
protected function cleanValidationRules(array $rules, array $data = null): array { if (empty($data)) { return []; } foreach ($rules as $field => $rule) { if (! array_key_exists($field, $data)) { unset($rules[$field]); } } return $rules; }
php
{ "resource": "" }
q254484
Model.getValidationRules
test
public function getValidationRules(array $options = []): array { $rules = $this->validationRules; if (isset($options['except'])) { $rules = array_diff_key($rules, array_flip($options['except'])); } elseif (isset($options['only'])) { $rules = array_intersect_key($rules, array_flip($options['only'])); } return $rules; }
php
{ "resource": "" }
q254485
Model.countAllResults
test
public function countAllResults(bool $reset = true, bool $test = false) { if ($this->tempUseSoftDeletes === true) { $this->builder()->where($this->deletedField, 0); } return $this->builder()->countAllResults($reset, $test); }
php
{ "resource": "" }
q254486
CURLRequest.setAuth
test
public function setAuth(string $username, string $password, string $type = 'basic') { $this->config['auth'] = [ $username, $password, $type, ]; return $this; }
php
{ "resource": "" }
q254487
CURLRequest.setForm
test
public function setForm(array $params, bool $multipart = false) { if ($multipart) { $this->config['multipart'] = $params; } else { $this->config['form_params'] = $params; } return $this; }
php
{ "resource": "" }
q254488
CURLRequest.parseOptions
test
protected function parseOptions(array $options) { if (array_key_exists('baseURI', $options)) { $this->baseURI = $this->baseURI->setURI($options['baseURI']); unset($options['baseURI']); } if (array_key_exists('headers', $options) && is_array($options['headers'])) { foreach ($options['headers'] as $name => $value) { $this->setHeader($name, $value); } unset($options['headers']); } if (array_key_exists('delay', $options)) { // Convert from the milliseconds passed in // to the seconds that sleep requires. $this->delay = (float) $options['delay'] / 1000; unset($options['delay']); } foreach ($options as $key => $value) { $this->config[$key] = $value; } }
php
{ "resource": "" }
q254489
CURLRequest.getMethod
test
public function getMethod(bool $upper = false): string { return ($upper) ? strtoupper($this->method) : strtolower($this->method); }
php
{ "resource": "" }
q254490
CURLRequest.send
test
public function send(string $method, string $url) { // Reset our curl options so we're on a fresh slate. $curl_options = []; if (! empty($this->config['query']) && is_array($this->config['query'])) { // This is likely too naive a solution. // Should look into handling when $url already // has query vars on it. $url .= '?' . http_build_query($this->config['query']); unset($this->config['query']); } $curl_options[CURLOPT_URL] = $url; $curl_options[CURLOPT_RETURNTRANSFER] = true; $curl_options[CURLOPT_HEADER] = true; $curl_options[CURLOPT_FRESH_CONNECT] = true; // Disable @file uploads in post data. $curl_options[CURLOPT_SAFE_UPLOAD] = true; $curl_options = $this->setCURLOptions($curl_options, $this->config); $curl_options = $this->applyMethod($method, $curl_options); $curl_options = $this->applyRequestHeaders($curl_options); // Do we need to delay this request? if ($this->delay > 0) { sleep($this->delay); } $output = $this->sendRequest($curl_options); $continueStr = "HTTP/1.1 100 Continue\x0d\x0a\x0d\x0a"; if (strpos($output, $continueStr) === 0) { $output = substr($output, strlen($continueStr)); } // Split out our headers and body $break = strpos($output, "\r\n\r\n"); if ($break !== false) { // Our headers $headers = explode("\n", substr($output, 0, $break)); $this->setResponseHeaders($headers); // Our body $body = substr($output, $break + 4); $this->response->setBody($body); } else { $this->response->setBody($output); } return $this->response; }
php
{ "resource": "" }
q254491
CURLRequest.applyRequestHeaders
test
protected function applyRequestHeaders(array $curl_options = []): array { $headers = $this->getHeaders(); if (empty($headers)) { return $curl_options; } $set = []; foreach ($headers as $name => $value) { $set[] = $name . ': ' . $this->getHeaderLine($name); } $curl_options[CURLOPT_HTTPHEADER] = $set; return $curl_options; }
php
{ "resource": "" }
q254492
CURLRequest.setResponseHeaders
test
protected function setResponseHeaders(array $headers = []) { foreach ($headers as $header) { if (($pos = strpos($header, ':')) !== false) { $title = substr($header, 0, $pos); $value = substr($header, $pos + 1); $this->response->setHeader($title, $value); } else if (strpos($header, 'HTTP') === 0) { preg_match('#^HTTP\/([12]\.[01]) ([0-9]+) (.+)#', $header, $matches); if (isset($matches[1])) { $this->response->setProtocolVersion($matches[1]); } if (isset($matches[2])) { $this->response->setStatusCode($matches[2], $matches[3] ?? null); } } } }
php
{ "resource": "" }
q254493
CURLRequest.sendRequest
test
protected function sendRequest(array $curl_options = []): string { $ch = curl_init(); curl_setopt_array($ch, $curl_options); // Send the request and wait for a response. $output = curl_exec($ch); if ($output === false) { throw HTTPException::forCurlError(curl_errno($ch), curl_error($ch)); } curl_close($ch); return $output; }
php
{ "resource": "" }
q254494
MigrationRunner.version
test
public function version(string $targetVersion, string $namespace = null, string $group = null) { if (! $this->enabled) { throw ConfigException::forDisabledMigrations(); } $this->ensureTable(); // Set Namespace if not null if (! is_null($namespace)) { $this->setNamespace($namespace); } // Set database group if not null if (! is_null($group)) { $this->setGroup($group); } // Sequential versions need adjusting to 3 places so they can be found later. if ($this->type === 'sequential') { $targetVersion = str_pad($targetVersion, 3, '0', STR_PAD_LEFT); } $migrations = $this->findMigrations(); if (empty($migrations)) { return true; } // Get Namespace current version // Note: We use strings, so that timestamp versions work on 32-bit systems $currentVersion = $this->getVersion(); if ($targetVersion > $currentVersion) { // Moving Up $method = 'up'; ksort($migrations); } else { // Moving Down, apply in reverse order $method = 'down'; krsort($migrations); } // Check Migration consistency $this->checkMigrations($migrations, $method, $targetVersion); // loop migration for each namespace (module) $migrationStatus = false; foreach ($migrations as $version => $migration) { // Only include migrations within the scoop if (($method === 'up' && $version > $currentVersion && $version <= $targetVersion) || ( $method === 'down' && $version <= $currentVersion && $version > $targetVersion)) { $migrationStatus = false; include_once $migration->path; // Get namespaced class name $class = $this->namespace . '\Database\Migrations\Migration_' . ($migration->name); $this->setName($migration->name); // Validate the migration file structure if (! class_exists($class, false)) { throw new \RuntimeException(sprintf(lang('Migrations.classNotFound'), $class)); } // Forcing migration to selected database group $instance = new $class(\Config\Database::forge($this->group)); if (! is_callable([$instance, $method])) { throw new \RuntimeException(sprintf(lang('Migrations.missingMethod'), $method)); } $instance->{$method}(); if ($method === 'up') { $this->addHistory($migration->version); } elseif ($method === 'down') { $this->removeHistory($migration->version); } $migrationStatus = true; } } return ($migrationStatus) ? $targetVersion : false; }
php
{ "resource": "" }
q254495
MigrationRunner.findMigrations
test
public function findMigrations(): array { $migrations = []; // If $this->path contains a valid directory use it. if (! empty($this->path)) { helper('filesystem'); $dir = rtrim($this->path, DIRECTORY_SEPARATOR) . '/'; $files = get_filenames($dir, true); } // Otherwise use FileLocator to search files in the subdirectory of the namespace else { $locator = Services::locator(true); $files = $locator->listNamespaceFiles($this->namespace, '/Database/Migrations/'); } // Load all *_*.php files in the migrations path // We can't use glob if we want it to be testable.... foreach ($files as $file) { if (substr($file, -4) !== '.php') { continue; } // Remove the extension $name = basename($file, '.php'); // Filter out non-migration files if (preg_match($this->regex, $name)) { // Create migration object using stdClass $migration = new \stdClass(); // Get migration version number $migration->version = $this->getMigrationNumber($name); $migration->name = $this->getMigrationName($name); $migration->path = ! empty($this->path) && strpos($file, $this->path) !== 0 ? $this->path . $file : $file; // Add to migrations[version] $migrations[$migration->version] = $migration; } } ksort($migrations); return $migrations; }
php
{ "resource": "" }
q254496
MigrationRunner.checkMigrations
test
protected function checkMigrations(array $migrations, string $method, string $targetVersion): bool { // Check if no migrations found if (empty($migrations)) { if ($this->silent) { return false; } throw new \RuntimeException(lang('Migrations.empty')); } // Check if $targetVersion file is found if ((int)$targetVersion !== 0 && ! array_key_exists($targetVersion, $migrations)) { if ($this->silent) { return false; } throw new \RuntimeException(lang('Migrations.notFound') . $targetVersion); } ksort($migrations); if ($method === 'down') { $history_migrations = $this->getHistory($this->group); $history_size = count($history_migrations) - 1; } // Check for sequence gaps $loop = 0; foreach ($migrations as $migration) { if ($this->type === 'sequential' && abs($migration->version - $loop) > 1) { throw new \RuntimeException(lang('Migrations.gap') . ' ' . $migration->version); } // Check if all old migration files are all available to do downgrading if ($method === 'down') { if ($loop <= $history_size && $history_migrations[$loop]['version'] !== $migration->version) { throw new \RuntimeException(lang('Migrations.gap') . ' ' . $migration->version); } } $loop ++; } return true; }
php
{ "resource": "" }
q254497
MigrationRunner.getHistory
test
public function getHistory(string $group = 'default'): array { $this->ensureTable(); $query = $this->db->table($this->table) ->where('group', $group) ->where('namespace', $this->namespace) ->orderBy('version', 'ASC') ->get(); if (! $query) { return []; } return $query->getResultArray(); }
php
{ "resource": "" }
q254498
MigrationRunner.getMigrationName
test
protected function getMigrationName(string $migration): string { $parts = explode('_', $migration); array_shift($parts); return implode('_', $parts); }
php
{ "resource": "" }
q254499
MigrationRunner.getVersion
test
protected function getVersion(): string { $this->ensureTable(); $row = $this->db->table($this->table) ->select('version') ->where('group', $this->group) ->where('namespace', $this->namespace) ->orderBy('version', 'DESC') ->get(); return $row && ! is_null($row->getRow()) ? $row->getRow()->version : '0'; }
php
{ "resource": "" }