_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q254700
Autoloader.discoverComposerNamespaces
test
protected function discoverComposerNamespaces() { if (! is_file(COMPOSER_PATH)) { return false; } $composer = include COMPOSER_PATH; $paths = $composer->getPrefixesPsr4(); unset($composer); // Get rid of CodeIgniter so we don't have duplicates if (isset($paths['CodeIgniter\\'])) { unset($paths['CodeIgniter\\']); } // Composer stores paths with trailng slash. We don't. $newPaths = []; foreach ($paths as $key => $value) { $newPaths[rtrim($key, '\\ ')] = $value; } $this->prefixes = array_merge($this->prefixes, $newPaths); }
php
{ "resource": "" }
q254701
Filters.date_modify
test
public static function date_modify($value, string $adjustment): string { $value = static::date($value, 'Y-m-d H:i:s'); return strtotime($adjustment, strtotime($value)); }
php
{ "resource": "" }
q254702
Filters.excerpt
test
public static function excerpt(string $value, string $phrase, int $radius = 100): string { helper('text'); return excerpt($value, $phrase, $radius); }
php
{ "resource": "" }
q254703
DotEnv.sanitizeValue
test
protected function sanitizeValue(string $value): string { if (! $value) { return $value; } // Does it begin with a quote? if (strpbrk($value[0], '"\'') !== false) { // value starts with a quote $quote = $value[0]; $regexPattern = sprintf( '/^ %1$s # match a quote at the start of the value ( # capturing sub-pattern used (?: # we do not need to capture this [^%1$s\\\\] # any character other than a quote or backslash |\\\\\\\\ # or two backslashes together |\\\\%1$s # or an escaped quote e.g \" )* # as many characters that match the previous rules ) # end of the capturing sub-pattern %1$s # and the closing quote .*$ # and discard any string after the closing quote /mx', $quote ); $value = preg_replace($regexPattern, '$1', $value); $value = str_replace("\\$quote", $quote, $value); $value = str_replace('\\\\', '\\', $value); } else { $parts = explode(' #', $value, 2); $value = trim($parts[0]); // Unquoted values cannot contain whitespace if (preg_match('/\s+/', $value) > 0) { throw new \InvalidArgumentException('.env values containing spaces must be surrounded by quotes.'); } } return $value; }
php
{ "resource": "" }
q254704
DotEnv.resolveNestedVariables
test
protected function resolveNestedVariables(string $value): string { if (strpos($value, '$') !== false) { $loader = $this; $value = preg_replace_callback( '/\${([a-zA-Z0-9_]+)}/', function ($matchedPatterns) use ($loader) { $nestedVariable = $loader->getVariable($matchedPatterns[1]); if (is_null($nestedVariable)) { return $matchedPatterns[0]; } return $nestedVariable; }, $value ); } return $value; }
php
{ "resource": "" }
q254705
Connection.setDatabase
test
public function setDatabase(string $databaseName): bool { if ($databaseName === '') { $databaseName = $this->database; } if (empty($this->connID)) { $this->initialize(); } if ($this->connID->select_db($databaseName)) { $this->database = $databaseName; return true; } return false; }
php
{ "resource": "" }
q254706
Connection.execute
test
public function execute(string $sql) { while ($this->connID->more_results()) { $this->connID->next_result(); if ($res = $this->connID->store_result()) { $res->free(); } } return $this->connID->query($this->prepQuery($sql)); }
php
{ "resource": "" }
q254707
Connection.prepQuery
test
protected function prepQuery(string $sql): string { // mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack // modifies the query so that it a proper number of affected rows is returned. if ($this->deleteHack === true && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { return trim($sql) . ' WHERE 1=1'; } return $sql; }
php
{ "resource": "" }
q254708
Connection.error
test
public function error(): array { if (! empty($this->mysqli->connect_errno)) { return [ 'code' => $this->mysqli->connect_errno, 'message' => $this->mysqli->connect_error, ]; } return [ 'code' => $this->connID->errno, 'message' => $this->connID->error, ]; }
php
{ "resource": "" }
q254709
Connection.execute
test
public function execute(string $sql) { return $this->isWriteType($sql) ? $this->connID->exec($sql) : $this->connID->query($sql); }
php
{ "resource": "" }
q254710
Connection.getFieldNames
test
public function getFieldNames(string $table) { // Is there a cached result? if (isset($this->dataCache['field_names'][$table])) { return $this->dataCache['field_names'][$table]; } if (empty($this->connID)) { $this->initialize(); } if (false === ($sql = $this->_listColumns($table))) { if ($this->DBDebug) { throw new DatabaseException(lang('Database.featureUnavailable')); } return false; } $query = $this->query($sql); $this->dataCache['field_names'][$table] = []; foreach ($query->getResultArray() as $row) { // Do we know from where to get the column's name? if (! isset($key)) { if (isset($row['column_name'])) { $key = 'column_name'; } elseif (isset($row['COLUMN_NAME'])) { $key = 'COLUMN_NAME'; } elseif (isset($row['name'])) { $key = 'name'; } else { // We have no other choice but to just get the first element's key. $key = key($row); } } $this->dataCache['field_names'][$table][] = $row[$key]; } return $this->dataCache['field_names'][$table]; }
php
{ "resource": "" }
q254711
Services.cache
test
public static function cache(Cache $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('cache', $config); } if (! is_object($config)) { $config = new Cache(); } return CacheFactory::getHandler($config); }
php
{ "resource": "" }
q254712
Services.clirequest
test
public static function clirequest(App $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('clirequest', $config); } if (! is_object($config)) { $config = config(App::class); } return new CLIRequest($config); }
php
{ "resource": "" }
q254713
Services.curlrequest
test
public static function curlrequest(array $options = [], ResponseInterface $response = null, App $config = null, bool $getShared = true) { if ($getShared === true) { return static::getSharedInstance('curlrequest', $options, $response, $config); } if (! is_object($config)) { $config = config(App::class); } if (! is_object($response)) { $response = new Response($config); } return new CURLRequest( $config, new URI($options['base_uri'] ?? null), $response, $options ); }
php
{ "resource": "" }
q254714
Services.honeypot
test
public static function honeypot(BaseConfig $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('honeypot', $config); } if (is_null($config)) { $config = new \Config\Honeypot(); } return new Honeypot($config); }
php
{ "resource": "" }
q254715
Services.language
test
public static function language(string $locale = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('language', $locale) ->setLocale($locale); } $locale = ! empty($locale) ? $locale : static::request() ->getLocale(); return new Language($locale); }
php
{ "resource": "" }
q254716
Services.logger
test
public static function logger(bool $getShared = true) { if ($getShared) { return static::getSharedInstance('logger'); } return new \CodeIgniter\Log\Logger(new Logger()); }
php
{ "resource": "" }
q254717
Services.negotiator
test
public static function negotiator(RequestInterface $request = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('negotiator', $request); } if (is_null($request)) { $request = static::request(); } return new Negotiate($request); }
php
{ "resource": "" }
q254718
Services.parser
test
public static function parser(string $viewPath = null, $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('parser', $viewPath, $config); } if (is_null($config)) { $config = new \Config\View(); } if (is_null($viewPath)) { $paths = config('Paths'); $viewPath = $paths->viewDirectory; } return new Parser($config, $viewPath, static::locator(true), CI_DEBUG, static::logger(true)); }
php
{ "resource": "" }
q254719
Services.request
test
public static function request(App $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('request', $config); } if (! is_object($config)) { $config = config(App::class); } return new IncomingRequest( $config, new URI(), 'php://input', new UserAgent() ); }
php
{ "resource": "" }
q254720
Services.response
test
public static function response(App $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('response', $config); } if (! is_object($config)) { $config = config(App::class); } return new Response($config); }
php
{ "resource": "" }
q254721
Services.redirectResponse
test
public static function redirectResponse(App $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('redirectResponse', $config); } if (! is_object($config)) { $config = config(App::class); } $response = new RedirectResponse($config); $response->setProtocolVersion(static::request() ->getProtocolVersion()); return $response; }
php
{ "resource": "" }
q254722
Services.router
test
public static function router(RouteCollectionInterface $routes = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('router', $routes); } if (empty($routes)) { $routes = static::routes(true); } return new Router($routes); }
php
{ "resource": "" }
q254723
Services.security
test
public static function security(App $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('security', $config); } if (! is_object($config)) { $config = config(App::class); } return new Security($config); }
php
{ "resource": "" }
q254724
Services.uri
test
public static function uri(string $uri = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('uri', $uri); } return new URI($uri); }
php
{ "resource": "" }
q254725
Services.validation
test
public static function validation(\Config\Validation $config = null, bool $getShared = true) { if ($getShared) { return static::getSharedInstance('validation', $config); } if (is_null($config)) { $config = config('Validation'); } return new Validation($config, static::renderer()); }
php
{ "resource": "" }
q254726
ListCommands.describeCommands
test
protected function describeCommands(array $commands = []) { ksort($commands); // Sort into buckets by group $sorted = []; $maxTitleLength = 0; foreach ($commands as $title => $command) { if (! isset($sorted[$command['group']])) { $sorted[$command['group']] = []; } $sorted[$command['group']][$title] = $command; $maxTitleLength = max($maxTitleLength, strlen($title)); } ksort($sorted); // Display it all... foreach ($sorted as $group => $items) { CLI::newLine(); CLI::write($group); foreach ($items as $title => $item) { $title = $this->padTitle($title, $maxTitleLength, 2, 2); $out = CLI::color($title, 'yellow'); if (isset($item['description'])) { $out .= CLI::wrap($item['description'], 125, strlen($title)); } CLI::write($out); } } }
php
{ "resource": "" }
q254727
ListCommands.padTitle
test
protected function padTitle(string $item, int $max, int $extra = 2, int $indent = 0): string { $max += $extra + $indent; $item = str_repeat(' ', $indent) . $item; $item = str_pad($item, $max); return $item; }
php
{ "resource": "" }
q254728
BaseUtils.getCSVFromResult
test
public function getCSVFromResult(ResultInterface $query, string $delim = ',', string $newline = "\n", string $enclosure = '"') { $out = ''; // First generate the headings from the table column names foreach ($query->getFieldNames() as $name) { $out .= $enclosure . str_replace($enclosure, $enclosure . $enclosure, $name) . $enclosure . $delim; } $out = substr($out, 0, -strlen($delim)) . $newline; // Next blast through the result array and build out the rows while ($row = $query->getUnbufferedRow('array')) { $line = []; foreach ($row as $item) { $line[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $item) . $enclosure; } $out .= implode($delim, $line) . $newline; } return $out; }
php
{ "resource": "" }
q254729
BaseUtils.getXMLFromResult
test
public function getXMLFromResult(ResultInterface $query, array $params = []): string { // Set our default values foreach (['root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t"] as $key => $val) { if (! isset($params[$key])) { $params[$key] = $val; } } // Create variables for convenience extract($params); // Load the xml helper helper('xml'); // Generate the result $xml = '<' . $root . '>' . $newline; while ($row = $query->getUnbufferedRow()) { $xml .= $tab . '<' . $element . '>' . $newline; foreach ($row as $key => $val) { $val = (!empty($val)) ? xml_convert($val) : ''; $xml .= $tab . $tab . '<' . $key . '>' . $val . '</' . $key . '>' . $newline; } $xml .= $tab . '</' . $element . '>' . $newline; } return $xml . '</' . $root . '>' . $newline; }
php
{ "resource": "" }
q254730
BaseCommand.call
test
protected function call(string $command, array $params = []) { // The CommandRunner will grab the first element // for the command name. array_unshift($params, $command); return $this->commands->index($params); }
php
{ "resource": "" }
q254731
Seeder.call
test
public function call(string $class) { if (empty($class)) { throw new \InvalidArgumentException('No Seeder was specified.'); } $path = str_replace('.php', '', $class) . '.php'; // If we have namespaced class, simply try to load it. if (strpos($class, '\\') !== false) { $seeder = new $class($this->config); } // Otherwise, try to load the class manually. else { $path = $this->seedPath . $path; if (! is_file($path)) { throw new \InvalidArgumentException('The specified Seeder is not a valid file: ' . $path); } // Assume the class has the correct namespace $class = APP_NAMESPACE . '\Database\Seeds\\' . $class; if (! class_exists($class, false)) { require_once $path; } $seeder = new $class($this->config); } $seeder->run(); unset($seeder); if (is_cli() && ! $this->silent) { CLI::write("Seeded: {$class}", 'green'); } }
php
{ "resource": "" }
q254732
Rules.in_list
test
public function in_list(string $value = null, string $list, array $data): bool { $list = explode(',', $list); $list = array_map(function ($value) { return trim($value); }, $list); return in_array($value, $list, true); }
php
{ "resource": "" }
q254733
Rules.less_than_equal_to
test
public function less_than_equal_to(string $str = null, string $max): bool { return is_numeric($str) ? ($str <= $max) : false; }
php
{ "resource": "" }
q254734
Rules.required_with
test
public function required_with($str = null, string $fields, array $data): bool { $fields = explode(',', $fields); // If the field is present we can safely assume that // the field is here, no matter whether the corresponding // search field is present or not. $present = $this->required($str ?? ''); if ($present) { return true; } // Still here? Then we fail this test if // any of the fields are present in $data // as $fields is the lis $requiredFields = []; foreach ($fields as $field) { if (array_key_exists($field, $data)) { $requiredFields[] = $field; } } // Remove any keys with empty values since, that means they // weren't truly there, as far as this is concerned. $requiredFields = array_filter($requiredFields, function ($item) use ($data) { return ! empty($data[$item]); }); return empty($requiredFields); }
php
{ "resource": "" }
q254735
Rules.required_without
test
public function required_without($str = null, string $fields, array $data): bool { $fields = explode(',', $fields); // If the field is present we can safely assume that // the field is here, no matter whether the corresponding // search field is present or not. $present = $this->required($str ?? ''); if ($present) { return true; } // Still here? Then we fail this test if // any of the fields are not present in $data foreach ($fields as $field) { if (! array_key_exists($field, $data)) { return false; } } return true; }
php
{ "resource": "" }
q254736
Router.validateRequest
test
protected function validateRequest(array $segments): array { $segments = array_filter($segments); $segments = array_values($segments); $c = count($segments); $directory_override = isset($this->directory); // Loop through our segments and return as soon as a controller // is found or when such a directory doesn't exist while ($c -- > 0) { $test = $this->directory . ucfirst($this->translateURIDashes === true ? str_replace('-', '_', $segments[0]) : $segments[0] ); if (! is_file(APPPATH . 'Controllers/' . $test . '.php') && $directory_override === false && is_dir(APPPATH . 'Controllers/' . $this->directory . ucfirst($segments[0]))) { $this->setDirectory(array_shift($segments), true); continue; } return $segments; } // This means that all segments were actually directories return $segments; }
php
{ "resource": "" }
q254737
Router.setDirectory
test
protected function setDirectory(string $dir = null, bool $append = false) { $dir = ucfirst($dir); if ($append !== true || empty($this->directory)) { $this->directory = str_replace('.', '', trim($dir, '/')) . '/'; } else { $this->directory .= str_replace('.', '', trim($dir, '/')) . '/'; } }
php
{ "resource": "" }
q254738
Router.setRequest
test
protected function setRequest(array $segments = []) { // If we don't have any segments - try the default controller; if (empty($segments)) { $this->setDefaultController(); return; } list($controller, $method) = array_pad(explode('::', $segments[0]), 2, null); $this->controller = $controller; // $this->method already contains the default method name, // so don't overwrite it with emptiness. if (! empty($method)) { $this->method = $method; } array_shift($segments); $this->params = $segments; }
php
{ "resource": "" }
q254739
Router.setDefaultController
test
protected function setDefaultController() { if (empty($this->controller)) { throw RouterException::forMissingDefaultRoute(); } // Is the method being specified? if (sscanf($this->controller, '%[^/]/%s', $class, $this->method) !== 2) { $this->method = 'index'; } if (! is_file(APPPATH . 'Controllers/' . $this->directory . ucfirst($class) . '.php')) { return; } $this->controller = ucfirst($class); log_message('info', 'Used the default controller.'); }
php
{ "resource": "" }
q254740
File.getSize
test
public function getSize(string $unit = 'b') { if (is_null($this->size)) { $this->size = filesize($this->getPathname()); } switch (strtolower($unit)) { case 'kb': return number_format($this->size / 1024, 3); case 'mb': return number_format(($this->size / 1024) / 1024, 3); } return (int) $this->size; }
php
{ "resource": "" }
q254741
File.move
test
public function move(string $targetPath, string $name = null, bool $overwrite = false) { $targetPath = rtrim($targetPath, '/') . '/'; $name = $name ?? $this->getBaseName(); $destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name); $oldName = empty($this->getRealPath()) ? $this->getPath() : $this->getRealPath(); if (! @rename($oldName, $destination)) { $error = error_get_last(); throw FileException::forUnableToMove($this->getBasename(), $targetPath, strip_tags($error['message'])); } @chmod($targetPath, 0777 & ~umask()); return new File($destination); }
php
{ "resource": "" }
q254742
File.getDestination
test
public function getDestination(string $destination, string $delimiter = '_', int $i = 0): string { while (is_file($destination)) { $info = pathinfo($destination); if (strpos($info['filename'], $delimiter) !== false) { $parts = explode($delimiter, $info['filename']); if (is_numeric(end($parts))) { $i = end($parts); array_pop($parts); array_push($parts, ++ $i); $destination = $info['dirname'] . '/' . implode($delimiter, $parts) . '.' . $info['extension']; } else { $destination = $info['dirname'] . '/' . $info['filename'] . $delimiter . ++ $i . '.' . $info['extension']; } } else { $destination = $info['dirname'] . '/' . $info['filename'] . $delimiter . ++ $i . '.' . $info['extension']; } } return $destination; }
php
{ "resource": "" }
q254743
Database.collect
test
public static function collect(Query $query) { $config = config('Toolbar'); // Provide default in case it's not set $max = $config->maxQueries ?: 100; if (count(static::$queries) < $max) { static::$queries[] = $query; } }
php
{ "resource": "" }
q254744
Database.formatTimelineData
test
protected function formatTimelineData(): array { $data = []; foreach ($this->connections as $alias => $connection) { // Connection Time $data[] = [ 'name' => 'Connecting to Database: "' . $alias . '"', 'component' => 'Database', 'start' => $connection->getConnectStart(), 'duration' => $connection->getConnectDuration(), ]; } foreach (static::$queries as $query) { $data[] = [ 'name' => 'Query', 'component' => 'Database', 'start' => $query->getStartTime(true), 'duration' => $query->getDuration(), ]; } return $data; }
php
{ "resource": "" }
q254745
FileLocator.locateFile
test
public function locateFile(string $file, string $folder = null, string $ext = 'php') { $file = $this->ensureExt($file, $ext); // Clears the folder name if it is at the beginning of the filename if (! empty($folder) && ($pos = strpos($file, $folder)) === 0) { $file = substr($file, strlen($folder . '/')); } // Is not namespaced? Try the application folder. if (strpos($file, '\\') === false) { return $this->legacyLocate($file, $folder); } // Standardize slashes to handle nested directories. $file = strtr($file, '/', '\\'); $segments = explode('\\', $file); // The first segment will be empty if a slash started the filename. if (empty($segments[0])) { unset($segments[0]); } $path = ''; $prefix = ''; $filename = ''; // Namespaces always comes with arrays of paths $namespaces = $this->autoloader->getNamespace(); while (! empty($segments)) { $prefix .= empty($prefix) ? ucfirst(array_shift($segments)) : '\\' . ucfirst(array_shift($segments)); if (empty($namespaces[$prefix])) { continue; } $path = $this->getNamespaces($prefix); $filename = implode('/', $segments); break; } // IF we have a folder name, then the calling function // expects this file to be within that folder, like 'Views', // or 'libraries'. if (! empty($folder) && strpos($path . $filename, '/' . $folder . '/') === false) { $filename = $folder . '/' . $filename; } $path .= $filename; return is_file($path) ? $path : false; }
php
{ "resource": "" }
q254746
FileLocator.getClassname
test
public function getClassname(string $file) : string { $php = file_get_contents($file); $tokens = token_get_all($php); $count = count($tokens); $dlm = false; $namespace = ''; $class_name = ''; for ($i = 2; $i < $count; $i++) { if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $tokens[$i][0] === T_STRING)) { if (! $dlm) { $namespace = 0; } if (isset($tokens[$i][1])) { $namespace = $namespace ? $namespace . '\\' . $tokens[$i][1] : $tokens[$i][1]; $dlm = true; } } elseif ($dlm && ($tokens[$i][0] !== T_NS_SEPARATOR) && ($tokens[$i][0] !== T_STRING)) { $dlm = false; } if (($tokens[$i - 2][0] === T_CLASS || (isset($tokens[$i - 2][1]) && $tokens[$i - 2][1] === 'phpclass')) && $tokens[$i - 1][0] === T_WHITESPACE && $tokens[$i][0] === T_STRING) { $class_name = $tokens[$i][1]; break; } } if (empty( $class_name )) { return ''; } return $namespace . '\\' . $class_name; }
php
{ "resource": "" }
q254747
FileLocator.search
test
public function search(string $path, string $ext = 'php'): array { $path = $this->ensureExt($path, $ext); $foundPaths = []; foreach ($this->getNamespaces() as $namespace) { if (is_file($namespace['path'] . $path)) { $foundPaths[] = $namespace['path'] . $path; } } // Remove any duplicates $foundPaths = array_unique($foundPaths); return $foundPaths; }
php
{ "resource": "" }
q254748
FileLocator.ensureExt
test
protected function ensureExt(string $path, string $ext): string { if ($ext) { $ext = '.' . $ext; if (substr($path, -strlen($ext)) !== $ext) { $path .= $ext; } } return $path; }
php
{ "resource": "" }
q254749
FileLocator.findQualifiedNameFromPath
test
public function findQualifiedNameFromPath(string $path) { $path = realpath($path); if (! $path) { return false; } foreach ($this->getNamespaces() as $namespace) { $namespace['path'] = realpath($namespace['path']); if (empty($namespace['path'])) { continue; } if (mb_strpos($path, $namespace['path']) === 0) { $className = '\\' . $namespace['prefix'] . '\\' . ltrim(str_replace('/', '\\', mb_substr( $path, mb_strlen($namespace['path'])) ), '\\'); // Remove the file extension (.php) $className = mb_substr($className, 0, -4); return $className; } } return false; }
php
{ "resource": "" }
q254750
FileLocator.legacyLocate
test
protected function legacyLocate(string $file, string $folder = null) { $paths = [ APPPATH, SYSTEMPATH, ]; foreach ($paths as $path) { $path .= empty($folder) ? $file : $folder . '/' . $file; if (is_file($path)) { return $path; } } return false; }
php
{ "resource": "" }
q254751
View.renderString
test
public function renderString(string $view, array $options = null, bool $saveData = null): string { $start = microtime(true); if (is_null($saveData)) { $saveData = $this->config->saveData; } extract($this->data); if (! $saveData) { $this->data = []; } ob_start(); $incoming = '?>' . $view; eval($incoming); $output = ob_get_contents(); @ob_end_clean(); $this->logPerformance($start, microtime(true), $this->excerpt($view)); return $output; }
php
{ "resource": "" }
q254752
View.excerpt
test
public function excerpt(string $string, int $length = 20): string { return (strlen($string) > $length) ? substr($string, 0, $length - 3) . '...' : $string; }
php
{ "resource": "" }
q254753
View.setData
test
public function setData(array $data = [], string $context = null): RendererInterface { if (! empty($context)) { $data = \esc($data, $context); } $this->data = array_merge($this->data, $data); return $this; }
php
{ "resource": "" }
q254754
View.setVar
test
public function setVar(string $name, $value = null, string $context = null): RendererInterface { if (! empty($context)) { $value = \esc($value, $context); } $this->data[$name] = $value; return $this; }
php
{ "resource": "" }
q254755
View.renderSection
test
public function renderSection(string $sectionName) { if (! isset($this->sections[$sectionName])) { echo ''; return; } foreach ($this->sections[$sectionName] as $contents) { echo $contents; } }
php
{ "resource": "" }
q254756
View.include
test
public function include(string $view, array $options = null, $saveData = null): string { return $this->render($view, $options, $saveData); }
php
{ "resource": "" }
q254757
View.logPerformance
test
protected function logPerformance(float $start, float $end, string $view) { if (! $this->debug) { return; } $this->performanceData[] = [ 'start' => $start, 'end' => $end, 'view' => $view, ]; }
php
{ "resource": "" }
q254758
BaseHandler.withFile
test
public function withFile(string $path) { // Clear out the old resource so that // it doesn't try to use a previous image $this->resource = null; $this->image = new Image($path, true); $this->image->getProperties(false); $this->width = $this->image->origWidth; $this->height = $this->image->origHeight; return $this; }
php
{ "resource": "" }
q254759
BaseHandler.ensureResource
test
protected function ensureResource() { if ($this->resource === null) { $path = $this->image->getPathname(); // if valid image type, make corresponding image resource switch ($this->image->imageType) { case IMAGETYPE_GIF: $this->resource = imagecreatefromgif($path); break; case IMAGETYPE_JPEG: $this->resource = imagecreatefromjpeg($path); break; case IMAGETYPE_PNG: $this->resource = imagecreatefrompng($path); break; } } }
php
{ "resource": "" }
q254760
BaseHandler.resize
test
public function resize(int $width, int $height, bool $maintainRatio = false, string $masterDim = 'auto') { // If the target width/height match the source, then we have nothing to do here. if ($this->image->origWidth === $width && $this->image->origHeight === $height) { return $this; } $this->width = $width; $this->height = $height; if ($maintainRatio) { $this->masterDim = $masterDim; $this->reproportion(); } return $this->_resize($maintainRatio); }
php
{ "resource": "" }
q254761
BaseHandler.rotate
test
public function rotate(float $angle) { // Allowed rotation values $degs = [ 90, 180, 270, ]; if ($angle === '' || ! in_array($angle, $degs)) { throw ImageException::forMissingAngle(); } // cast angle as an int, for our use $angle = (int) $angle; // Reassign the width and height if ($angle === 90 || $angle === 270) { $temp = $this->height; $this->width = $this->height; $this->height = $temp; } // Call the Handler-specific version. $this->_rotate($angle); return $this; }
php
{ "resource": "" }
q254762
BaseHandler.flip
test
public function flip(string $dir = 'vertical') { $dir = strtolower($dir); if ($dir !== 'vertical' && $dir !== 'horizontal') { throw ImageException::forInvalidDirection($dir); } return $this->_flip($dir); }
php
{ "resource": "" }
q254763
BaseHandler.text
test
public function text(string $text, array $options = []) { $options = array_merge($this->textDefaults, $options); $options['color'] = trim($options['color'], '# '); $options['shadowColor'] = trim($options['shadowColor'], '# '); $this->_text($text, $options); return $this; }
php
{ "resource": "" }
q254764
BaseHandler.reorient
test
public function reorient(bool $silent = false) { $orientation = $this->getEXIF('Orientation', $silent); switch ($orientation) { case 2: return $this->flip('horizontal'); break; case 3: return $this->rotate(180); break; case 4: return $this->rotate(180) ->flip('horizontal'); break; case 5: return $this->rotate(270) ->flip('horizontal'); break; case 6: return $this->rotate(270); break; case 7: return $this->rotate(90) ->flip('horizontal'); break; case 8: return $this->rotate(90); break; default: return $this; } }
php
{ "resource": "" }
q254765
BaseHandler.getEXIF
test
public function getEXIF(string $key = null, bool $silent = false) { if (! function_exists('exif_read_data')) { if ($silent) { return null; } } $exif = exif_read_data($this->image->getPathname()); if (! is_null($key) && is_array($exif)) { $exif = $exif[$key] ?? false; } return $exif; }
php
{ "resource": "" }
q254766
BaseHandler.fit
test
public function fit(int $width, int $height = null, string $position = 'center') { $origWidth = $this->image->origWidth; $origHeight = $this->image->origHeight; list($cropWidth, $cropHeight) = $this->calcAspectRatio($width, $height, $origWidth, $origHeight); if (is_null($height)) { $height = ceil(($width / $cropWidth) * $cropHeight); } list($x, $y) = $this->calcCropCoords($width, $height, $origWidth, $origHeight, $position); return $this->crop($cropWidth, $cropHeight, $x, $y) ->resize($width, $height); }
php
{ "resource": "" }
q254767
Serve.run
test
public function run(array $params) { // Valid PHP Version? if (phpversion() < $this->minPHPVersion) { die('Your PHP version must be ' . $this->minPHPVersion . ' or higher to run CodeIgniter. Current version: ' . phpversion()); } // Collect any user-supplied options and apply them. $php = CLI::getOption('php') ?? PHP_BINARY; $host = CLI::getOption('host') ?? 'localhost'; $port = CLI::getOption('port') ?? '8080'; // Get the party started. CLI::write('CodeIgniter development server started on http://' . $host . ':' . $port, 'green'); CLI::write('Press Control-C to stop.'); // Set the Front Controller path as Document Root. $docroot = escapeshellarg(FCPATH); // Mimic Apache's mod_rewrite functionality with user settings. $rewrite = escapeshellarg(__DIR__ . '/rewrite.php'); // Call PHP's built-in webserver, making sure to set our // base path to the public folder, and to use the rewrite file // to ensure our environment is set and it simulates basic mod_rewrite. passthru($php . ' -S ' . $host . ':' . $port . ' -t ' . $docroot . ' ' . $rewrite); }
php
{ "resource": "" }
q254768
Parser.renderString
test
public function renderString(string $template, array $options = null, bool $saveData = null): string { $start = microtime(true); if (is_null($saveData)) { $saveData = $this->config->saveData; } $output = $this->parse($template, $this->data, $options); $this->logPerformance($start, microtime(true), $this->excerpt($template)); if (! $saveData) { $this->data = []; } return $output; }
php
{ "resource": "" }
q254769
Parser.parsePair
test
protected function parsePair(string $variable, array $data, string $template): array { // Holds the replacement patterns and contents // that will be used within a preg_replace in parse() $replace = []; // Find all matches of space-flexible versions of {tag}{/tag} so we // have something to loop over. preg_match_all( '#' . $this->leftDelimiter . '\s*' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '(.+?)' . $this->leftDelimiter . '\s*' . '/' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '#s', $template, $matches, PREG_SET_ORDER ); /* * Each match looks like: * * $match[0] {tag}...{/tag} * $match[1] Contents inside the tag */ foreach ($matches as $match) { // Loop over each piece of $data, replacing // it's contents so that we know what to replace in parse() $str = ''; // holds the new contents for this tag pair. foreach ($data as $row) { // Objects that have a `toArray()` method should be // converted with that method (i.e. Entities) if (is_object($row) && method_exists($row, 'toArray')) { $row = $row->toArray(); } // Otherwise, cast as an array and it will grab public properties. else if (is_object($row)) { $row = (array)$row; } $temp = []; $pairs = []; $out = $match[1]; foreach ($row as $key => $val) { // For nested data, send us back through this method... if (is_array($val)) { $pair = $this->parsePair($key, $val, $match[1]); if (! empty($pair)) { $pairs[array_keys( $pair )[0]] = true; $temp = array_merge($temp, $pair); } continue; } else if (is_object($val)) { $val = 'Class: ' . get_class($val); } else if (is_resource($val)) { $val = 'Resource'; } $temp['#' . $this->leftDelimiter . '!?\s*' . preg_quote($key) . '\s*\|*\s*([|\w<>=\(\),:_\-\s\+]+)*\s*!?' . $this->rightDelimiter . '#s'] = $val; } // Now replace our placeholders with the new content. foreach ($temp as $pattern => $content) { $out = $this->replaceSingle($pattern, $content, $out, ! isset( $pairs[$pattern] ) ); } $str .= $out; } $replace['#' . $match[0] . '#s'] = $str; } return $replace; }
php
{ "resource": "" }
q254770
Parser.extractNoparse
test
protected function extractNoparse(string $template): string { $pattern = '/\{\s*noparse\s*\}(.*?)\{\s*\/noparse\s*\}/ms'; /* * $matches[][0] is the raw match * $matches[][1] is the contents */ if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { // Create a hash of the contents to insert in its place. $hash = md5($match[1]); $this->noparseBlocks[$hash] = $match[1]; $template = str_replace($match[0], "noparse_{$hash}", $template); } } return $template; }
php
{ "resource": "" }
q254771
Parser.insertNoparse
test
public function insertNoparse(string $template): string { foreach ($this->noparseBlocks as $hash => $replace) { $template = str_replace("noparse_{$hash}", $replace, $template); unset($this->noparseBlocks[$hash]); } return $template; }
php
{ "resource": "" }
q254772
Parser.parseConditionals
test
protected function parseConditionals(string $template): string { $pattern = '/\{\s*(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*\}/ms'; /** * For each match: * [0] = raw match `{if var}` * [1] = conditional `if` * [2] = condition `do === true` * [3] = same as [2] */ preg_match_all($pattern, $template, $matches, PREG_SET_ORDER); foreach ($matches as $match) { // Build the string to replace the `if` statement with. $condition = $match[2]; $statement = $match[1] === 'elseif' ? '<?php elseif (' . $condition . '): ?>' : '<?php if (' . $condition . '): ?>'; $template = str_replace($match[0], $statement, $template); } $template = preg_replace('/\{\s*else\s*\}/ms', '<?php else: ?>', $template); $template = preg_replace('/\{\s*endif\s*\}/ms', '<?php endif; ?>', $template); // Parse the PHP itself, or insert an error so they can debug ob_start(); extract($this->data); try { eval('?>' . $template . '<?php '); } catch (\ParseError $e) { ob_end_clean(); throw ViewException::forTagSyntaxError(str_replace(['?>', '<?php '], '', $template)); } return ob_get_clean(); }
php
{ "resource": "" }
q254773
Parser.setDelimiters
test
public function setDelimiters($leftDelimiter = '{', $rightDelimiter = '}'): RendererInterface { $this->leftDelimiter = $leftDelimiter; $this->rightDelimiter = $rightDelimiter; return $this; }
php
{ "resource": "" }
q254774
Parser.replaceSingle
test
protected function replaceSingle($pattern, $content, $template, bool $escape = false): string { // Any dollar signs in the pattern will be mis-interpreted, so slash them $pattern = addcslashes($pattern, '$'); // Replace the content in the template $template = preg_replace_callback($pattern, function ($matches) use ($content, $escape) { // Check for {! !} syntax to not-escape this one. if (strpos($matches[0], '{!') === 0 && substr($matches[0], -2) === '!}') { $escape = false; } return $this->prepareReplacement($matches, $content, $escape); }, $template); return $template; }
php
{ "resource": "" }
q254775
Parser.shouldAddEscaping
test
public function shouldAddEscaping(string $key) { $escape = false; $key = trim(str_replace(['{', '}'], '', $key)); // If the key has a context stored (from setData) // we need to respect that. if (array_key_exists($key, $this->dataContexts)) { if ($this->dataContexts[$key] !== 'raw') { return $this->dataContexts[$key]; } } // No pipes, then we know we need to escape elseif (strpos($key, '|') === false) { $escape = 'html'; } // If there's a `noescape` then we're definitely false. elseif (strpos($key, 'noescape') !== false) { $escape = false; } // If no `esc` filter is found, then we'll need to add one. elseif (! preg_match('/\s+esc/', $key)) { $escape = 'html'; } return $escape; }
php
{ "resource": "" }
q254776
Parser.addPlugin
test
public function addPlugin(string $alias, callable $callback, bool $isPair = false) { $this->plugins[$alias] = $isPair ? [$callback] : $callback; return $this; }
php
{ "resource": "" }
q254777
GDHandler.createImage
test
protected function createImage(string $path = '', string $imageType = '') { if ($this->resource !== null) { return $this->resource; } if ($path === '') { $path = $this->image->getPathname(); } if ($imageType === '') { $imageType = $this->image->imageType; } switch ($imageType) { case IMAGETYPE_GIF: if (! function_exists('imagecreatefromgif')) { throw ImageException::forInvalidImageCreate(lang('images.gifNotSupported')); } return imagecreatefromgif($path); case IMAGETYPE_JPEG: if (! function_exists('imagecreatefromjpeg')) { throw ImageException::forInvalidImageCreate(lang('images.jpgNotSupported')); } return imagecreatefromjpeg($path); case IMAGETYPE_PNG: if (! function_exists('imagecreatefrompng')) { throw ImageException::forInvalidImageCreate(lang('images.pngNotSupported')); } return imagecreatefrompng($path); default: throw ImageException::forInvalidImageCreate('Ima'); } }
php
{ "resource": "" }
q254778
Message.getHeader
test
public function getHeader(string $name) { $orig_name = $this->getHeaderName($name); if (! isset($this->headers[$orig_name])) { return null; } return $this->headers[$orig_name]; }
php
{ "resource": "" }
q254779
Message.hasHeader
test
public function hasHeader(string $name): bool { $orig_name = $this->getHeaderName($name); return isset($this->headers[$orig_name]); }
php
{ "resource": "" }
q254780
Message.setHeader
test
public function setHeader(string $name, $value) { if (! isset($this->headers[$name])) { $this->headers[$name] = new Header($name, $value); $this->headerMap[strtolower($name)] = $name; return $this; } if (! is_array($this->headers[$name])) { $this->headers[$name] = [$this->headers[$name]]; } if (isset($this->headers[$name])) { $this->headers[$name] = new Header($name, $value); } return $this; }
php
{ "resource": "" }
q254781
Message.removeHeader
test
public function removeHeader(string $name) { $orig_name = $this->getHeaderName($name); unset($this->headers[$orig_name]); unset($this->headerMap[strtolower($name)]); return $this; }
php
{ "resource": "" }
q254782
Message.setProtocolVersion
test
public function setProtocolVersion(string $version) { if (! is_numeric($version)) { $version = substr($version, strpos($version, '/') + 1); } if (! in_array($version, $this->validProtocolVersions)) { throw HTTPException::forInvalidHTTPProtocol(implode(', ', $this->validProtocolVersions)); } $this->protocolVersion = $version; return $this; }
php
{ "resource": "" }
q254783
Message.getHeaderName
test
protected function getHeaderName(string $name): string { $lower_name = strtolower($name); return $this->headerMap[$lower_name] ?? $name; }
php
{ "resource": "" }
q254784
FileHandler.configureSessionIDRegex
test
protected function configureSessionIDRegex() { $bitsPerCharacter = (int)ini_get('session.sid_bits_per_character'); $SIDLength = (int)ini_get('session.sid_length'); if (($bits = $SIDLength * $bitsPerCharacter) < 160) { // Add as many more characters as necessary to reach at least 160 bits $SIDLength += (int)ceil((160 % $bits) / $bitsPerCharacter); ini_set('session.sid_length', $SIDLength); } // Yes, 4,5,6 are the only known possible values as of 2016-10-27 switch ($bitsPerCharacter) { case 4: $this->sessionIDRegex = '[0-9a-f]'; break; case 5: $this->sessionIDRegex = '[0-9a-v]'; break; case 6: $this->sessionIDRegex = '[0-9a-zA-Z,-]'; break; } $this->sessionIDRegex .= '{' . $SIDLength . '}'; }
php
{ "resource": "" }
q254785
Response.getReason
test
public function getReason(): string { if (empty($this->reason)) { return ! empty($this->statusCode) ? static::$statusCodes[$this->statusCode] : ''; } return $this->reason; }
php
{ "resource": "" }
q254786
Response.setLink
test
public function setLink(PagerInterface $pager) { $links = ''; if ($previous = $pager->getPreviousPageURI()) { $links .= '<' . $pager->getPageURI($pager->getFirstPage()) . '>; rel="first",'; $links .= '<' . $previous . '>; rel="prev"'; } if (($next = $pager->getNextPageURI()) && $previous) { $links .= ','; } if ($next) { $links .= '<' . $next . '>; rel="next",'; $links .= '<' . $pager->getPageURI($pager->getLastPage()) . '>; rel="last"'; } $this->setHeader('Link', $links); return $this; }
php
{ "resource": "" }
q254787
Response.setContentType
test
public function setContentType(string $mime, string $charset = 'UTF-8') { // add charset attribute if not already there and provided as parm if ((strpos($mime, 'charset=') < 1) && ! empty($charset)) { $mime .= '; charset=' . $charset; } $this->removeHeader('Content-Type'); // replace existing content type $this->setHeader('Content-Type', $mime); return $this; }
php
{ "resource": "" }
q254788
Response.getJSON
test
public function getJSON() { $body = $this->body; if ($this->bodyFormat !== 'json') { /** * @var Format $config */ $config = config(Format::class); $formatter = $config->getFormatter('application/json'); $body = $formatter->format($body); } return $body ?: null; }
php
{ "resource": "" }
q254789
Response.getXML
test
public function getXML() { $body = $this->body; if ($this->bodyFormat !== 'xml') { /** * @var Format $config */ $config = config(Format::class); $formatter = $config->getFormatter('application/xml'); $body = $formatter->format($body); } return $body; }
php
{ "resource": "" }
q254790
Response.formatBody
test
protected function formatBody($body, string $format) { $mime = "application/{$format}"; $this->setContentType($mime); $this->bodyFormat = $format; // Nothing much to do for a string... if (! is_string($body)) { /** * @var Format $config */ $config = config(Format::class); $formatter = $config->getFormatter($mime); $body = $formatter->format($body); } return $body; }
php
{ "resource": "" }
q254791
Response.setCache
test
public function setCache(array $options = []) { if (empty($options)) { return $this; } $this->removeHeader('Cache-Control'); $this->removeHeader('ETag'); // ETag if (isset($options['etag'])) { $this->setHeader('ETag', $options['etag']); unset($options['etag']); } // Last Modified if (isset($options['last-modified'])) { $this->setLastModified($options['last-modified']); unset($options['last-modified']); } $this->setHeader('Cache-control', $options); return $this; }
php
{ "resource": "" }
q254792
Response.send
test
public function send() { // If we're enforcing a Content Security Policy, // we need to give it a chance to build out it's headers. if ($this->CSPEnabled === true) { $this->CSP->finalize($this); } else { $this->body = str_replace(['{csp-style-nonce}', '{csp-script-nonce}'], '', $this->body); } $this->sendHeaders(); $this->sendBody(); $this->sendCookies(); return $this; }
php
{ "resource": "" }
q254793
Response.sendHeaders
test
public function sendHeaders() { // Have the headers already been sent? if ($this->pretend || headers_sent()) { return $this; } // Per spec, MUST be sent with each request, if possible. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html if (! isset($this->headers['Date'])) { $this->setDate(\DateTime::createFromFormat('U', time())); } // HTTP Status header(sprintf('HTTP/%s %s %s', $this->protocolVersion, $this->statusCode, $this->reason), true, $this->statusCode); // Send all of our headers foreach ($this->getHeaders() as $name => $values) { header($name . ': ' . $this->getHeaderLine($name), false, $this->statusCode); } return $this; }
php
{ "resource": "" }
q254794
Response.setCookie
test
public function setCookie( $name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = false, $httponly = false ) { if (is_array($name)) { // always leave 'name' in last place, as the loop will break otherwise, due to $$item foreach (['value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name'] as $item) { if (isset($name[$item])) { $$item = $name[$item]; } } } if ($prefix === '' && $this->cookiePrefix !== '') { $prefix = $this->cookiePrefix; } if ($domain === '' && $this->cookieDomain !== '') { $domain = $this->cookieDomain; } if ($path === '/' && $this->cookiePath !== '/') { $path = $this->cookiePath; } if ($secure === false && $this->cookieSecure === true) { $secure = $this->cookieSecure; } if ($httponly === false && $this->cookieHTTPOnly !== false) { $httponly = $this->cookieHTTPOnly; } if (! is_numeric($expire)) { $expire = time() - 86500; } else { $expire = ($expire > 0) ? time() + $expire : 0; } $this->cookies[] = [ 'name' => $prefix . $name, 'value' => $value, 'expires' => $expire, 'path' => $path, 'domain' => $domain, 'secure' => $secure, 'httponly' => $httponly, ]; return $this; }
php
{ "resource": "" }
q254795
Response.hasCookie
test
public function hasCookie(string $name, string $value = null, string $prefix = ''): bool { if ($prefix === '' && $this->cookiePrefix !== '') { $prefix = $this->cookiePrefix; } $name = $prefix . $name; foreach ($this->cookies as $cookie) { if ($cookie['name'] !== $name) { continue; } if ($value === null) { return true; } return $cookie['value'] === $value; } return false; }
php
{ "resource": "" }
q254796
Response.getCookie
test
public function getCookie(string $name = null, string $prefix = '') { // if no name given, return them all if (empty($name)) { return $this->cookies; } if ($prefix === '' && $this->cookiePrefix !== '') { $prefix = $this->cookiePrefix; } $name = $prefix . $name; foreach ($this->cookies as $cookie) { if ($cookie['name'] === $name) { return $cookie; } } return null; }
php
{ "resource": "" }
q254797
Response.deleteCookie
test
public function deleteCookie(string $name = '', string $domain = '', string $path = '/', string $prefix = '') { if (empty($name)) { return $this; } if ($prefix === '' && $this->cookiePrefix !== '') { $prefix = $this->cookiePrefix; } $name = $prefix . $name; foreach ($this->cookies as &$cookie) { if ($cookie['name'] === $name) { if (! empty($domain) && $cookie['domain'] !== $domain) { continue; } if (! empty($path) && $cookie['path'] !== $path) { continue; } $cookie['value'] = ''; $cookie['expires'] = ''; break; } } return $this; }
php
{ "resource": "" }
q254798
Response.sendCookies
test
protected function sendCookies() { if ($this->pretend) { return; } foreach ($this->cookies as $params) { // PHP cannot unpack array with string keys $params = array_values($params); setcookie(...$params); } }
php
{ "resource": "" }
q254799
Response.download
test
public function download(string $filename = '', $data = '', bool $setMime = false) { if ($filename === '' || $data === '') { return null; } $filepath = ''; if ($data === null) { $filepath = $filename; $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename)); $filename = end($filename); } $response = new DownloadResponse($filename, $setMime); if ($filepath !== '') { $response->setFilePath($filepath); } elseif ($data !== null) { $response->setBinary($data); } return $response; }
php
{ "resource": "" }