_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q250000
DropzonerController.postUpload
validation
public function postUpload(Request $request) { $input = $request->all(); $response = $this->uploadRepository->upload($input); return $response; }
php
{ "resource": "" }
q250001
SymfonyConsoleLog.setLinePrefixMap
validation
public function setLinePrefixMap(array $prefixMap) { foreach ($prefixMap as $status => $prefix) { $this->setLinePrefix($status, $prefix); } }
php
{ "resource": "" }
q250002
SymfonyConsoleLog.writeLogLine
validation
public function writeLogLine(Tick $tick) { // Line segments $lineSegs = array(); // 1st Segment is a star switch ($tick->getStatus()) { case Tick::SUCCESS: $lineSegs[] = sprintf("<fg=green>%s</fg=green>", $this->linePrefixMap[Tick::SUCCESS]); break; case Tick::FAIL: $lineSegs[] = sprintf("<fg=red>%s</fg=red>", $this->linePrefixMap[Tick::FAIL]); break; case Tick::SKIP: default: $lineSegs[] = $this->linePrefixMap[Tick::SKIP]; } // Item Progress $lineSegs[] = sprintf( "[%s%s]", $tick->getReport()->getNumItemsProcessed(), $tick->getReport()->getTotalItemCount() != Tracker::UNKNOWN ? "/" . $tick->getReport()->getTotalItemCount() : '' ); // If verbose, add walltime and item counts if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $lineSegs[] = $this->formatSeconds($tick->getReport()->getTimeElapsed()); $lineSegs[] = sprintf( '(<fg=green>%s</fg=green>/%s/<fg=red>%s</fg=red>)', $tick->getReport()->getNumItemsSuccess(), $tick->getReport()->getNumItemsSkip(), $tick->getReport()->getNumItemsFail() ); } // If very verbose, add memory usage if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $lineSegs[] = sprintf("{%s/%s}", $this->bytesToHuman($tick->getReport()->getMemUsage()), $this->bytesToHuman($tick->getReport()->getMemPeakUsage()) ); } // Add message $lineSegs[] = $tick->getMessage() ?: sprintf( "Processing item %s", number_format($tick->getReport()->getNumItemsProcessed(), 0) ); // Output it! $this->output->writeln(implode(' ', $lineSegs)); }
php
{ "resource": "" }
q250003
UploadRepository.upload
validation
public function upload($input) { $validator = \Validator::make($input, config('dropzoner.validator'), config('dropzoner.validator-messages')); if ($validator->fails()) { return response()->json([ 'error' => true, 'message' => $validator->messages()->first(), 'code' => 400 ], 400); } $photo = $input['file']; $original_name = $photo->getClientOriginalName(); $extension = $photo->getClientOriginalExtension(); $original_name_without_extension = substr($original_name, 0, strlen($original_name) - strlen($extension) - 1); $filename = $this->sanitize($original_name_without_extension); $allowed_filename = $this->createUniqueFilename( $filename ); $filename_with_extension = $allowed_filename .'.' . $extension; $manager = new ImageManager(); $image = $manager->make( $photo )->save(config('dropzoner.upload-path') . $filename_with_extension ); if( !$image ) { return response()->json([ 'error' => true, 'message' => 'Server error while uploading', 'code' => 500 ], 500); } //Fire ImageWasUploaded Event event(new ImageWasUploaded($original_name, $filename_with_extension)); return response()->json([ 'error' => false, 'code' => 200, 'filename' => $filename_with_extension ], 200); }
php
{ "resource": "" }
q250004
UploadRepository.delete
validation
public function delete($server_filename) { $upload_path = config('dropzoner.upload-path'); $full_path = $upload_path . $server_filename; if (\File::exists($full_path)) { \File::delete($full_path); } event(new ImageWasDeleted($server_filename)); return response()->json([ 'error' => false, 'code' => 200 ], 200); }
php
{ "resource": "" }
q250005
UploadRepository.createUniqueFilename
validation
private function createUniqueFilename( $filename ) { $full_size_dir = config('dropzoner.upload-path'); $full_image_path = $full_size_dir . $filename . '.jpg'; if (\File::exists($full_image_path)) { // Generate token for image $image_token = substr(sha1(mt_rand()), 0, 5); return $filename . '-' . $image_token; } return $filename; }
php
{ "resource": "" }
q250006
VariableUtils.getNextAvailableVariableName
validation
public static function getNextAvailableVariableName(string $variable, array $usedVariables): string { $variable = self::toVariableName($variable); while (true) { // check that the name is not reserved if (!in_array($variable, $usedVariables, true)) { break; } $numbers = ''; while (true) { $lastCharacter = substr($variable, strlen($variable) - 1); if ($lastCharacter >= '0' && $lastCharacter <= '9') { $numbers = $lastCharacter.$numbers; $variable = substr($variable, 0, strlen($variable) - 1); } else { break; } } if ($numbers === '') { $numbers = 0; } else { $numbers = (int) $numbers; } ++$numbers; $variable = $variable.$numbers; } return $variable; }
php
{ "resource": "" }
q250007
Application.loadConfigFiles
validation
protected function loadConfigFiles() { try { if (file_exists($this->cachePath('config.php'))) { $this->config = require $this->cachePath('config.php'); } else { $dotenv = new \Dotenv\Dotenv($this->root); $dotenv->load(); foreach (glob($this->root . '/config/*.php') as $file) { $keyName = strtolower(str_replace( [$this->root . '/config/', '.php'], '', $file )); $this->config[$keyName] = require $file; } } } catch (Exception $e) { die(printf( "Configuration information could not be retrieved properly.\nError Message: %s", $e->getMessage() )); } }
php
{ "resource": "" }
q250008
Application.registerBaseBindings
validation
protected function registerBaseBindings() { static::setInstance($this); $this->instance('app', $this); $this->instance(Container::class, $this); $this->singleton('config', function() { return new \Nur\Config\Config($this->config); }); $this->singleton('files', function () { return new Filesystem; }); $this->instance(PackageManifest::class, new PackageManifest( new Filesystem, $this->basePath(), $this->getCachedPackagesPath() )); }
php
{ "resource": "" }
q250009
Application.registerApplicationAliases
validation
protected function registerApplicationAliases() { foreach ($this->config['services']['aliases'] as $key => $alias) { $this->alias($key, $alias); if (! class_exists($key)) { class_alias($alias, $key); } } }
php
{ "resource": "" }
q250010
Application.bootstrap
validation
public function bootstrap() { $this->hasBeenBootstrapped = true; $this['events']->dispatch('bootstrapping', [$this]); $this->boot(); $this['events']->dispatch('bootstrapped', [$this]); }
php
{ "resource": "" }
q250011
Application.bindPathsInContainer
validation
protected function bindPathsInContainer() { $this->instance('path', $this->path()); $this->instance('path.base', $this->basePath()); $this->instance('path.lang', $this->langPath()); $this->instance('path.config', $this->configPath()); $this->instance('path.storage', $this->storagePath()); $this->instance('path.database', $this->databasePath()); $this->instance('path.cache', $this->cachePath()); $this->instance('path.public', $this->publicPath()); }
php
{ "resource": "" }
q250012
Application.registerConfiguredProviders
validation
public function registerConfiguredProviders() { $providers = Collection::make($this->config['app.providers']) ->partition(function ($provider) { return Str::startsWith($provider, 'Nur\\'); }); $providers->splice(1, 0, [$this->make(PackageManifest::class)->providers()]); (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath())) ->load($providers->collapse()->toArray()); }
php
{ "resource": "" }
q250013
Application.markAsRegistered
validation
protected function markAsRegistered(ServiceProvider $provider) { $this->serviceProviders[] = $provider; $this->loadedProviders[get_class($provider)] = true; }
php
{ "resource": "" }
q250014
Application.registerCoreContainerAliases
validation
public function registerCoreContainerAliases() { // Prepare Facades Facade::clearResolvedInstances(); Facade::setApplication($this); foreach ($this->registerCoreAliases as $key => $alias) { $this->alias($key, $alias); if (! class_exists($key)) { class_alias($alias, $key); } } }
php
{ "resource": "" }
q250015
UriGenerator.base
validation
public function base($data = null, $secure = false) { $data = (! is_null($data)) ? $this->url . $data : $this->url . '/'; return $this->getUrl($data, $secure); }
php
{ "resource": "" }
q250016
UriGenerator.admin
validation
public function admin($data = null, $secure = false) { $data = (! is_null($data)) ? $this->url . '/' . ADMIN_FOLDER . '/' . $data : $this->url . '/' . ADMIN_FOLDER . '/'; return $this->getUrl($data, $secure); }
php
{ "resource": "" }
q250017
UriGenerator.route
validation
public function route($name, array $params = null, $secure = false) { $routes = file_exists(cache_path('routes.php')) ? require cache_path('routes.php') : app('route')->getRoutes(); $found = false; foreach ($routes as $key => $value) { if ($value['alias'] == $name) { $found = true; break; } } if ($found) { if (strstr($routes[$key]['route'], '{')) { $segment = explode('/', $routes[$key]['route']); $i = 0; foreach ($segment as $key => $value) { if (strstr($value, '{')) { $segment[$key] = $params[$i]; $i++; } } $newUrl = implode('/', $segment); } else { $newUrl = $routes[$key]['route']; } $data = str_replace($this->base, '', $this->url) . '/' . $newUrl; return $this->getUrl($data, $secure); } return $this->getUrl($this->url, $secure); }
php
{ "resource": "" }
q250018
UriGenerator.assets
validation
public function assets($data = null, $secure = false) { $data = (! is_null($data)) ? $this->url . '/' . ASSETS_FOLDER . '/' . $data : $this->url . '/' . ASSETS_FOLDER . '/'; return $this->getUrl($data, $secure); }
php
{ "resource": "" }
q250019
UriGenerator.redirect
validation
public function redirect($data = null, int $statusCode = 301, $secure = false) { if (substr($data, 0, 4) === 'http' || substr($data, 0, 5) === 'https') { header('Location: ' . $data, true, $statusCode); } else { $data = (! is_null($data)) ? $this->url . '/' . $data : $this->url; header('Location: ' . $this->getUrl($data, $secure), true, $statusCode); } die(); }
php
{ "resource": "" }
q250020
UriGenerator.segment
validation
public function segment($num = null) { if (is_null(http()->server('REQUEST_URI')) || is_null(http()->server('SCRIPT_NAME'))) { return null; } if (! is_null($num)) { $uri = $this->replace(str_replace($this->base, '', http()->server('REQUEST_URI'))); $uriA = explode('/', $uri); return (isset($uriA[$num]) ? reset(explode('?', $uriA[$num])) : null); } return null; }
php
{ "resource": "" }
q250021
UriGenerator.scheme
validation
protected function scheme() { if ($this->cachedHttps === true) { $this->https = true; } return "http" . ($this->https === true ? 's' : '') . "://"; }
php
{ "resource": "" }
q250022
Cache.save
validation
public function save($content = null, $time = 30) { $fileName = md5($this->prefix . http()->server('REQUEST_URI')) . $this->extension; $this->file = cache_path('html' . DIRECTORY_SEPARATOR . $fileName); $this->start($time); return $this->finish($content); }
php
{ "resource": "" }
q250023
Cache.finish
validation
protected function finish($output = null) { if (! is_null($output)) { $file = fopen($this->file, 'w+'); fwrite($file, $output); fclose($file); return $output; } return false; }
php
{ "resource": "" }
q250024
ServiceProvider.publishes
validation
protected function publishes(array $paths, $group = null) { $this->ensurePublishArrayInitialized($class = static::class); static::$publishes[$class] = array_merge(static::$publishes[$class], $paths); if ($group) { $this->addPublishGroup($group, $paths); } }
php
{ "resource": "" }
q250025
Log.log
validation
protected function log($level, $message) { if (is_array($message) || is_object($message)) { // $message = json_encode($message); $message = print_r($message, true); } $text = '[' . date($this->timeFormat, time()) . '] - [' . strtoupper($level) . '] - [' . http()->getClientIP() . '] --> ' . $message; $this->save($text); }
php
{ "resource": "" }
q250026
Request.fullUrlWithQuery
validation
public function fullUrlWithQuery(array $query) { $question = $this->getBaseUrl() . $this->getPathInfo() == '/' ? '/?' : '?'; return count($this->query()) > 0 ? $this->url() . $question . http_build_query(array_merge($this->query(), $query)) : $this->fullUrl() . $question . http_build_query($query); }
php
{ "resource": "" }
q250027
Command.generate
validation
public function generate() { foreach ($this->commandList as $key => $value) { $this->app->add(new $value); } foreach ($this->migrationCommands as $command) { $newCommand = new $command; $newCommand->setName("migration:" . $newCommand->getName()); $this->app->add($newCommand); } }
php
{ "resource": "" }
q250028
HtmlProvider.script
validation
public function script($url, $attributes = [], $secure = null) { $attributes['src'] = $this->uri->assets($url, $secure); return $this->toHtmlString('<script' . $this->attributes($attributes) . '></script>' . PHP_EOL); }
php
{ "resource": "" }
q250029
HtmlProvider.style
validation
public function style($url, $attributes = [], $secure = null) { $defaults = ['media' => 'all', 'type' => 'text/css', 'rel' => 'stylesheet']; $attributes = array_merge($attributes, $defaults); $attributes['href'] = $this->uri->assets($url, $secure); return $this->toHtmlString('<link' . $this->attributes($attributes) . '>' . PHP_EOL); }
php
{ "resource": "" }
q250030
HtmlProvider.image
validation
public function image($url, $alt = null, $attributes = [], $secure = null) { $attributes['alt'] = $alt; return $this->toHtmlString('<img src="' . $this->uri->assets($url, $secure) . '"' . $this->attributes($attributes) . '>'); }
php
{ "resource": "" }
q250031
HtmlProvider.linkAsset
validation
public function linkAsset($url, $title = null, $attributes = [], $secure = null) { $url = $this->uri->assets($url, $secure); return $this->link($url, $title ?: $url, $attributes, $secure); }
php
{ "resource": "" }
q250032
HtmlProvider.meta
validation
public function meta($name, $content, array $attributes = []) { $defaults = compact('name', 'content'); $attributes = array_merge($defaults, $attributes); return $this->toHtmlString('<meta' . $this->attributes($attributes) . '>' . PHP_EOL); }
php
{ "resource": "" }
q250033
HtmlProvider.tag
validation
public function tag($tag, $content, array $attributes = []) { $content = is_array($content) ? implode(PHP_EOL, $content) : $content; return $this->toHtmlString('<' . $tag . $this->attributes($attributes) . '>' . PHP_EOL . $this->toHtmlString($content) . PHP_EOL . '</' . $tag . '>' . PHP_EOL); }
php
{ "resource": "" }
q250034
KeygenCommand.setKeyInEnvironmentFile
validation
protected function setKeyInEnvironmentFile($key, $input, $output) { $currentKey = config('app.key'); $helper = $this->getHelper('question'); $question = new ConfirmationQuestion('Application key will re-generate. Are you sure?: ', false); if (strlen($currentKey) !== 0 && (! $helper->ask($input, $output, $question))) { return false; } $this->writeNewEnvironmentFileWith($key); return true; }
php
{ "resource": "" }
q250035
KeygenCommand.writeNewEnvironmentFileWith
validation
protected function writeNewEnvironmentFileWith($key) { file_put_contents(base_path('.env'), preg_replace( $this->keyReplacementPattern(), 'APP_KEY='.$key, file_get_contents(base_path('.env')) )); }
php
{ "resource": "" }
q250036
Load.view
validation
public function view($name, array $data = []) { $file = app_path('Views' . DIRECTORY_SEPARATOR . $name . '.php'); if (file_exists($file)) { extract($data); require $file; return ob_get_clean(); } throw new ExceptionHandler('Oppss! File not found.', 'View::' . $name . ' not found.'); }
php
{ "resource": "" }
q250037
Load.helper
validation
public function helper($name, $directory = 'Helpers') { $file = app_path($directory . DIRECTORY_SEPARATOR . $name . '.php'); if (file_exists($file)) { return require $file; } throw new ExceptionHandler('Oppss! File not found.', 'Helper::' . $name . ' not found.'); }
php
{ "resource": "" }
q250038
Event.trigger
validation
public function trigger($event, array $params = [], $method = 'handle') { $listeners = config('services.listeners'); foreach ($listeners[$event] as $listener) { if (! class_exists($listener)) { throw new ExceptionHandler('Event class not found.', $listener); } if (! method_exists($listener, $method)) { throw new ExceptionHandler('Method not found in Event class.', $listener . '::' . $method . '()'); } call_user_func_array([new $listener, $method], $params); } }
php
{ "resource": "" }
q250039
Blade.registerDirectives
validation
public function registerDirectives(BladeCompiler $blade) { $keywords = [ "namespace", "use", ]; foreach ($keywords as $keyword) { $blade->directive($keyword, function ($parameter) use ($keyword) { $parameter = trim($parameter, "()"); return "<?php {$keyword} {$parameter} ?>"; }); } $assetify = function ($file, $type) { $file = trim($file, "()"); if (in_array(substr($file, 0, 1), ["'", '"'], true)) { $file = trim($file, "'\""); } else { return "{{ {$file} }}"; } if (substr($file, 0, 1) !== "/") { $file = "/{$type}/{$file}"; } if (substr($file, (strlen($type) + 1) * -1) !== ".{$type}") { $file .= ".{$type}"; } return $file; }; $blade->directive("css", function ($parameter) use ($assetify) { $file = $assetify($parameter, "css"); return '<link rel="stylesheet" type="text/css" href="' . $file . '"/>'; }); $blade->directive("js", function ($parameter) use ($assetify) { $file = $assetify($parameter, "js"); return '<script type="text/javascript" src="' . $file . '"></script>'; }); }
php
{ "resource": "" }
q250040
ArgonHash.make
validation
public function make($value, array $options = []) { $hash = password_hash($value, PASSWORD_ARGON2I, [ 'memory_cost' => $this->memory($options), 'time_cost' => $this->time($options), 'threads' => $this->threads($options), ]); if ($hash === false) { throw new RuntimeException('Argon2 hashing not supported.'); } return $hash; }
php
{ "resource": "" }
q250041
ArgonHash.needsRehash
validation
public function needsRehash($hashedValue, array $options = []) { return password_needs_rehash($hashedValue, PASSWORD_ARGON2I, [ 'memory_cost' => $this->memory($options), 'time_cost' => $this->time($options), 'threads' => $this->threads($options), ]); }
php
{ "resource": "" }
q250042
Session.set
validation
public function set($key, $value) { if (is_array($key)) { foreach ($key as $k => $v) { $_SESSION[$k] = $v; } } else { $_SESSION[$key] = $value; } return; }
php
{ "resource": "" }
q250043
Session.get
validation
public function get($key = null) { return (is_null($key) ? $_SESSION : ($this->has($key) ? $_SESSION[$key] : null)); }
php
{ "resource": "" }
q250044
Session.setFlash
validation
public function setFlash($key, $value, $redirect = null) { $this->set('_nur_flash', [$key => $value]); if (! is_null($redirect)) { uri()->redirect($redirect); } return false; }
php
{ "resource": "" }
q250045
Session.getFlash
validation
public function getFlash($key = null) { if (! is_null($key)) { $value = null; if ($this->hasFlash($key)) { $value = $this->get('_nur_flash')[$key]; unset($_SESSION['_nur_flash'][$key]); } return $value; } return $key; }
php
{ "resource": "" }
q250046
Hash.driver
validation
protected function driver() { if ($this->getDefaultDriver() === 'argon') { return $this->createArgonDriver(); } elseif ($this->getDefaultDriver() === 'argon2id') { return $this->createArgon2IdDriver(); } return $this->createBcryptDriver(); }
php
{ "resource": "" }
q250047
AliasLoader.ensureFacadeExists
validation
protected function ensureFacadeExists($alias) { if (file_exists($path = storage_path('cache/facade-'.sha1($alias).'.php'))) { return $path; } file_put_contents($path, $this->formatFacadeStub( $alias, file_get_contents(__DIR__.'/stubs/facade.stub') )); return $path; }
php
{ "resource": "" }
q250048
Cookie.set
validation
public function set($key, $value, $time = 0) { if (is_array($key)) { foreach ($key as $k => $v) { setcookie($k, $v, ($time == 0 ? 0 : time() + $time), '/'); $_COOKIE[$k] = $v; } } else { setcookie($key, $value, ($time == 0 ? 0 : time() + $time), '/'); $_COOKIE[$key] = $value; } return; }
php
{ "resource": "" }
q250049
Cookie.get
validation
public function get($key = null) { return (is_null($key) ? $_COOKIE : ($this->has($key) ? $_COOKIE[$key] : null)); }
php
{ "resource": "" }
q250050
Cookie.delete
validation
public function delete($key) { if ($this->has($key)) { setcookie($key, null, -1, '/'); unset($_COOKIE[$key]); } return; }
php
{ "resource": "" }
q250051
Cookie.destroy
validation
public function destroy() { foreach ($_COOKIE as $key => $value) { setcookie($key, null, -1, '/'); unset($_COOKIE[$key]); } return; }
php
{ "resource": "" }
q250052
Response.header
validation
public function header($key, $value) { if (is_array($key) && !empty($key)) { foreach ($key as $k => $v) { $this->headers->set($k, $v); } } elseif (is_string($key) && !empty($key)) { $this->headers->set($key, $value); } return $this; }
php
{ "resource": "" }
q250053
Response.view
validation
public function view($view, array $data = []) { if (function_exists('app')) { $this->setContent( app('load')->view($view, $data) ); return $this; } return; }
php
{ "resource": "" }
q250054
Response.blade
validation
public function blade($view, array $data = [], array $mergeData = []) { if (function_exists('app')) { $this->setContent( app('view')->make($view, $data, $mergeData)->render() ); return $this; } return; }
php
{ "resource": "" }
q250055
Http.post
validation
public function post($key = null, $filter = false) { if (is_null($key)) { return $_POST; } $value = (isset($_POST[$key]) ? $_POST[$key] : null); return $this->filter($value, $filter); }
php
{ "resource": "" }
q250056
Http.get
validation
public function get($key = null, $filter = false) { if (is_null($key)) { return $_GET; } $value = (isset($_GET[$key]) ? $_GET[$key] : null); return $this->filter($value, $filter); }
php
{ "resource": "" }
q250057
Http.put
validation
public function put($key = null, $filter = true) { parse_str(file_get_contents("php://input"), $_PUT); if ($key == null) { return $_PUT; } return $this->filter($_PUT[$key], $filter); }
php
{ "resource": "" }
q250058
Http.delete
validation
public function delete($key = null, $filter = true) { parse_str(file_get_contents("php://input"), $_DELETE); if ($key == null) { return $_DELETE; } return $this->filter($_DELETE[$key], $filter); }
php
{ "resource": "" }
q250059
Http.files
validation
public function files($key = null, $name = null) { if (is_null($key)) { return $_FILES; } if (isset($_FILES[$key])) { if (! is_null($name)) { return $_FILES[$key][$name]; } return $_FILES[$key]; } return false; }
php
{ "resource": "" }
q250060
Http.server
validation
public function server($key = null) { if (is_null($key)) { return $_SERVER; } $key = strtoupper($key); return (isset($_SERVER[$key]) ? $_SERVER[$key] : null); }
php
{ "resource": "" }
q250061
Http.getClientIP
validation
public function getClientIP() { $ip = null; $client = $this->server('HTTP_CLIENT_IP'); $forward = $this->server('HTTP_X_FORWARDED_FOR'); $remote = $this->server('REMOTE_ADDR'); if (filter_var($client, FILTER_VALIDATE_IP)) { $ip = $client; } elseif (filter_var($forward, FILTER_VALIDATE_IP)) { $ip = $forward; } else { $ip = $remote; } return $ip; }
php
{ "resource": "" }
q250062
Http.filter
validation
public function filter($data = null, $filter = false) { if (is_null($data)) { return null; } if (is_array($data)) { return array_map(function ($value) use ($filter) { return $this->filter($value, $filter); }, $data); } return ($filter == true ? $this->xssClean($data) : trim($data)); }
php
{ "resource": "" }
q250063
Validation.rules
validation
public function rules(Array $rules) { foreach ($rules as $key => $value) { $this->rule( $key, $value['label'], $value['rules'], isset($value['text']) && ! empty($value['text']) ? $value['text'] : [] ); } }
php
{ "resource": "" }
q250064
Validation.rule
validation
public function rule($field, $label, $rules, array $text = []) { $this->labels[$field] = $label; $this->rules[$field] = $rules; $this->texts[$field] = (! empty($text) ? $text : null); }
php
{ "resource": "" }
q250065
Validation.errorMessage
validation
protected function errorMessage($filter, $field, $params = null) { $text = (isset($this->texts[$field][$filter]) && ! is_null($this->texts[$field][$filter]) ? $this->texts[$field][$filter] : $this->msg); $text = str_replace([':label:', ':value:'], '%s', $text); if (! isset($this->data[$field])) { $this->errors[] = sprintf($text, $this->labels[$field], $params); } elseif (! is_null($params)) { if ($filter == 'matches') { if ($this->matches($this->data[$field], $this->data[$params]) === false) { $this->errors[] = sprintf($text, $this->labels[$field], $params); } } else { if ($this->$filter($this->data[$field], $params) === false) { $this->errors[] = sprintf($text, $this->labels[$field], $params); } } } else { if ($this->$filter($this->data[$field]) === false) { $this->errors[] = sprintf($text, $this->labels[$field], $params); } } }
php
{ "resource": "" }
q250066
Validation.valid_cc
validation
protected function valid_cc($data) { $number = preg_replace('/\D/', '', $data); if (function_exists('mb_strlen')) { $number_length = mb_strlen($number); } else { $number_length = strlen($number); } $parity = $number_length % 2; $total = 0; for ($i = 0; $i < $number_length; $i++) { $digit = $number[$i]; if ($i % 2 == $parity) { $digit *= 2; if ($digit > 9) { $digit -= 9; } } $total += $digit; } return ($total % 10 == 0) ? true : false; }
php
{ "resource": "" }
q250067
AbstractCommand.migrationToClassName
validation
protected function migrationToClassName( $migrationName ) { $class = str_replace('_', ' ', $migrationName); $class = ucwords($class); $class = str_replace(' ', '', $class); if (!$this->isValidClassName($class)) { throw new \InvalidArgumentException(sprintf( 'Migration class "%s" is invalid', $class )); } return $class; }
php
{ "resource": "" }
q250068
FormProvider.token
validation
public function token() { $token = ! empty($this->csrfToken) ? $this->csrfToken : csrfToken(); return $this->hidden('_token', $token); }
php
{ "resource": "" }
q250069
FormProvider.image
validation
public function image($name, $file, $attributes = [], $secure = null) { $attributes['src'] = $this->uri->assets($file, $secure); return $this->input('image', $name, null, $attributes); }
php
{ "resource": "" }
q250070
FormProvider.option
validation
protected function option($display, $value, $selected, array $attributes = []) { $selected = $this->getSelectedValue($value, $selected); $options = array_merge(['value' => $value, 'selected' => $selected], $attributes); return $this->toHtmlString('<option' . $this->html->attributes($options) . '>' . e($display) . '</option>'); }
php
{ "resource": "" }
q250071
FormProvider.getSelectedValue
validation
protected function getSelectedValue($value, $selected) { if (is_array($selected)) { return in_array($value, $selected, true) ? 'selected' : null; } return ((string)$value == (string)$selected) ? 'selected' : null; }
php
{ "resource": "" }
q250072
FormProvider.getCheckboxCheckedState
validation
protected function getCheckboxCheckedState($name, $value, $checked) { $posted = $this->getValueAttribute($name, $checked); if (is_array($posted)) { return in_array($value, $posted); } else { return (bool)$posted; } }
php
{ "resource": "" }
q250073
Lexer.tokenise
validation
public function tokenise ($pattern, $expand = false) { preg_match_all(' / (?<class_U_explicit>\\\U) \{ (?<class_U_repetition>[0-9]+) \} | (?<class_U_implicit>\\\U) | \[ (?<range_token_explicit>[^]]+) \] \{ (?<range_repetition>[0-9]+) \} | \[ (?<range_token_implicit>[^]]+) \] | (?<literal_string>[^\\\[]+) /x ', $pattern, $matches, \PREG_SET_ORDER); $tokens = []; foreach ($matches as $match) { if (!empty($match['class_U_explicit'])) { $token = [ 'type' => 'class', 'class' => static::CLASS_UPPERCASE_UNAMBIGUOUS, 'repetition' => (int) $match['class_U_repetition'] ]; if ($expand) { $token['haystack'] = 'ABCDEFGHKMNOPRSTUVWXYZ23456789'; } $tokens[] = $token; } else if (!empty($match['class_U_implicit'])) { $token = [ 'type' => 'class', 'class' => static::CLASS_UPPERCASE_UNAMBIGUOUS, 'repetition' => 1 ]; if ($expand) { $token['haystack'] = 'ABCDEFGHKMNOPRSTUVWXYZ23456789'; } $tokens[] = $token; } else if (!empty($match['range_token_explicit'])) { $token = [ 'type' => 'range', 'token' => $match['range_token_explicit'], 'repetition' => (int) $match['range_repetition'] ]; if ($expand) { $token['haystack'] = static::expandRange($match['range_token_explicit']); } $tokens[] = $token; } else if (!empty($match['range_token_implicit'])) { $token = [ 'type' => 'range', 'token' => $match['range_token_implicit'], 'repetition' => 1 ]; if ($expand) { $token['haystack'] = static::expandRange($match['range_token_implicit']); } $tokens[] = $token; } else if (!empty($match['literal_string'])) { $tokens[] = [ 'type' => 'literal', 'string' => $match['literal_string'] ]; } } return $tokens; }
php
{ "resource": "" }
q250074
Generator.generateFromPattern
validation
public function generateFromPattern ($pattern, $amount = 1, $safeguard = 100) { $lexer = new \Gajus\Paggern\Lexer(); $tokens = $lexer->tokenise($pattern, true); $codes = array_fill(0, $amount + $safeguard, ''); foreach ($tokens as &$token) { if ($token['type'] !== 'literal') { // Use RandomLib\Generator to populate token pool with random characters matching the pattern. // Pool is pre-generated for each token use. This is done to reduce the number of generator invocations. $token['pool'] = $this->generator->generateString($token['repetition'] * ($amount + $safeguard), $token['haystack']); } unset($token); } // Itterate through each code appending the value derived from the token. // In case of the range or class token, offset the value from the pre-generated pattern matching pool. foreach ($codes as $i => &$code) { foreach ($tokens as $token) { if ($token['type'] === 'literal') { $code .= $token['string']; } else { $code .= mb_substr($token['pool'], $token['repetition'] * $i, $token['repetition']); } } unset($code); } $codes = array_slice(array_unique($codes), 0, $amount); if (count($codes) < $amount) { throw new Exception\RuntimeException('Unique combination pool exhausted.'); } return $codes; }
php
{ "resource": "" }
q250075
CommandBuilder.getObserver
validation
private function getObserver(): ProcessObserverInterface { if (1 === count($this->observerList)) { $observer = $this->observerList[0]; } elseif (count($this->observerList)) { $observer = new AggregateLogger($this->observerList); } else { $observer = new NullProcessObserver(); } return $observer; }
php
{ "resource": "" }
q250076
CommandBuilder.getEnvironment
validation
public function getEnvironment(string $operatingSystem): EnvironmentInterface { $environmentList = [ new UnixEnvironment() ]; /** @var EnvironmentInterface $environment */ $environment = null; foreach ($environmentList as $possibleEnvironment) { if (in_array($operatingSystem, $possibleEnvironment->getSupportedList())) { $environment = $possibleEnvironment; } } if (is_null($environment)) { throw new \RuntimeException( 'Unable to find Environment for OS "' . $operatingSystem . '".'. 'Try explicitly providing an Environment when instantiating the builder.' ); } return $environment; }
php
{ "resource": "" }
q250077
AbstractTask.setMaxRetries
validation
public function setMaxRetries($retries) { switch (gettype($retries)) { case 'integer': $this->maxRetries = new Retries($retries); break; case 'object': $this->maxRetries = $retries; break; default: throw new InvalidArgumentException('Invalid type for max retries given.'); break; } }
php
{ "resource": "" }
q250078
Process.hasExceededTimeout
validation
private function hasExceededTimeout(): bool { return -1 !== $this->timeout && (microtime(true) - $this->startTime) * 1000000 > $this->timeout; }
php
{ "resource": "" }
q250079
Process.getStatus
validation
private function getStatus(): array { $status = proc_get_status($this->process); if (!$status['running'] && is_null($this->exitCode)) { $this->exitCode = $status['exitcode']; } return $status; }
php
{ "resource": "" }
q250080
Process.readStreams
validation
private function readStreams(\Closure $callback = null): void { $stdOut = $this->readOutput(self::STDOUT); $stdErr = $this->readOutput(self::STDERR); $this->fullStdOut .= $stdOut; $this->fullStdErr .= $stdErr; if (!is_null($callback)) { $callback($stdOut, $stdErr); } $this->observer->stdOutRead($this->pid, $stdOut); $this->observer->stdErrRead($this->pid, $stdErr); }
php
{ "resource": "" }
q250081
Event.setExitCode
validation
public function setExitCode($exitCode) { \Assert\that($exitCode)->integer()->min(0); $this->exitCode = $exitCode; return $this; }
php
{ "resource": "" }
q250082
URLSegmentExtension.generateURLSegment
validation
public function generateURLSegment($increment = null) { $filter = new URLSegmentFilter(); $this->owner->URLSegment = $filter->filter($this->owner->Title); if(is_int($increment)) $this->owner->URLSegment .= '-' . $increment; // Check to see if the URLSegment already exists $duplicate = DataList::create($this->owner->ClassName)->filter(array( "URLSegment" => $this->owner->URLSegment, "BlogID" => $this->owner->BlogID )); if($this->owner->ID) $duplicate = $duplicate->exclude("ID", $this->owner->ID); if($duplicate->count() > 0) { $increment = is_int($increment) ? $increment + 1 : 0; $this->owner->generateURLSegment((int) $increment); } return $this->owner->URLSegment; }
php
{ "resource": "" }
q250083
ProcessOutput.stringToArray
validation
private function stringToArray(string $string): array { $lines = preg_split('/\R/', $string); if (1 === count($lines) && '' === $lines[0]) { $lines = []; } return $lines; }
php
{ "resource": "" }
q250084
Rendition.save
validation
public function save() { if (!isset($this->name)) { return false; } if ( class_exists('\Tilmeld\Tilmeld') && !\Tilmeld\Tilmeld::gatekeeper('umailphp/admin') ) { return false; } return parent::save(); }
php
{ "resource": "" }
q250085
AllLogger.log
validation
private function log(string $message, array $context = []): void { $this->logger->log($this->logLevel, $message, $context); }
php
{ "resource": "" }
q250086
HarmonyThemeBundle.build
validation
public function build(ContainerBuilder $container) { $container->addCompilerPass(new ThemeCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, - 10); $container->addCompilerPass(new ThemeProviderPass()); }
php
{ "resource": "" }
q250087
Blog.getBlogPosts
validation
public function getBlogPosts() { $blogPosts = BlogPost::get()->filter("ParentID", $this->ID); //Allow decorators to manipulate list $this->extend('updateGetBlogPosts', $blogPosts); return $blogPosts; }
php
{ "resource": "" }
q250088
Blog.getArchivedBlogPosts
validation
public function getArchivedBlogPosts($year, $month = null, $day = null) { $query = $this->getBlogPosts()->dataQuery(); $stage = $query->getQueryParam("Versioned.stage"); if($stage) $stage = '_' . Convert::raw2sql($stage); $query->innerJoin("BlogPost", "`SiteTree" . $stage . "`.`ID` = `BlogPost" . $stage . "`.`ID`"); $query->where("YEAR(PublishDate) = '" . Convert::raw2sql($year) . "'"); if($month) { $query->where("MONTH(PublishDate) = '" . Convert::raw2sql($month) . "'"); if($day) { $query->where("DAY(PublishDate) = '" . Convert::raw2sql($day) . "'"); } } return $this->getBlogPosts()->setDataQuery($query); }
php
{ "resource": "" }
q250089
Blog_Controller.tag
validation
public function tag() { $tag = $this->getCurrentTag(); if($tag) { $this->blogPosts = $tag->BlogPosts(); return $this->render(); } return $this->httpError(404, "Not Found"); }
php
{ "resource": "" }
q250090
Blog_Controller.category
validation
public function category() { $category = $this->getCurrentCategory(); if($category) { $this->blogPosts = $category->BlogPosts(); return $this->render(); } return $this->httpError(404, "Not Found"); }
php
{ "resource": "" }
q250091
Blog_Controller.rss
validation
public function rss() { $rss = new RSSFeed($this->getBlogPosts(), $this->Link(), $this->MetaTitle, $this->MetaDescription); $this->extend('updateRss', $rss); return $rss->outputToBrowser(); }
php
{ "resource": "" }
q250092
Blog_Controller.PaginatedList
validation
public function PaginatedList() { $posts = new PaginatedList($this->blogPosts); // If pagination is set to '0' then no pagination will be shown. if($this->PostsPerPage > 0) $posts->setPageLength($this->PostsPerPage); else $posts->setPageLength($this->getBlogPosts()->count()); $start = $this->request->getVar($posts->getPaginationGetVar()); $posts->setPageStart($start); return $posts; }
php
{ "resource": "" }
q250093
Blog_Controller.getCurrentTag
validation
public function getCurrentTag() { $tag = $this->request->param("Tag"); if($tag) { return $this->dataRecord->Tags() ->filter("URLSegment", $tag) ->first(); } return null; }
php
{ "resource": "" }
q250094
Blog_Controller.getCurrentCategory
validation
public function getCurrentCategory() { $category = $this->request->param("Category"); if($category) { return $this->dataRecord->Categories() ->filter("URLSegment", $category) ->first(); } return null; }
php
{ "resource": "" }
q250095
Blog_Controller.getArchiveYear
validation
public function getArchiveYear() { $year = $this->request->param("Year"); if(preg_match("/^[0-9]{4}$/", $year)) { return (int) $year; } return null; }
php
{ "resource": "" }
q250096
Blog_Controller.getArchiveDate
validation
public function getArchiveDate() { $year = $this->getArchiveYear(); $month = $this->getArchiveMonth(); $day = $this->getArchiveDay(); if($year) { if($month) { $date = $year . '-' . $month . '-01'; if($day) { $date = $year . '-' . $month . '-' . $day; } } else { $date = $year . '-01-01'; } return DBField::create_field("Date", $date); } }
php
{ "resource": "" }
q250097
Retries.increase
validation
public function increase() { $this->retries++; if ($this->retries > $this->maxRetries) { throw new MaxRetriesExceededException( sprintf( 'Max allowed retries exceeded. Allowed: %s. Tried: %s.', $this->maxRetries, $this->retries ) ); } return $this; }
php
{ "resource": "" }
q250098
ThemeAssetsInstallCommand._relativeSymlinkWithFallback
validation
private function _relativeSymlinkWithFallback(string $originDir, string $targetDir): string { try { $this->_symlink($originDir, $targetDir, true); $method = AssetsInstallCommand::METHOD_RELATIVE_SYMLINK; } catch (IOException $e) { $method = $this->_absoluteSymlinkWithFallback($originDir, $targetDir); } return $method; }
php
{ "resource": "" }
q250099
ThemeAssetsInstallCommand._absoluteSymlinkWithFallback
validation
private function _absoluteSymlinkWithFallback(string $originDir, string $targetDir): string { try { $this->_symlink($originDir, $targetDir); $method = AssetsInstallCommand::METHOD_ABSOLUTE_SYMLINK; } catch (IOException $e) { // fall back to copy $method = $this->_hardCopy($originDir, $targetDir); } return $method; }
php
{ "resource": "" }