_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q12400
Job.release
train
public function release($delay = 10, $priority = 5) { return $this->getConnection()->release($this->getId(), $priority, $delay); }
php
{ "resource": "" }
q12401
VirtualEntity.handle
train
private function handle($method, array $arguments, $default) { // Target property (drop set or get word) $property = substr($method, 3); // Convert to snake case $property = TextUtils::snakeCase($property); $start = substr($method, 0, 3); // Are we dealing with a getter? if ($start == 'get') { if ($property === false) { throw new LogicException('Attempted to call a getter on undefined property'); } // getter is being used if ($this->has($property)) { return $this->container[$property]; } else { return $default; } // Are we dealing with a setter? } else if ($start == 'set') { if ($this->once === true && $this->has($property)) { throw new RuntimeException(sprintf('You can write to "%s" only once', $property)); } // Make sure the first argument is supplied if (array_key_exists(0, $arguments)) { $value = $arguments[0]; } else { throw new UnderflowException(sprintf( 'The virtual setter for "%s" expects at least one argument, which would be a value. None supplied.', $property )); } // If filter is defined, then use it if (isset($arguments[1])) { // Override value with filtered one $value = Filter::sanitize($value, $arguments[1]); } // setter is being used $this->container[$property] = $value; return $this; } else { // Throw exception only on strict mode if ($this->strict == true) { throw new RuntimeException(sprintf( 'Virtual method name must start either from "get" or "set". You provided "%s"', $method )); } } }
php
{ "resource": "" }
q12402
SessionBag.initHandler
train
private function initHandler(SaveHandlerInterface $handler) { return session_set_save_handler(array($handler, 'open'), array($handler, 'close'), array($handler, 'read'), array($handler, 'write'), array($handler, 'destroy'), array($handler, 'gc')); }
php
{ "resource": "" }
q12403
SessionBag.start
train
public function start(array $options = array()) { if ($this->isStarted() === false) { // Cookie parameters must be defined before session_start()! if (!empty($options)) { $this->setCookieParams($options); } if (!session_start()) { return false; } } // Reference is important! Because we are going to deal with $_SESSION itself // not with its copy, or this simply won't work the way we expect $this->session =& $_SESSION; // Store unique data to validator $this->sessionValidator->write($this); return true; }
php
{ "resource": "" }
q12404
SessionBag.setMany
train
public function setMany(array $collection) { foreach ($collection as $key => $value) { $this->set($key, $value); } return $this; }
php
{ "resource": "" }
q12405
SessionBag.hasMany
train
public function hasMany(array $keys) { foreach ($keys as $key) { if (!$this->has($key)) { return false; } } return true; }
php
{ "resource": "" }
q12406
SessionBag.get
train
public function get($key, $default = false) { if ($this->has($key) !== false) { return $this->session[$key]; } else { return $default; } }
php
{ "resource": "" }
q12407
SessionBag.remove
train
public function remove($key) { if ($this->has($key)) { unset($this->session[$key]); return true; } else { return false; } }
php
{ "resource": "" }
q12408
SessionBag.setCookieParams
train
public function setCookieParams(array $params) { $defaults = $this->getCookieParams(); // Override defaults if present $params = array_merge($defaults, $params); return session_set_cookie_params( intval($params['lifetime']), $params['path'], $params['domain'], (bool) $params['secure'], (bool) $params['httponly'] ); }
php
{ "resource": "" }
q12409
SessionBag.destroy
train
public function destroy() { // Erase the id on the client side if ($this->cookieBag->has($this->getName())) { $this->cookieBag->remove($this->getName()); } // Erase on the server side return session_destroy(); }
php
{ "resource": "" }
q12410
ReAuth.getUserBag
train
public function getUserBag() { $userBag = new UserBag(); $userBag->setLogin($this->cookieBag->get(self::CLIENT_LOGIN_KEY)) ->setPasswordHash($this->cookieBag->get(self::CLIENT_LOGIN_PASSWORD_HASH_KEY)); return $userBag; }
php
{ "resource": "" }
q12411
ReAuth.isStored
train
public function isStored() { foreach ($this->getKeys() as $key) { if (!$this->cookieBag->has($key)) { return false; } } // Now start checking the signature if (!$this->isValidSignature( $this->cookieBag->get(self::CLIENT_LOGIN_KEY), $this->cookieBag->get(self::CLIENT_LOGIN_PASSWORD_HASH_KEY), $this->cookieBag->get(self::CLIENT_TOKEN_KEY) )) { return false; } return true; }
php
{ "resource": "" }
q12412
ReAuth.clear
train
public function clear() { $keys = $this->getKeys(); foreach ($keys as $key) { $this->cookieBag->remove($key); } return true; }
php
{ "resource": "" }
q12413
ReAuth.store
train
public function store($login, $passwordHash) { // Data to store on client machine $data = array( self::CLIENT_LOGIN_KEY => $login, self::CLIENT_LOGIN_PASSWORD_HASH_KEY => $passwordHash, self::CLIENT_TOKEN_KEY => $this->makeToken($login, $passwordHash) ); foreach ($data as $key => $value) { $this->cookieBag->set($key, $value, self::CLIENT_LIFETIME); } }
php
{ "resource": "" }
q12414
AssetManager.parseModes
train
protected function parseModes() { foreach ($this->modeDirs as $dir) { $absDir = $this->fileLocator->locate($dir); $finder = Finder::create()->files()->in($absDir)->notName("*test.js")->name('*.js'); foreach ($finder as $file) { $this->addModesFromFile($dir,$file); } } #save to cache if env prod if ($this->env == 'prod') { $this->cacheDriver->save(static::CACHE_MODES_NAME, $this->getModes()); } }
php
{ "resource": "" }
q12415
AssetManager.addModesFromFile
train
protected function addModesFromFile($dir,$file) { $dir = $this->parseDir($dir); $jsContent = $file->getContents(); preg_match_all('#defineMIME\(\s*(\'|")([^\'"]+)(\'|")#', $jsContent, $modes); if (count($modes[2])) { foreach ($modes[2] as $mode) { $this->addMode($mode, $dir."/".$file->getRelativePathname()); } } $this->addMode($file->getRelativePath(), $dir."/".$file->getRelativePathname()); #save to cache if env prod if ($this->env == 'prod') { $this->cacheDriver->save(static::CACHE_MODES_NAME, $this->getThemes()); } }
php
{ "resource": "" }
q12416
AssetManager.parseThemes
train
protected function parseThemes() { foreach ($this->themesDirs as $dir) { $absDir = $this->fileLocator->locate($dir); $finder = Finder::create()->files()->in($absDir)->name('*.css'); foreach ($finder as $file) { $this->addTheme($file->getBasename('.css'), $file->getPathname()); } } #save to cache if env prod if ($this->env == 'prod') { $this->cacheDriver->save(static::CACHE_THEMES_NAME, $this->getThemes()); } }
php
{ "resource": "" }
q12417
BaseConverter.baseConvert
train
public static function baseConvert($number, $fromBase, $toBase, $precision = -1) { $converter = new self($fromBase, $toBase); $converter->setPrecision($precision); return $converter->convert($number); }
php
{ "resource": "" }
q12418
BaseConverter.convert
train
public function convert($number) { $integer = (string) $number; $fractions = null; $sign = ''; if (in_array(substr($integer, 0, 1), ['+', '-'], true)) { $sign = $integer[0]; $integer = substr($integer, 1); } if (($pos = strpos($integer, '.')) !== false) { $fractions = substr($integer, $pos + 1); $integer = substr($integer, 0, $pos); } return $this->convertNumber($sign, $integer, $fractions); }
php
{ "resource": "" }
q12419
BaseConverter.convertNumber
train
private function convertNumber($sign, $integer, $fractions) { try { $result = implode('', $this->convertInteger($this->source->splitString($integer))); if ($fractions !== null) { $result .= '.' . implode('', $this->convertFractions($this->source->splitString($fractions))); } } catch (DigitList\InvalidDigitException $ex) { return false; } return $sign . $result; }
php
{ "resource": "" }
q12420
CApacheAbstractFile.populateCommonDocs
train
protected function populateCommonDocs(string $padding, string $commondocs) : string { $output = ''; if (is_dir($commondocs)) { $h = opendir($commondocs); while ($dir = readdir($h)) { $folder = $commondocs . DIRECTORY_SEPARATOR . $dir; if ($dir !== '.' && $dir !== '..' && is_dir($folder)) { $output .= "\n" . $padding . "Alias /$dir \"$folder\"\n" . $padding . "<Directory \"$folder\">\n" . $padding . " AllowOverride All\n" . $padding . " Require all granted\n" . $padding . "</Directory>\n" ; } } closedir($h); } return $output; }
php
{ "resource": "" }
q12421
StrCheckers.hasSubstring
train
public static function hasSubstring($haystack, $needles, $characterEncoding = 'UTF-8') { foreach ((array)$needles as $needle) { if ($needle == '') { continue; } if (mb_strpos($haystack, $needle, 0, $characterEncoding) !== false) { return true; } } return false; }
php
{ "resource": "" }
q12422
StrCheckers.startsWith
train
public static function startsWith($haystack, $needles) { foreach ((array)$needles as $needle) { if ($needle == '') { continue; } $substring = mb_substr($haystack, 0, mb_strlen($needle)); if (self::doesStringMatchNeedle($substring, $needle)) { return true; } } return false; }
php
{ "resource": "" }
q12423
StrCheckers.matchesPattern
train
public static function matchesPattern($pattern, $givenString) { if ($pattern == $givenString) { return true; } $pattern = preg_quote($pattern, '#'); $pattern = str_replace('\*', '.*', $pattern) . '\z'; return (bool)preg_match('#^' . $pattern . '#', $givenString); }
php
{ "resource": "" }
q12424
AbstractListWidget.createListItem
train
protected function createListItem($class, $text) { $li = new NodeElement(); $li->openTag('li') ->addAttribute('class', $class) ->finalize(false); if ($text !== null) { $li->setText($text); } return $li->closeTag(); }
php
{ "resource": "" }
q12425
AbstractListWidget.renderList
train
protected function renderList($class, array $children) { $ul = new NodeElement(); $ul->openTag('ul') ->addAttribute('class', $class) ->finalize(true) ->appendChildren($children) ->closeTag(); return $ul->render(); }
php
{ "resource": "" }
q12426
Template.get_include_files
train
public static function get_include_files( $directory, $exclude_underscore = false ) { $return = [ 'files' => [], 'directories' => [], ]; if ( ! is_dir( $directory ) ) { return $return; } $directory_iterator = new \DirectoryIterator( $directory ); foreach ( $directory_iterator as $file ) { if ( $file->isDot() ) { continue; } if ( $file->isDir() ) { $return['directories'][] = $file->getPathname(); continue; } if ( 'php' !== $file->getExtension() ) { continue; } if ( $exclude_underscore ) { if ( 0 === strpos( $file->getBasename(), '_' ) ) { continue; } } $return['files'][] = $file->getPathname(); } return $return; }
php
{ "resource": "" }
q12427
Template.get_template_parts
train
public static function get_template_parts( $directory, $exclude_underscore = false ) { if ( ! is_dir( $directory ) ) { return; } $files = static::get_include_files( $directory, $exclude_underscore ); foreach ( $files['files'] as $file ) { $file = realpath( $file ); $template_name = str_replace( [ trailingslashit( realpath( get_template_directory() ) ), '.php' ], '', $file ); \get_template_part( $template_name ); } foreach ( $files['directories'] as $directory ) { static::get_template_parts( $directory, $exclude_underscore ); } }
php
{ "resource": "" }
q12428
Template.glob_recursive
train
public static function glob_recursive( $path ) { $files = []; if ( preg_match( '/\\' . DIRECTORY_SEPARATOR . 'vendor$/', $path ) ) { return $files; } foreach ( glob( $path . '/*' ) as $file ) { if ( is_dir( $file ) ) { $files = array_merge( $files, static::glob_recursive( $file ) ); } elseif ( preg_match( '/\.php$/', $file ) ) { $files[] = $file; } } return $files; }
php
{ "resource": "" }
q12429
CommonUtil.getValidatorErrorMessage
train
public static function getValidatorErrorMessage($validator) { $messages = $validator->errors(); $msgArr = $messages->all(); $arr = []; foreach ($msgArr as $k => $v) { $arr[] = $v; } $ret = implode(",", $arr); return $ret; }
php
{ "resource": "" }
q12430
CommonUtil.randStr
train
public static function randStr($len = 6, $format = 'ALL') { switch (strtoupper($format)) { case 'ALL': $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break; case 'CHAR': $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break; case 'NUMBER': $chars = '0123456789'; break; default : $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break; } mt_srand((double)microtime() * 1000000 * getmypid()); $randStr = ""; while (strlen($randStr) < $len) $randStr .= substr($chars, (mt_rand() % strlen($chars)), 1); return $randStr; }
php
{ "resource": "" }
q12431
FormatterUtil.formatResultData
train
public static function formatResultData(AjaxChoiceListFormatterInterface $formatter, ChoiceListView $choiceListView) { $result = []; foreach ($choiceListView->choices as $i => $choiceView) { if ($choiceView instanceof ChoiceGroupView) { $group = $formatter->formatGroupChoice($choiceView); foreach ($choiceView->choices as $j => $subChoiceView) { $group = $formatter->addChoiceInGroup($group, $subChoiceView); } if (!$formatter->isEmptyGroup($group)) { $result[] = $group; } } else { $result[] = $formatter->formatChoice($choiceView); } } return $result; }
php
{ "resource": "" }
q12432
ConnectionTable.pluck
train
public function pluck($field, $indexField=null) { $fieldsFormat = $field; $usingFormatting = preg_match_all('/{(\w+\.\w+|\w+)}/', $field, $matches); //Obtención del campo/s de la consulta $fields = []; if ($usingFormatting) { $fields = $matches[1]; foreach ($fields as $formatField) { if (($pos = strpos($formatField, '.')) !== false) { $replaceFormatField = substr($formatField, $pos + 1); $fieldsFormat = str_replace($formatField, $replaceFormatField, $fieldsFormat); } } } else { $fields = [$field]; } //Establecer los campos del select $selectFields = $fields; if ($indexField != null && !in_array($indexField, $selectFields)) { $selectFields[] = $indexField; } $this->selectFields($selectFields); //Obtención del campo de indice $returnIndexField = $indexField; if (!empty($returnIndexField)) { if (($pos = strpos($returnIndexField, '.')) !== false) { $returnIndexField = substr($returnIndexField, $pos + 1); } } //Obtención de los campos de retorno $returnFields = []; foreach ($fields as $returnField) { if (($pos = strpos($returnField, '.')) !== false) { $returnField = substr($returnField, $pos + 1); } $returnFields[] = $returnField; } //Creación del array de resultados $fieldResults = []; $results = $this->find(); foreach ($results as $result) { $value = null; if (!$usingFormatting) { $value = $result->{$returnFields[0]}; } else { $value = $fieldsFormat; foreach ($returnFields as $returnField) { $value = str_replace("{" . $returnField . "}", $result->$returnField, $value); } } if ($returnIndexField != null) { $fieldResults[$result->$returnIndexField] = $value; } else { $fieldResults[] = $value; } } return $fieldResults; }
php
{ "resource": "" }
q12433
ConnectionTable.insert
train
public function insert(array $fields = []) { $query = new InsertQuery($this->getTable()); $query->fields(!empty($fields)? $fields : $this->getFields()); return $this->connection->exec($query); }
php
{ "resource": "" }
q12434
ConnectionTable.update
train
public function update(array $fields = []) { $query = new UpdateQuery($this->getTable()); $query->fields(!empty($fields)? $fields : $this->getFields()); $query->whereConditionGroup($this->getWhereConditionGroup()); return $this->connection->exec($query); }
php
{ "resource": "" }
q12435
ConnectionTable.delete
train
public function delete() { $query = new DeleteQuery($this->getTable()); $query->whereConditionGroup($this->getWhereConditionGroup()); return $this->connection->exec($query); }
php
{ "resource": "" }
q12436
AbstractCommand.getPhpFiles
train
protected function getPhpFiles($path) { if (is_dir($path)) { return new RegexIterator( new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied" ), '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH ); } else { return []; } }
php
{ "resource": "" }
q12437
AbstractCommand.dumpLangArray
train
protected function dumpLangArray($source, $code = '') { // Use array short syntax if ($this->config('array_shorthand', true) === false) { return $source; } // Split given source into PHP tokens $tokens = token_get_all($source); $brackets = []; for ($i = 0; $i < count($tokens); $i++) { $token = $tokens[$i]; if ($token === '(') { $brackets[] = false; } elseif ($token === ')') { $token = array_pop($brackets) ? ']' : ')'; } elseif (is_array($token) && $token[0] === T_ARRAY) { $a = $i + 1; if (isset($tokens[$a]) && $tokens[$a][0] === T_WHITESPACE) { $a++; } if (isset($tokens[$a]) && $tokens[$a] === '(') { $i = $a; $brackets[] = true; $token = '['; } } $code .= is_array($token) ? $token[1] : $token; } // Fix indenting $code = preg_replace('/^ |\G /m', ' ', $code); // Fix weird new line breaks at the beginning of arrays $code = preg_replace('/=\>\s\n\s{4,}\[/m', '=> [', $code); return $code; }
php
{ "resource": "" }
q12438
MongoManager.addDatabase
train
public function addDatabase(string $name, MongoDatabase $database): MongoManager { if (isset($this->databases[$name])) { throw new ODMException("Database '{$name}' already exists"); } $this->databases[$name] = $database; return $this; }
php
{ "resource": "" }
q12439
MongoManager.database
train
public function database(string $database = null): MongoDatabase { if (empty($database)) { $database = $this->config->defaultDatabase(); } //Spiral support ability to link multiple virtual databases together using aliases $database = $this->config->resolveAlias($database); if (isset($this->databases[$database])) { return $this->databases[$database]; } if (!$this->config->hasDatabase($database)) { throw new ODMException( "Unable to initiate MongoDatabase, no presets for '{$database}' found" ); } $options = $this->config->databaseOptions($database); //Initiating database instance return $this->createDatabase( $database, $options['server'], $options['database'], $options['driverOptions'] ?? [], $options['options'] ?? [] ); }
php
{ "resource": "" }
q12440
MongoManager.getDatabases
train
public function getDatabases(): array { $result = []; //Include manually added databases foreach ($this->config->databaseNames() as $name) { $result[] = $this->database($name); } return $result; }
php
{ "resource": "" }
q12441
Crypter.encryptValue
train
public function encryptValue($value) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->salt, $value, MCRYPT_MODE_ECB, $iv); return trim(base64_encode($text)); }
php
{ "resource": "" }
q12442
Crypter.decryptValue
train
public function decryptValue($value) { $decoded = base64_decode($value); $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->salt, $decoded, MCRYPT_MODE_ECB, $iv); return trim($text); }
php
{ "resource": "" }
q12443
JWT.generateTokenByUser
train
public function generateTokenByUser($user) { return $this->builder ->set('user', $user) ->sign(new Sha256(), env('JWT_SECRET')) ->getToken(); }
php
{ "resource": "" }
q12444
VMProApiExtension.flattenParametersFromConfig
train
private function flattenParametersFromConfig(ContainerBuilder $container, $configs, $root) { $parameters = []; foreach ($configs as $key => $value) { $parameterKey = sprintf('%s_%s', $root, $key); if (is_array($value)) { $parameters = array_merge( $parameters, $this->flattenParametersFromConfig($container, $value, $parameterKey) ); continue; } $parameters[$parameterKey] = $value; } return $parameters; }
php
{ "resource": "" }
q12445
VMProApiExtension.loadInternal
train
protected function loadInternal(array $configs, ContainerBuilder $container) { $parameters = $this->flattenParametersFromConfig($container, $configs, 'vm_pro_api'); foreach ($parameters as $key => $value) { $container->setParameter($key, $value); } $loader = new YamlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); // Always load the services that will always be the same $loader->load('services/main.yml'); // only load ratings service if the meta data fields are configured if (array_key_exists('vm_pro_api_rating_meta_data_fields_average', $parameters) && array_key_exists('vm_pro_api_rating_meta_data_fields_count', $parameters)) { $loader->load('services/ratings.yml'); } // Dynamically load service configurations that are specific // to which Guzzle version is installed if (version_compare(ClientInterface::VERSION, '6.0', '>=')) { $loader->load('services/guzzle6.yml'); } else { $loader->load('services/guzzle5.yml'); } if (version_compare(Kernel::VERSION, '3.3', '>=')) { $loader->load('services/symfony3.yml'); } }
php
{ "resource": "" }
q12446
Mail.render
train
public function render($controller, $template, $data) { $view = new View($controller); $css = array(); $html = $view->mail($template, $data, $css); $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setCSS($this->getCss($css)); $cssToInlineStyles->setHTML($html); return $cssToInlineStyles->convert(); }
php
{ "resource": "" }
q12447
AuthorListComparator.patchExtractor
train
private function patchExtractor($path, $extractor, $wantedAuthors) { if (!($this->diff && $extractor instanceof PatchingExtractor)) { return false; } $original = \explode("\n", $extractor->getBuffer($path)); $new = \explode("\n", $extractor->getBuffer($path, $wantedAuthors)); $diff = new \Diff($original, $new); $patch = $diff->render($this->diff); if (empty($patch)) { return false; } $patchFile = $path; foreach ($this->config->getIncludedPaths() as $prefix) { $prefixLength = \strlen($prefix); if (strpos($path, $prefix) === 0) { $patchFile = \substr($path, $prefixLength); if (strncmp($patchFile, '/', 1) === 0) { $patchFile = \substr($patchFile, 1); } break; } } $this->patchSet[] = 'diff ' . $patchFile . ' ' . $patchFile . "\n" . '--- ' . $patchFile . "\n" . '+++ ' . $patchFile . "\n" . $patch; return true; }
php
{ "resource": "" }
q12448
AuthorListComparator.determineSuperfluous
train
private function determineSuperfluous($mentionedAuthors, $wantedAuthors, $path) { $superfluous = []; foreach (\array_diff_key($mentionedAuthors, $wantedAuthors) as $key => $author) { if (!$this->config->isCopyLeftAuthor($author, $path)) { $superfluous[$key] = $author; } } return $superfluous; }
php
{ "resource": "" }
q12449
AuthorListComparator.comparePath
train
private function comparePath(AuthorExtractor $current, AuthorExtractor $should, ProgressBar $progressBar, $path) { $validates = true; $mentionedAuthors = $current->extractAuthorsFor($path); $multipleAuthors = $current->extractMultipleAuthorsFor($path); $wantedAuthors = array_merge($should->extractAuthorsFor($path), $this->config->getCopyLeftAuthors($path)); // If current input is not valid, return. if ($mentionedAuthors === null) { if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->output->writeln( \sprintf('Skipped check of <info>%s</info> as it is not present.', $path) ); } if ($this->useProgressBar) { $progressBar->advance(1); $progressBar->setMessage('Author validation is in progress...'); } return true; } $superfluousMentions = $this->determineSuperfluous($mentionedAuthors, $wantedAuthors, $path); $missingMentions = \array_diff_key($wantedAuthors, $mentionedAuthors); if (\count($superfluousMentions)) { $this->output->writeln( \sprintf( PHP_EOL . PHP_EOL . 'The file <info>%s</info> is mentioning superfluous author(s):' . PHP_EOL . '<comment>%s</comment>' . PHP_EOL, $path, \implode(PHP_EOL, $superfluousMentions) ) ); $validates = false; } if (\count($missingMentions)) { $this->output->writeln( \sprintf( PHP_EOL . PHP_EOL . 'The file <info>%s</info> is not mentioning its author(s):' . PHP_EOL . '<comment>%s</comment>' . PHP_EOL, $path, \implode(PHP_EOL, $missingMentions) ) ); $validates = false; } if (\count($multipleAuthors)) { $this->output->writeln( \sprintf( PHP_EOL . PHP_EOL . 'The file <info>%s</info> multiple author(s):' . PHP_EOL . '<comment>%s</comment>'. PHP_EOL, $path, \implode(PHP_EOL, $multipleAuthors) ) ); $validates = false; } if (!$validates) { $this->patchExtractor($path, $current, $wantedAuthors); } if ($this->useProgressBar) { $progressBar->advance(1); $progressBar->setMessage('Author validation is in progress...'); } return $validates; }
php
{ "resource": "" }
q12450
AuthorListComparator.compare
train
public function compare(AuthorExtractor $current, AuthorExtractor $should) { $shouldPaths = $should->getFilePaths(); $currentPaths = $current->getFilePaths(); $allPaths = \array_intersect($shouldPaths, $currentPaths); $validates = true; $progressBar = new ProgressBar($this->output, \count($allPaths)); if ($this->useProgressBar) { $progressBar->start(); $progressBar->setMessage('Start author validation.'); $progressBar->setFormat('%current%/%max% [%bar%] %message% %elapsed:6s%'); } foreach ($allPaths as $pathname) { $validates = $this->comparePath($current, $should, $progressBar, $pathname) && $validates; } if ($this->useProgressBar) { $progressBar->setMessage('Finished author validation.'); $progressBar->finish(); $this->output->writeln(PHP_EOL); } return $validates; }
php
{ "resource": "" }
q12451
ManagerController.getObjectDataManager
train
protected function getObjectDataManager(Request $request) { $objectDataManager = $this->container->get(ObjectDataManager::class); $resolver = new OptionsResolver(); $resolver->setDefaults([ "folder" => null, ]); $resolver->setRequired(["returnUrl","objectId","objectType"]); $config = $resolver->resolve($request->get("_conf")); $objectDataManager->configure($config["objectId"],$config["objectType"]); $objectDataManager->documents()->folder($config["folder"]); $this->config = $config; return $objectDataManager; }
php
{ "resource": "" }
q12452
Initialize.setPlatformOptions
train
protected function setPlatformOptions(InputInterface $input, OutputInterface $output) { $platform = ProjectX::getPlatformType(); if (!$platform instanceof NullPlatformType && $platform instanceof OptionFormAwareInterface) { $classname = get_class($platform); $command_io = new SymfonyStyle($input, $output); $command_io->newLine(2); $command_io->title(sprintf('%s Platform Options', $classname::getLabel())); $form = $platform->optionForm(); $form ->setInput($input) ->setOutput($output) ->setHelperSet($this->getHelperSet()) ->process(); $this->options[$classname::getTypeId()] = $form->getResults(); } return $this; }
php
{ "resource": "" }
q12453
Initialize.setProjectOptions
train
protected function setProjectOptions(InputInterface $input, OutputInterface $output) { $project = ProjectX::getProjectType(); if ($project instanceof OptionFormAwareInterface) { $classname = get_class($project); $command_io = new SymfonyStyle($input, $output); $command_io->newLine(2); $command_io->title(sprintf('%s Project Options', $classname::getLabel())); $form = $project->optionForm(); $form ->setInput($input) ->setOutput($output) ->setHelperSet($this->getHelperSet()) ->process(); $this->options[$classname::getTypeId()] = $form->getResults(); } return $this; }
php
{ "resource": "" }
q12454
Initialize.setDeployOptions
train
protected function setDeployOptions(InputInterface $input, OutputInterface $output) { $project = ProjectX::getProjectType(); if ($project instanceof DeployAwareInterface) { $command_io = new SymfonyStyle($input, $output); $command_io->title('Deploy Build Options'); $form = (new Form()) ->setInput($input) ->setOutput($output) ->setHelperSet($this->getHelperSet()) ->addFields([ (new BooleanField('deploy', 'Setup build deploy?')) ->setDefault(false) ->setSubform(function ($subform, $value) { if (true === $value) { $subform->addFields([ (new TextField('repo_url', 'Repository URL')), ]); } }) ]) ->process(); $results = $form->getResults(); if (isset($results['deploy']) && !empty($results['deploy'])) { $this->options['deploy'] = $results['deploy']; } } return $this; }
php
{ "resource": "" }
q12455
Initialize.setEngineServiceOptions
train
protected function setEngineServiceOptions() { $project = ProjectX::getProjectType(); if ($project instanceof EngineServiceInterface) { $engine = ProjectX::getEngineType(); $classname = get_class($engine); $this->options[$classname::getTypeId()] = [ 'services' => $project->defaultServices() ]; } return $this; }
php
{ "resource": "" }
q12456
RemoteDesktopCertificate.generate
train
static public function generate() { if (! extension_loaded('openssl')) { throw new \RuntimeException("Can only generate a remote desktop certificate when OpenSSL PHP extension is installed."); } // Generate a new private (and public) key pair $config = array( 'config' => __DIR__ . '/../Resources/config/openssl.cnf' ); $privkey = openssl_pkey_new($config); // Generate a certificate signing request $dn = array( "commonName" => "AzureDistributionBundle for Symfony Tools" ); $csr = openssl_csr_new($dn, $privkey, $config); $sscert = openssl_csr_sign($csr, null, $privkey, 365, $config); return new self($privkey, $sscert); }
php
{ "resource": "" }
q12457
RemoteDesktopCertificate.export
train
public function export($directory, $filePrefix, $keyPassword, $overwrite = false) { if (! is_writeable($directory)) { throw new \RuntimeException("Key Export directory is not writable: " . $directory); } $pkcs12File = $directory . "/" . $filePrefix . ".pfx"; $x509File = $directory . "/" . $filePrefix . ".cer"; if (! $overwrite && file_exists($pkcs12File)) { throw new \RuntimeException("PKCS12 File at " . $pkcs12File . " already exists and is not overwritten."); } if (! $overwrite && file_exists($x509File)) { throw new \RuntimeException("X509 Certificate File at " . $x509File . " already exists and is not overwritten."); } $args = array( 'friendly_name' => 'AzureDistributionBundle for Symfony Tools' ); openssl_pkcs12_export_to_file($this->certificate, $pkcs12File, $this->privKey, $keyPassword, $args); openssl_x509_export_to_file($this->certificate, $x509File, true); return $x509File; }
php
{ "resource": "" }
q12458
RemoteDesktopCertificate.encryptAccountPassword
train
public function encryptAccountPassword($x509File, $desktopPassword) { $directory = sys_get_temp_dir(); $filePrefix = "azure"; $pkcs7In = $directory . "/" . $filePrefix . "_in.pkcs7"; $pkcs7Out = $directory . "/" . $filePrefix . "_out.pkcs7"; $certificate = openssl_x509_read(file_get_contents($x509File)); file_put_contents($pkcs7In, $desktopPassword); $ret = openssl_pkcs7_encrypt($pkcs7In, $pkcs7Out, $certificate, array()); if (! $ret) { throw new \RuntimeException("Encrypting Password failed."); } $parts = explode("\n\n", file_get_contents($pkcs7Out)); $body = str_replace("\n", "", $parts[1]); unlink($pkcs7In); unlink($pkcs7Out); return $body; }
php
{ "resource": "" }
q12459
RemoteDesktopCertificate.getThumbprint
train
public function getThumbprint() { $resource = openssl_x509_read($this->certificate); $thumbprint = null; $output = null; $result = openssl_x509_export($resource, $output); if ($result !== false) { $output = str_replace('-----BEGIN CERTIFICATE-----', '', $output); $output = str_replace('-----END CERTIFICATE-----', '', $output); $output = base64_decode($output); $thumbprint = sha1($output); } return $thumbprint; }
php
{ "resource": "" }
q12460
Path.build
train
public function build() : string { $path = collect([ $this->prepends, $this->resourceKey, $this->id, $this->appends, ]) ->filter() ->implode('/'); $uri = "{$path}.{$this->format}"; return $this->hasParams() ? $uri.'?'.http_build_query($this->params) : $uri; }
php
{ "resource": "" }
q12461
Path.format
train
public function format(string $format) : self { if (! in_array($format, self::VALID_FORMATS)) { throw new Exception('Invalid format provided to path.'); } $this->format = $format; return $this; }
php
{ "resource": "" }
q12462
TabsManager.buildTab
train
public function buildTab() { $tab = $this->tab; $tab->setParameters($this->parametersToView); $this->tab = null; $this->parametersToView = []; return $tab; }
php
{ "resource": "" }
q12463
CurrencyConverter.convert
train
public function convert($currency) { if ($this->isAvailable($currency)) { $rate = 1 / $this->rates[$currency]; return round($this->base * $rate, 2); } else { throw new RuntimeException(sprintf( 'Target currency "%s" does not belong to the registered map of rates', $currency )); } }
php
{ "resource": "" }
q12464
Zodiacal.getSign
train
public function getSign() { foreach ($this->getMap() as $name => $method) { // Call associated method dynamically if (call_user_func(array($this, $method))) { return $name; } } // On failure return false; }
php
{ "resource": "" }
q12465
Zodiacal.isValidMonth
train
private function isValidMonth($month) { $list = array( self::MONTH_JANUARY, self::MONTH_FEBRUARY, self::MONTH_MARCH, self::MONTH_APRIL, self::MONTH_MAY, self::MONTH_JUNE, self::MONTH_JULY, self::MONTH_AUGUST, self::MONTH_SEPTEMBER, self::MONTH_OCTOBER, self::MONTH_NOVEMBER, self::MONTH_DECEMBER ); return in_array($month, $list); }
php
{ "resource": "" }
q12466
Zodiacal.isAries
train
public function isAries() { return ($this->month === self::MONTH_MARCH) && ($this->day >= 21) && ($this->day <= 31) || ($this->month === self::MONTH_APRIL) && ($this->day <= 20); }
php
{ "resource": "" }
q12467
Zodiacal.isTaurus
train
public function isTaurus() { return ($this->month === self::MONTH_APRIL) && ($this->day >= 21) && ($this->day <= 30) || ($this->month === self::MONTH_MAY) && ($this->day <= 21); }
php
{ "resource": "" }
q12468
Zodiacal.isGemini
train
public function isGemini() { return ($this->month === self::MONTH_MAY) && ($this->day >= 22) && ($this->day <= 31) || ($this->month === self::MONTH_JULY) && ($this->day <= 21); }
php
{ "resource": "" }
q12469
Zodiacal.isCancer
train
public function isCancer() { return ($this->month === self::MONTH_JUNE) && ($this->day >= 22) && ($this->day <= 30) || ($this->month === self::MONTH_JULY) && ($this->day <= 22); }
php
{ "resource": "" }
q12470
Zodiacal.isLeo
train
public function isLeo() { return ($this->month === self::MONTH_JULY) && ($this->day >= 23) && ($this->day <= 30) || ($this->month === self::MONTH_MAY) && ($this->day <= 22); }
php
{ "resource": "" }
q12471
Zodiacal.isVirgo
train
public function isVirgo() { return ($this->month === self::MONTH_AUGUST) && ($this->day >= 23) && ($this->day <= 30) || ($this->month === self::MONTH_SEPTEMBER) && ($this->day <= 23); }
php
{ "resource": "" }
q12472
Zodiacal.isScorpio
train
public function isScorpio() { return ($this->month === self::MONTH_OCTOBER) && ($this->day >= 24) && ($this->day <= 30) || ($this->month === self::MONTH_NOVEMBER) && ($this->day <= 22); }
php
{ "resource": "" }
q12473
Zodiacal.isLibra
train
public function isLibra() { return ($this->month === self::MONTH_SEPTEMBER) && ($this->day >= 24) && ($this->day <= 30) || ($this->month === self::MONTH_OCTOBER) && ($this->day <= 23); }
php
{ "resource": "" }
q12474
Zodiacal.isSagittarius
train
public function isSagittarius() { return ($this->month === self::MONTH_NOVEMBER) && ($this->day >= 23) && ($this->day <= 30) || ($this->month === self::MONTH_DECEMBER) && ($this->day <= 21); }
php
{ "resource": "" }
q12475
Zodiacal.isCapricorn
train
public function isCapricorn() { return ($this->month === self::MONTH_DECEMBER) && ($this->day >= 22) && ($this->day <= 30) || ($this->month === self::MONTH_JANUARY) && ($this->day <= 20); }
php
{ "resource": "" }
q12476
Zodiacal.isAquarius
train
public function isAquarius() { return ($this->month === self::MONTH_JANUARY) && ($this->day >= 21) && ($this->day <= 30) || ($this->month === self::MONTH_FEBRUARY) && ($this->day <= 19); }
php
{ "resource": "" }
q12477
Zodiacal.isPisces
train
public function isPisces() { return ($this->month === self::MONTH_FEBRUARY) && ($this->day >= 20) && ($this->day <= 30) || ($this->month === self::MONTH_MARCH) && ($this->day <= 20); }
php
{ "resource": "" }
q12478
StandardMessageContent.embed
train
public function embed(string $filePath): string { $id = $this->getAttachmentId($filePath); $this->embeddedAttachments[$id] = $filePath; return $id; }
php
{ "resource": "" }
q12479
DrupalTasks.drupalInstall
train
public function drupalInstall($opts = [ 'db-name' => null, 'db-user' => null, 'db-pass' => null, 'db-host' => null, 'db-port' => null, 'db-protocol' => null, 'localhost' => false, ]) { $this->executeCommandHook(__FUNCTION__, 'before'); $database = $this->buildDatabase($opts); $this->getProjectInstance() ->setDatabaseOverride($database) ->setupDrupalInstall($opts['localhost']); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q12480
DrupalTasks.drupalLocalSetup
train
public function drupalLocalSetup($opts = [ 'db-name' => null, 'db-user' => null, 'db-pass' => null, 'db-host' => null, 'db-port' => null, 'db-protocol' => null, 'no-engine' => false, 'no-browser' => false, 'restore-method' => null, 'localhost' => false, ]) { $this->executeCommandHook(__FUNCTION__, 'before'); $database = $this->buildDatabase($opts); $this ->getProjectInstance() ->setDatabaseOverride($database) ->setupExistingProject( $opts['no-engine'], $opts['restore-method'], $opts['no-browser'], $opts['localhost'] ); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q12481
DrupalTasks.drupalLetmein
train
public function drupalLetmein($opts = [ 'user' => null, 'path' => null ]) { $this->executeCommandHook(__FUNCTION__, 'before'); /** @var DrupalProjectType $instance */ $instance = $this->getProjectInstance(); $instance->createDrupalLoginLink($opts['user'], $opts['path']); $this->executeCommandHook(__FUNCTION__, 'after'); }
php
{ "resource": "" }
q12482
DrupalTasks.drupalDrush
train
public function drupalDrush(array $drush_command, $opts = [ 'silent' => false, 'localhost' => false, ]) { /** @var DrupalProjectType $instance */ $instance = $this->getProjectInstance(); return $instance->runDrushCommand( implode(' ', $drush_command), $opts['silent'], $opts['localhost'] ); }
php
{ "resource": "" }
q12483
DrupalTasks.drupalLocalSync
train
public function drupalLocalSync() { $this->executeCommandHook(__FUNCTION__, 'before'); /** @var DrupalProjectType $instance */ $instance = $this->getProjectInstance(); if ($instance->getProjectVersion() >= 8) { $drush = new DrushCommand(); $local_alias = $this->determineDrushLocalAlias(); $remote_alias = $this->determineDrushRemoteAlias(); if (isset($local_alias) && isset($remote_alias)) { // Drupal 8 tables to skip when syncing or dumping SQL. $skip_tables = implode(',', [ 'cache_bootstrap', 'cache_config', 'cache_container', 'cache_data', 'cache_default', 'cache_discovery', 'cache_dynamic_page_cache', 'cache_entity', 'cache_menu', 'cache_render', 'history', 'search_index', 'sessions', 'watchdog' ]); $drush->command( "sql-sync --sanitize --skip-tables-key='$skip_tables' '@$remote_alias' '@$local_alias'", true ); } $drush ->command('cim') ->command('updb --entity-updates') ->command('cr'); $instance->runDrushCommand($drush); } $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q12484
DrupalTasks.drupalRefresh
train
public function drupalRefresh($opts = [ 'db-name' => null, 'db-user' => null, 'db-pass' => null, 'db-host' => null, 'db-port' => null, 'db-protocol' => null, 'hard' => false, 'localhost' => false, ]) { $this->executeCommandHook(__FUNCTION__, 'before'); $localhost = $opts['localhost']; /** @var DrupalProjectType $instance */ $instance = $this->getProjectInstance(); $version = $instance->getProjectVersion(); // Composer install. $this->taskComposerInstall()->run(); if ($opts['hard']) { $database = $this->buildDatabase($opts); // Reinstall the Drupal database, which drops the existing data. $instance ->setDatabaseOverride($database) ->setupDrupalInstall( $localhost ); if ($version >= 8) { $instance->setDrupalUuid($localhost); } } $drush = new DrushCommand(null, $localhost); if ($version >= 8) { $instance->runDrushCommand('updb --entity-updates', false, $localhost); $instance->importDrupalConfig(1, $localhost); $drush->command('cr'); } else { $drush ->command('updb') ->command('cc all'); } $instance->runDrushCommand($drush, false, $localhost); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q12485
DrupalTasks.drupalDrushAlias
train
public function drupalDrushAlias($opts = ['exclude-remote' => false]) { $this->executeCommandHook(__FUNCTION__, 'before'); /** @var DrupalProjectType $instance */ $instance = $this->getProjectInstance(); $instance->setupDrushAlias($opts['exclude-remote']); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q12486
DrupalTasks.buildDatabase
train
protected function buildDatabase(array $options) { return (new Database()) ->setPort($options['db-port']) ->setUser($options['db-user']) ->setPassword($options['db-pass']) ->setDatabase($options['db-name']) ->setHostname($options['db-host']) ->setProtocol($options['db-protocol']); }
php
{ "resource": "" }
q12487
DrupalTasks.getDrushAliasKeys
train
protected function getDrushAliasKeys($realm) { $aliases = $this->loadDrushAliasesByRelam($realm); $alias_keys = array_keys($aliases); array_walk($alias_keys, function (&$key) use ($realm) { $key = "$realm.$key"; }); return $alias_keys; }
php
{ "resource": "" }
q12488
DrupalTasks.determineDrushAlias
train
protected function determineDrushAlias($realm, array $options) { if (count($options) > 1) { return $this->askChoiceQuestion( sprintf('Select the %s drush alias that should be used:', $realm), $options, 0 ); } return reset($options) ?: null; }
php
{ "resource": "" }
q12489
DrupalTasks.loadDrushAliasesByRelam
train
protected function loadDrushAliasesByRelam($realm) { static $cached = []; if (empty($cached[$realm])) { $project_root = ProjectX::projectRoot(); if (!file_exists("$project_root/drush")) { return []; } $drush_alias_dir = "$project_root/drush/site-aliases"; if (!file_exists($drush_alias_dir)) { return []; } if (!file_exists("$drush_alias_dir/$realm.aliases.drushrc.php")) { return []; } include_once "$drush_alias_dir/$realm.aliases.drushrc.php"; $cached[$realm] = isset($aliases) ? $aliases : array(); } return $cached[$realm]; }
php
{ "resource": "" }
q12490
MissingCommand.dumpLemmas
train
protected function dumpLemmas(array $lemmas) { // Create a dumpy-dump $content = var_export($lemmas, true); // Decode all keys $content = $this->decodeKey($content); return $this->dumpLangArray("<?php\n\nreturn {$content};"); }
php
{ "resource": "" }
q12491
MissingCommand.saveChanges
train
protected function saveChanges() { $this->line(''); if (count($this->jobs) > 0) { $do = true; if ($this->config('ask_for_value') === false) { $do = ($this->ask('Do you wish to apply these changes now? [yes|no]') === 'yes'); } if ($do === true) { $this->line(''); $this->line('Save files:'); foreach ($this->jobs as $file_lang_path => $file_content) { file_put_contents($file_lang_path, $file_content); $this->line(" <info>" . $this->getShortPath($file_lang_path)); } $this->line(''); $this->info('Process done!'); } else { $this->comment('Process aborted. No file have been changed.'); } } else { if ($this->has_new && ($this->is_dirty === true || $this->option('force')) === false) { $this->comment('Not all translations are up to date.'); } else { $this->info('All translations are up to date.'); } } $this->line(''); }
php
{ "resource": "" }
q12492
MissingCommand.processObsoleteLemmas
train
protected function processObsoleteLemmas($family, array $old_lemmas = [], array $new_lemmas = []) { // Get obsolete lemmas $lemmas = array_diff_key($old_lemmas, $new_lemmas); // Process all of the obsolete lemmas if (count($lemmas) > 0) { // Sort lemmas by key ksort($lemmas); // Remove all dynamic fields foreach ($lemmas as $key => $value) { $id = $this->decodeKey($key); // Remove any keys that can never be obsolete if ($this->neverObsolete($id)) { Arr::set($this->final_lemmas, $key, str_replace('%LEMMA', $value, $this->option('new-value')) ); unset($lemmas[$key]); } } } // Check for obsolete lemmas if (count($lemmas) > 0) { $this->is_dirty = true; $this->comment(" " . count($lemmas) . " obsolete strings (will be deleted)"); if ($this->option('verbose')) { foreach ($lemmas as $key => $value) { $this->line(" <comment>" . $this->decodeKey($key) . "</comment>"); } } } }
php
{ "resource": "" }
q12493
MissingCommand.processExistingLemmas
train
protected function processExistingLemmas($family, array $old_lemmas = [], array $new_lemmas = []) { // Get existing lemmas $lemmas = array_intersect_key($old_lemmas, $new_lemmas); if (count($lemmas) > 0) { // Sort lemmas by key ksort($lemmas); if ($this->option('verbose')) { $this->line(" " . count($lemmas) . " already translated strings"); } foreach ($lemmas as $key => $value) { Arr::set( $this->final_lemmas, $key, $value ); } return true; } return false; }
php
{ "resource": "" }
q12494
MissingCommand.processNewLemmas
train
protected function processNewLemmas($family, array $new_lemmas = [], array $old_lemmas = []) { // Get new lemmas $lemmas = array_diff_key($new_lemmas, $old_lemmas); // Remove any never obsolete values if ($this->config('ask_for_value') === false) { $lemmas = array_filter($lemmas, function ($key) { if ($this->neverObsolete($key)) { $this->line(" <comment>Manually add:</comment> <info>{$key}</info>"); $this->has_new = true; return false; } return true; }, ARRAY_FILTER_USE_KEY); } // Process new lemmas if (count($lemmas) > 0) { $this->is_dirty = true; $this->has_new = true; // Sort lemmas by key ksort($lemmas); $this->info(" " . count($lemmas) . " new strings to translate"); foreach ($lemmas as $key => $path) { $value = $this->decodeKey($key); // Only ask for feedback when it's not a dirty check if ($this->option('dirty') === false && $this->config('ask_for_value') === true) { $value = $this->ask( "{$family}.{$value}", $this->createSuggestion($value) ); } if ($this->option('verbose')) { $this->line(" <info>{$key}</info> in " . $this->getShortPath($path)); } Arr::set($this->final_lemmas, $key, str_replace('%LEMMA', $value, $this->option('new-value')) ); } return true; } return false; }
php
{ "resource": "" }
q12495
MissingCommand.getLanguages
train
protected function getLanguages(array $paths = []) { // Get language path $dir_lang = $this->getLangPath(); // Only use the default locale if ($this->config('default_locale_only')) { return [ $this->default_locale => "{$dir_lang}/{$this->default_locale}", ]; } // Get all language paths foreach (glob("{$dir_lang}/*", GLOB_ONLYDIR) as $path) { $paths[basename($path)] = $path; } return $paths; }
php
{ "resource": "" }
q12496
MissingCommand.createSuggestion
train
protected function createSuggestion($value) { // Strip the obsolete regex keys if (empty($this->obsolete_regex) === false) { $value = preg_replace("/^({$this->obsolete_regex})\./i", '', $value); } return Str::title(str_replace('_', ' ', $value)); }
php
{ "resource": "" }
q12497
MissingCommand.neverObsolete
train
protected function neverObsolete($value) { // Remove any keys that can never be obsolete foreach ($this->config('never_obsolete_keys', []) as $remove) { $remove = "{$remove}."; if (substr($value, 0, strlen($remove)) === $remove || strpos($value, ".{$remove}") !== false ) { return true; } } return false; }
php
{ "resource": "" }
q12498
MissingCommand.getLemmasStructured
train
protected function getLemmasStructured(array $structured = []) { foreach ($this->getLemmas() as $key => $value) { // Get the lemma family $family = substr($key, 0, strpos($key, '.')); // Check key against the ignore list if (in_array($family, $this->config('ignore_lang_files', []))) { if ($this->option('verbose')) { $this->line(''); $this->info(" ! Skip lang file '{$family}' !"); } continue; } // Sanity check if (strpos($key, '.') === false) { $this->line(' <error>' . $key . '</error> in file <comment>' . $this->getShortPath($value) . '</comment> <error>will not be included because it has no parent</error>'); } else { Arr::set( $structured, $this->encodeKey($key), $value ); } } return $structured; }
php
{ "resource": "" }
q12499
MissingCommand.getLemmas
train
protected function getLemmas(array $lemmas = []) { // Get folders $folders = $this->getPath($this->config('folders', [])); foreach ($folders as $path) { if ($this->option('verbose')) { $this->line(' <info>' . $path . '</info>'); } foreach ($this->getPhpFiles($path) as $php_file_path => $dumb) { $lemma = []; foreach ($this->extractTranslationFromFile($php_file_path) as $k => $v) { $real_value = eval("return $k;"); $lemma[$real_value] = $php_file_path; } $lemmas = array_merge($lemmas, $lemma); } } if (count($lemmas) === 0) { $this->comment("No lemma have been found in the code."); $this->line("In these directories:"); foreach ($this->config('folders', []) as $path) { $path = $this->getPath($path); $this->line(" {$path}"); } $this->line("For these functions/methods:"); foreach ($this->config('trans_methods', []) as $k => $v) { $this->line(" {$k}"); } die(); } $this->line((count($lemmas) > 1) ? count($lemmas) . " lemmas have been found in the code" : "1 lemma has been found in the code"); if ($this->option('verbose')) { foreach ($lemmas as $key => $value) { if (strpos($key, '.') !== false) { $this->line(' <info>' . $key . '</info> in file <comment>' . $this->getShortPath($value) . '</comment>'); } } } return $lemmas; }
php
{ "resource": "" }