_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q241300
SuggestedPackagesReporter.addPackage
validation
public function addPackage($source, $target, $reason) { $this->suggestedPackages[] = array( 'source' => $source, 'target' => $target, 'reason' => $reason, ); return $this; }
php
{ "resource": "" }
q241301
SuggestedPackagesReporter.addSuggestionsFromPackage
validation
public function addSuggestionsFromPackage(PackageInterface $package) { $source = $package->getPrettyName(); foreach ($package->getSuggests() as $target => $reason) { $this->addPackage( $source, $target, $reason ); } return $this; }
php
{ "resource": "" }
q241302
Filesystem.isDirEmpty
validation
public function isDirEmpty($dir) { $finder = Finder::create() ->ignoreVCS(false) ->ignoreDotFiles(false) ->depth(0) ->in($dir); return count($finder) === 0; }
php
{ "resource": "" }
q241303
Filesystem.unlink
validation
public function unlink($path) { $unlinked = @$this->unlinkImplementation($path); if (!$unlinked) { // retry after a bit on windows since it tends to be touchy with mass removals if (Platform::isWindows()) { usleep(350000); $unlinked = @$this->unlinkImplementation($path); } if (!$unlinked) { $error = error_get_last(); $message = 'Could not delete '.$path.': ' . @$error['message']; if (Platform::isWindows()) { $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed"; } throw new \RuntimeException($message); } } return true; }
php
{ "resource": "" }
q241304
Filesystem.rmdir
validation
public function rmdir($path) { $deleted = @rmdir($path); if (!$deleted) { // retry after a bit on windows since it tends to be touchy with mass removals if (Platform::isWindows()) { usleep(350000); $deleted = @rmdir($path); } if (!$deleted) { $error = error_get_last(); $message = 'Could not delete '.$path.': ' . @$error['message']; if (Platform::isWindows()) { $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed"; } throw new \RuntimeException($message); } } return true; }
php
{ "resource": "" }
q241305
Filesystem.size
validation
public function size($path) { if (!file_exists($path)) { throw new \RuntimeException("$path does not exist."); } if (is_dir($path)) { return $this->directorySize($path); } return filesize($path); }
php
{ "resource": "" }
q241306
Filesystem.normalizePath
validation
public function normalizePath($path) { $parts = array(); $path = strtr($path, '\\', '/'); $prefix = ''; $absolute = false; // extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive: if (preg_match('{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix', $path, $match)) { $prefix = $match[1]; $path = substr($path, strlen($prefix)); } if (substr($path, 0, 1) === '/') { $absolute = true; $path = substr($path, 1); } $up = false; foreach (explode('/', $path) as $chunk) { if ('..' === $chunk && ($absolute || $up)) { array_pop($parts); $up = !(empty($parts) || '..' === end($parts)); } elseif ('.' !== $chunk && '' !== $chunk) { $parts[] = $chunk; $up = '..' !== $chunk; } } return $prefix.($absolute ? '/' : '').implode('/', $parts); }
php
{ "resource": "" }
q241307
Filesystem.isSymlinkedDirectory
validation
public function isSymlinkedDirectory($directory) { if (!is_dir($directory)) { return false; } $resolved = $this->resolveSymlinkedDirectorySymlink($directory); return is_link($resolved); }
php
{ "resource": "" }
q241308
Filesystem.resolveSymlinkedDirectorySymlink
validation
private function resolveSymlinkedDirectorySymlink($pathname) { if (!is_dir($pathname)) { return $pathname; } $resolved = rtrim($pathname, '/'); if (!strlen($resolved)) { return $pathname; } return $resolved; }
php
{ "resource": "" }
q241309
Filesystem.junction
validation
public function junction($target, $junction) { if (!Platform::isWindows()) { throw new \LogicException(sprintf('Function %s is not available on non-Windows platform', __CLASS__)); } if (!is_dir($target)) { throw new IOException(sprintf('Cannot junction to "%s" as it is not a directory.', $target), 0, null, $target); } $cmd = sprintf( 'mklink /J %s %s', ProcessExecutor::escape(str_replace('/', DIRECTORY_SEPARATOR, $junction)), ProcessExecutor::escape(realpath($target)) ); if ($this->getProcess()->execute($cmd, $output) !== 0) { throw new IOException(sprintf('Failed to create junction to "%s" at "%s".', $target, $junction), 0, null, $target); } clearstatcache(true, $junction); }
php
{ "resource": "" }
q241310
Filesystem.removeJunction
validation
public function removeJunction($junction) { if (!Platform::isWindows()) { return false; } $junction = rtrim(str_replace('/', DIRECTORY_SEPARATOR, $junction), DIRECTORY_SEPARATOR); if (!$this->isJunction($junction)) { throw new IOException(sprintf('%s is not a junction and thus cannot be removed as one', $junction)); } return $this->rmdir($junction); }
php
{ "resource": "" }
q241311
AutoloadGenerator.createLoader
validation
public function createLoader(array $autoloads) { $loader = new ClassLoader(); if (isset($autoloads['psr-0'])) { foreach ($autoloads['psr-0'] as $namespace => $path) { $loader->add($namespace, $path); } } if (isset($autoloads['psr-4'])) { foreach ($autoloads['psr-4'] as $namespace => $path) { $loader->addPsr4($namespace, $path); } } if (isset($autoloads['classmap'])) { $blacklist = null; if (!empty($autoloads['exclude-from-classmap'])) { $blacklist = '{(' . implode('|', $autoloads['exclude-from-classmap']) . ')}'; } foreach ($autoloads['classmap'] as $dir) { try { $loader->addClassMap($this->generateClassMap($dir, $blacklist, null, false)); } catch (\RuntimeException $e) { $this->io->writeError('<warning>'.$e->getMessage().'</warning>'); } } } return $loader; }
php
{ "resource": "" }
q241312
AutoloadGenerator.filterPackageMap
validation
protected function filterPackageMap(array $packageMap, PackageInterface $mainPackage) { $packages = array(); $include = array(); foreach ($packageMap as $item) { $package = $item[0]; $name = $package->getName(); $packages[$name] = $package; } $add = function (PackageInterface $package) use (&$add, $packages, &$include) { foreach ($package->getRequires() as $link) { $target = $link->getTarget(); if (!isset($include[$target])) { $include[$target] = true; if (isset($packages[$target])) { $add($packages[$target]); } } } }; $add($mainPackage); return array_filter( $packageMap, function ($item) use ($include) { $package = $item[0]; foreach ($package->getNames() as $name) { if (isset($include[$name])) { return true; } } return false; } ); }
php
{ "resource": "" }
q241313
Bitbucket.authorizeOAuth
validation
public function authorizeOAuth($originUrl) { if ($originUrl !== 'bitbucket.org') { return false; } // if available use token from git config if (0 === $this->process->execute('git config bitbucket.accesstoken', $output)) { $this->io->setAuthentication($originUrl, 'x-token-auth', trim($output)); return true; } return false; }
php
{ "resource": "" }
q241314
Bitbucket.authorizeOAuthInteractively
validation
public function authorizeOAuthInteractively($originUrl, $message = null) { if ($message) { $this->io->writeError($message); } $url = 'https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html'; $this->io->writeError(sprintf('Follow the instructions on %s', $url)); $this->io->writeError(sprintf('to create a consumer. It will be stored in "%s" for future use by Composer.', $this->config->getAuthConfigSource()->getName())); $this->io->writeError('Ensure you enter a "Callback URL" (http://example.com is fine) or it will not be possible to create an Access Token (this callback url will not be used by composer)'); $consumerKey = trim($this->io->askAndHideAnswer('Consumer Key (hidden): ')); if (!$consumerKey) { $this->io->writeError('<warning>No consumer key given, aborting.</warning>'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org <consumer-key> <consumer-secret>"'); return false; } $consumerSecret = trim($this->io->askAndHideAnswer('Consumer Secret (hidden): ')); if (!$consumerSecret) { $this->io->writeError('<warning>No consumer secret given, aborting.</warning>'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org <consumer-key> <consumer-secret>"'); return false; } $this->io->setAuthentication($originUrl, $consumerKey, $consumerSecret); if (!$this->requestAccessToken($originUrl)) { return false; } // store value in user config $this->storeInAuthConfig($originUrl, $consumerKey, $consumerSecret); // Remove conflicting basic auth credentials (if available) $this->config->getAuthConfigSource()->removeConfigSetting('http-basic.' . $originUrl); $this->io->writeError('<info>Consumer stored successfully.</info>'); return true; }
php
{ "resource": "" }
q241315
Bitbucket.requestToken
validation
public function requestToken($originUrl, $consumerKey, $consumerSecret) { if (!empty($this->token) || $this->getTokenFromConfig($originUrl)) { return $this->token['access_token']; } $this->io->setAuthentication($originUrl, $consumerKey, $consumerSecret); if (!$this->requestAccessToken($originUrl)) { return ''; } $this->storeInAuthConfig($originUrl, $consumerKey, $consumerSecret); return $this->token['access_token']; }
php
{ "resource": "" }
q241316
RuleWatchChain.seek
validation
public function seek($offset) { $this->rewind(); for ($i = 0; $i < $offset; $i++, $this->next()); }
php
{ "resource": "" }
q241317
RuleWatchChain.remove
validation
public function remove() { $offset = $this->key(); $this->offsetUnset($offset); $this->seek($offset); }
php
{ "resource": "" }
q241318
BaseDependencyCommand.configure
validation
protected function configure() { $this->setDefinition(array( new InputArgument(self::ARGUMENT_PACKAGE, InputArgument::REQUIRED, 'Package to inspect'), new InputArgument(self::ARGUMENT_CONSTRAINT, InputArgument::OPTIONAL, 'Optional version constraint', '*'), new InputOption(self::OPTION_RECURSIVE, 'r', InputOption::VALUE_NONE, 'Recursively resolves up to the root package'), new InputOption(self::OPTION_TREE, 't', InputOption::VALUE_NONE, 'Prints the results as a nested tree'), )); }
php
{ "resource": "" }
q241319
RepositoryManager.findPackage
validation
public function findPackage($name, $constraint) { foreach ($this->repositories as $repository) { /** @var RepositoryInterface $repository */ if ($package = $repository->findPackage($name, $constraint)) { return $package; } } return null; }
php
{ "resource": "" }
q241320
RepositoryManager.createRepository
validation
public function createRepository($type, $config, $name = null) { if (!isset($this->repositoryClasses[$type])) { throw new \InvalidArgumentException('Repository type is not registered: '.$type); } if (isset($config['packagist']) && false === $config['packagist']) { $this->io->writeError('<warning>Repository "'.$name.'" ('.json_encode($config).') has a packagist key which should be in its own repository definition</warning>'); } $class = $this->repositoryClasses[$type]; $reflMethod = new \ReflectionMethod($class, '__construct'); $params = $reflMethod->getParameters(); if (isset($params[4]) && $params[4]->getClass() && $params[4]->getClass()->getName() === 'Composer\Util\RemoteFilesystem') { return new $class($config, $this->io, $this->config, $this->eventDispatcher, $this->rfs); } return new $class($config, $this->io, $this->config, $this->eventDispatcher); }
php
{ "resource": "" }
q241321
Silencer.suppress
validation
public static function suppress($mask = null) { if (!isset($mask)) { $mask = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT; } $old = error_reporting(); self::$stack[] = $old; error_reporting($old & ~$mask); return $old; }
php
{ "resource": "" }
q241322
Silencer.call
validation
public static function call($callable /*, ...$parameters */) { try { self::suppress(); $result = call_user_func_array($callable, array_slice(func_get_args(), 1)); self::restore(); return $result; } catch (\Exception $e) { // Use a finally block for this when requirements are raised to PHP 5.5 self::restore(); throw $e; } }
php
{ "resource": "" }
q241323
PearPackageExtractor.extractTo
validation
public function extractTo($target, array $roles = array('php' => '/', 'script' => '/bin'), $vars = array()) { $extractionPath = $target.'/tarball'; try { $archive = new \PharData($this->file); $archive->extractTo($extractionPath, null, true); if (!is_file($this->combine($extractionPath, '/package.xml'))) { throw new \RuntimeException('Invalid PEAR package. It must contain package.xml file.'); } $fileCopyActions = $this->buildCopyActions($extractionPath, $roles, $vars); $this->copyFiles($fileCopyActions, $extractionPath, $target, $roles, $vars); $this->filesystem->removeDirectory($extractionPath); } catch (\Exception $exception) { throw new \UnexpectedValueException(sprintf('Failed to extract PEAR package %s to %s. Reason: %s', $this->file, $target, $exception->getMessage()), 0, $exception); } }
php
{ "resource": "" }
q241324
PearPackageExtractor.copyFiles
validation
private function copyFiles($files, $source, $target, $roles, $vars) { foreach ($files as $file) { $from = $this->combine($source, $file['from']); $to = $this->combine($target, $roles[$file['role']]); $to = $this->combine($to, $file['to']); $tasks = $file['tasks']; $this->copyFile($from, $to, $tasks, $vars); } }
php
{ "resource": "" }
q241325
Platform.expandPath
validation
public static function expandPath($path) { if (preg_match('#^~[\\/]#', $path)) { return self::getUserDirectory() . substr($path, 1); } return preg_replace_callback('#^(\$|(?P<percent>%))(?P<var>\w++)(?(percent)%)(?P<path>.*)#', function ($matches) { // Treat HOME as an alias for USERPROFILE on Windows for legacy reasons if (Platform::isWindows() && $matches['var'] == 'HOME') { return (getenv('HOME') ?: getenv('USERPROFILE')) . $matches['path']; } return getenv($matches['var']) . $matches['path']; }, $path); }
php
{ "resource": "" }
q241326
ArchiveManager.getPackageFilename
validation
public function getPackageFilename(PackageInterface $package) { $nameParts = array(preg_replace('#[^a-z0-9-_]#i', '-', $package->getName())); if (preg_match('{^[a-f0-9]{40}$}', $package->getDistReference())) { array_push($nameParts, $package->getDistReference(), $package->getDistType()); } else { array_push($nameParts, $package->getPrettyVersion(), $package->getDistReference()); } if ($package->getSourceReference()) { $nameParts[] = substr(sha1($package->getSourceReference()), 0, 6); } $name = implode('-', array_filter($nameParts, function ($p) { return !empty($p); })); return str_replace('/', '-', $name); }
php
{ "resource": "" }
q241327
ArchiveManager.archive
validation
public function archive(PackageInterface $package, $format, $targetDir, $fileName = null, $ignoreFilters = false) { if (empty($format)) { throw new \InvalidArgumentException('Format must be specified'); } // Search for the most appropriate archiver $usableArchiver = null; foreach ($this->archivers as $archiver) { if ($archiver->supports($format, $package->getSourceType())) { $usableArchiver = $archiver; break; } } // Checks the format/source type are supported before downloading the package if (null === $usableArchiver) { throw new \RuntimeException(sprintf('No archiver found to support %s format', $format)); } $filesystem = new Filesystem(); if (null === $fileName) { $packageName = $this->getPackageFilename($package); } else { $packageName = $fileName; } // Archive filename $filesystem->ensureDirectoryExists($targetDir); $target = realpath($targetDir).'/'.$packageName.'.'.$format; $filesystem->ensureDirectoryExists(dirname($target)); if (!$this->overwriteFiles && file_exists($target)) { return $target; } if ($package instanceof RootPackageInterface) { $sourcePath = realpath('.'); } else { // Directory used to download the sources $sourcePath = sys_get_temp_dir().'/composer_archive'.uniqid(); $filesystem->ensureDirectoryExists($sourcePath); try { // Download sources $this->downloadManager->download($package, $sourcePath); } catch (\Exception $e) { $filesystem->removeDirectory($sourcePath); throw $e; } // Check exclude from downloaded composer.json if (file_exists($composerJsonPath = $sourcePath.'/composer.json')) { $jsonFile = new JsonFile($composerJsonPath); $jsonData = $jsonFile->read(); if (!empty($jsonData['archive']['exclude'])) { $package->setArchiveExcludes($jsonData['archive']['exclude']); } } } // Create the archive $tempTarget = sys_get_temp_dir().'/composer_archive'.uniqid().'.'.$format; $filesystem->ensureDirectoryExists(dirname($tempTarget)); $archivePath = $usableArchiver->archive($sourcePath, $tempTarget, $format, $package->getArchiveExcludes(), $ignoreFilters); $filesystem->rename($archivePath, $target); // cleanup temporary download if (!$package instanceof RootPackageInterface) { $filesystem->removeDirectory($sourcePath); } $filesystem->remove($tempTarget); return $target; }
php
{ "resource": "" }
q241328
StrictConfirmationQuestion.getDefaultNormalizer
validation
private function getDefaultNormalizer() { $default = $this->getDefault(); $trueRegex = $this->trueAnswerRegex; $falseRegex = $this->falseAnswerRegex; return function ($answer) use ($default, $trueRegex, $falseRegex) { if (is_bool($answer)) { return $answer; } if (empty($answer) && !empty($default)) { return $default; } if (preg_match($trueRegex, $answer)) { return true; } if (preg_match($falseRegex, $answer)) { return false; } return null; }; }
php
{ "resource": "" }
q241329
Rule2Literals.equals
validation
public function equals(Rule $rule) { // specialized fast-case if ($rule instanceof self) { if ($this->literal1 !== $rule->literal1) { return false; } if ($this->literal2 !== $rule->literal2) { return false; } return true; } $literals = $rule->getLiterals(); if (2 != count($literals)) { return false; } if ($this->literal1 !== $literals[0]) { return false; } if ($this->literal2 !== $literals[1]) { return false; } return true; }
php
{ "resource": "" }
q241330
JsonFile.write
validation
public function write(array $hash, $options = 448) { $dir = dirname($this->path); if (!is_dir($dir)) { if (file_exists($dir)) { throw new \UnexpectedValueException( $dir.' exists and is not a directory.' ); } if (!@mkdir($dir, 0777, true)) { throw new \UnexpectedValueException( $dir.' does not exist and could not be created.' ); } } $retries = 3; while ($retries--) { try { file_put_contents($this->path, static::encode($hash, $options). ($options & self::JSON_PRETTY_PRINT ? "\n" : '')); break; } catch (\Exception $e) { if ($retries) { usleep(500000); continue; } throw $e; } } }
php
{ "resource": "" }
q241331
JsonFile.throwEncodeError
validation
private static function throwEncodeError($code) { switch ($code) { case JSON_ERROR_DEPTH: $msg = 'Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $msg = 'Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $msg = 'Unexpected control character found'; break; case JSON_ERROR_UTF8: $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: $msg = 'Unknown error'; } throw new \RuntimeException('JSON encoding failed: '.$msg); }
php
{ "resource": "" }
q241332
JsonFile.parseJson
validation
public static function parseJson($json, $file = null) { if (null === $json) { return; } $data = json_decode($json, true); if (null === $data && JSON_ERROR_NONE !== json_last_error()) { self::validateSyntax($json, $file); } return $data; }
php
{ "resource": "" }
q241333
JsonFile.validateSyntax
validation
protected static function validateSyntax($json, $file = null) { $parser = new JsonParser(); $result = $parser->lint($json); if (null === $result) { if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) { throw new \UnexpectedValueException('"'.$file.'" is not UTF-8, could not parse as JSON'); } return true; } throw new ParsingException('"'.$file.'" does not contain valid JSON'."\n".$result->getMessage(), $result->getDetails()); }
php
{ "resource": "" }
q241334
BaseExcludeFilter.filter
validation
public function filter($relativePath, $exclude) { foreach ($this->excludePatterns as $patternData) { list($pattern, $negate, $stripLeadingSlash) = $patternData; if ($stripLeadingSlash) { $path = substr($relativePath, 1); } else { $path = $relativePath; } if (preg_match($pattern, $path)) { $exclude = !$negate; } } return $exclude; }
php
{ "resource": "" }
q241335
InitCommand.hasVendorIgnore
validation
protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor') { if (!file_exists($ignoreFile)) { return false; } $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor)); $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES); foreach ($lines as $line) { if (preg_match($pattern, $line)) { return true; } } return false; }
php
{ "resource": "" }
q241336
InitCommand.findBestVersionAndNameForPackage
validation
private function findBestVersionAndNameForPackage(InputInterface $input, $name, $phpVersion, $preferredStability = 'stable', $requiredVersion = null, $minimumStability = null) { // find the latest version allowed in this pool $versionSelector = new VersionSelector($this->getPool($input, $minimumStability)); $ignorePlatformReqs = $input->hasOption('ignore-platform-reqs') && $input->getOption('ignore-platform-reqs'); // ignore phpVersion if platform requirements are ignored if ($ignorePlatformReqs) { $phpVersion = null; } $package = $versionSelector->findBestCandidate($name, $requiredVersion, $phpVersion, $preferredStability); if (!$package) { // platform packages can not be found in the pool in versions other than the local platform's has // so if platform reqs are ignored we just take the user's word for it if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) { return array($name, $requiredVersion ?: '*'); } // Check whether the PHP version was the problem if ($phpVersion && $versionSelector->findBestCandidate($name, $requiredVersion, null, $preferredStability)) { throw new \InvalidArgumentException(sprintf( 'Package %s at version %s has a PHP requirement incompatible with your PHP version (%s)', $name, $requiredVersion, $phpVersion )); } // Check whether the required version was the problem if ($requiredVersion && $versionSelector->findBestCandidate($name, null, $phpVersion, $preferredStability)) { throw new \InvalidArgumentException(sprintf( 'Could not find package %s in a version matching %s', $name, $requiredVersion )); } // Check whether the PHP version was the problem if ($phpVersion && $versionSelector->findBestCandidate($name)) { throw new \InvalidArgumentException(sprintf( 'Could not find package %s in any version matching your PHP version (%s)', $name, $phpVersion )); } // Check for similar names/typos $similar = $this->findSimilar($name); if ($similar) { // Check whether the minimum stability was the problem but the package exists if ($requiredVersion === null && in_array($name, $similar, true)) { throw new \InvalidArgumentException(sprintf( 'Could not find a version of package %s matching your minimum-stability (%s). Require it with an explicit version constraint allowing its desired stability.', $name, $this->getMinimumStability($input) )); } throw new \InvalidArgumentException(sprintf( "Could not find package %s.\n\nDid you mean " . (count($similar) > 1 ? 'one of these' : 'this') . "?\n %s", $name, implode("\n ", $similar) )); } throw new \InvalidArgumentException(sprintf( 'Could not find a matching version of package %s. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (%s).', $name, $this->getMinimumStability($input) )); } return array( $package->getPrettyName(), $versionSelector->findRecommendedRequireVersion($package), ); }
php
{ "resource": "" }
q241337
ChannelReader.read
validation
public function read($url) { $xml = $this->requestXml($url, "/channel.xml"); $channelName = (string) $xml->name; $channelAlias = (string) $xml->suggestedalias; $supportedVersions = array_keys($this->readerMap); $selectedRestVersion = $this->selectRestVersion($xml, $supportedVersions); if (!$selectedRestVersion) { throw new \UnexpectedValueException(sprintf('PEAR repository %s does not supports any of %s protocols.', $url, implode(', ', $supportedVersions))); } $reader = $this->readerMap[$selectedRestVersion['version']]; $packageDefinitions = $reader->read($selectedRestVersion['baseUrl']); return new ChannelInfo($channelName, $channelAlias, $packageDefinitions); }
php
{ "resource": "" }
q241338
ChannelReader.selectRestVersion
validation
private function selectRestVersion($channelXml, $supportedVersions) { $channelXml->registerXPathNamespace('ns', self::CHANNEL_NS); foreach ($supportedVersions as $version) { $xpathTest = "ns:servers/ns:*/ns:rest/ns:baseurl[@type='{$version}']"; $testResult = $channelXml->xpath($xpathTest); foreach ($testResult as $result) { // Choose first https:// option. $result = (string) $result; if (preg_match('{^https://}i', $result)) { return array('version' => $version, 'baseUrl' => $result); } } // Fallback to non-https if it does not exist. if (count($testResult) > 0) { return array('version' => $version, 'baseUrl' => (string) $testResult[0]); } } return null; }
php
{ "resource": "" }
q241339
ClassLoader.add
validation
public function add($prefix, $paths, $prepend = false) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } }
php
{ "resource": "" }
q241340
ClassLoader.addPsr4
validation
public function addPsr4($prefix, $paths, $prepend = false) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } }
php
{ "resource": "" }
q241341
ClassLoader.set
validation
public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } }
php
{ "resource": "" }
q241342
ClassLoader.setPsr4
validation
public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } }
php
{ "resource": "" }
q241343
ClassLoader.findFile
validation
public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; }
php
{ "resource": "" }
q241344
DefaultPolicy.pruneToHighestPriorityOrInstalled
validation
protected function pruneToHighestPriorityOrInstalled(Pool $pool, array $installedMap, array $literals) { $selected = array(); $priority = null; foreach ($literals as $literal) { $package = $pool->literalToPackage($literal); if (isset($installedMap[$package->id])) { $selected[] = $literal; continue; } if (null === $priority) { $priority = $this->getPriority($pool, $package); } if ($this->getPriority($pool, $package) != $priority) { break; } $selected[] = $literal; } return $selected; }
php
{ "resource": "" }
q241345
GitHub.isRateLimited
validation
public function isRateLimited(array $headers) { foreach ($headers as $header) { if (preg_match('{^X-RateLimit-Remaining: *0$}i', trim($header))) { return true; } } return false; }
php
{ "resource": "" }
q241346
RuleWatchNode.watch2OnHighest
validation
public function watch2OnHighest(Decisions $decisions) { $literals = $this->rule->getLiterals(); // if there are only 2 elements, both are being watched anyway if (count($literals) < 3) { return; } $watchLevel = 0; foreach ($literals as $literal) { $level = $decisions->decisionLevel($literal); if ($level > $watchLevel) { $this->watch2 = $literal; $watchLevel = $level; } } }
php
{ "resource": "" }
q241347
RuleWatchNode.moveWatch
validation
public function moveWatch($from, $to) { if ($this->watch1 == $from) { $this->watch1 = $to; } else { $this->watch2 = $to; } }
php
{ "resource": "" }
q241348
Config.prohibitUrlByConfig
validation
public function prohibitUrlByConfig($url, IOInterface $io = null) { // Return right away if the URL is malformed or custom (see issue #5173) if (false === filter_var($url, FILTER_VALIDATE_URL)) { return; } // Extract scheme and throw exception on known insecure protocols $scheme = parse_url($url, PHP_URL_SCHEME); if (in_array($scheme, array('http', 'git', 'ftp', 'svn'))) { if ($this->get('secure-http')) { throw new TransportException("Your configuration does not allow connections to $url. See https://getcomposer.org/doc/06-config.md#secure-http for details."); } elseif ($io) { $host = parse_url($url, PHP_URL_HOST); if (!isset($this->warnedHosts[$host])) { $io->writeError("<warning>Warning: Accessing $host over $scheme which is an insecure protocol.</warning>"); } $this->warnedHosts[$host] = true; } } }
php
{ "resource": "" }
q241349
PlatformRepository.addExtension
validation
private function addExtension($name, $prettyVersion) { $extraDescription = null; try { $version = $this->versionParser->normalize($prettyVersion); } catch (\UnexpectedValueException $e) { $extraDescription = ' (actual version: '.$prettyVersion.')'; if (preg_match('{^(\d+\.\d+\.\d+(?:\.\d+)?)}', $prettyVersion, $match)) { $prettyVersion = $match[1]; } else { $prettyVersion = '0'; } $version = $this->versionParser->normalize($prettyVersion); } $packageName = $this->buildPackageName($name); $ext = new CompletePackage($packageName, $version, $prettyVersion); $ext->setDescription('The '.$name.' PHP extension'.$extraDescription); $this->addPackage($ext); }
php
{ "resource": "" }
q241350
Git.getVersion
validation
public function getVersion() { if (isset(self::$version)) { return self::$version; } if (0 !== $this->process->execute('git --version', $output)) { return; } if (preg_match('/^git version (\d+(?:\.\d+)+)/m', $output, $matches)) { return self::$version = $matches[1]; } }
php
{ "resource": "" }
q241351
PluginManager.loadInstalledPlugins
validation
public function loadInstalledPlugins() { if ($this->disablePlugins) { return; } $repo = $this->composer->getRepositoryManager()->getLocalRepository(); $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null; if ($repo) { $this->loadRepository($repo); } if ($globalRepo) { $this->loadRepository($globalRepo); } }
php
{ "resource": "" }
q241352
PluginManager.addPlugin
validation
public function addPlugin(PluginInterface $plugin) { $this->io->writeError('Loading plugin '.get_class($plugin), true, IOInterface::DEBUG); $this->plugins[] = $plugin; $plugin->activate($this->composer, $this->io); if ($plugin instanceof EventSubscriberInterface) { $this->composer->getEventDispatcher()->addSubscriber($plugin); } }
php
{ "resource": "" }
q241353
PluginManager.collectDependencies
validation
private function collectDependencies(Pool $pool, array $collected, PackageInterface $package) { $requires = array_merge( $package->getRequires(), $package->getDevRequires() ); foreach ($requires as $requireLink) { $requiredPackage = $this->lookupInstalledPackage($pool, $requireLink); if ($requiredPackage && !isset($collected[$requiredPackage->getName()])) { $collected[$requiredPackage->getName()] = $requiredPackage; $collected = $this->collectDependencies($pool, $collected, $requiredPackage); } } return $collected; }
php
{ "resource": "" }
q241354
PluginManager.getInstallPath
validation
private function getInstallPath(PackageInterface $package, $global = false) { if (!$global) { return $this->composer->getInstallationManager()->getInstallPath($package); } return $this->globalComposer->getInstallationManager()->getInstallPath($package); }
php
{ "resource": "" }
q241355
HomeCommand.openBrowser
validation
private function openBrowser($url) { $url = ProcessExecutor::escape($url); $process = new ProcessExecutor($this->getIO()); if (Platform::isWindows()) { return $process->execute('start "web" explorer "' . $url . '"', $output); } $linux = $process->execute('which xdg-open', $output); $osx = $process->execute('which open', $output); if (0 === $linux) { $process->execute('xdg-open ' . $url, $output); } elseif (0 === $osx) { $process->execute('open ' . $url, $output); } else { $this->getIO()->writeError('No suitable browser opening command found, open yourself: ' . $url); } }
php
{ "resource": "" }
q241356
Svn.execute
validation
public function execute($command, $url, $cwd = null, $path = null, $verbose = false) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); return $this->executeWithAuthRetry($command, $cwd, $url, $path, $verbose); }
php
{ "resource": "" }
q241357
Svn.executeLocal
validation
public function executeLocal($command, $path, $cwd = null, $verbose = false) { // A local command has no remote url return $this->executeWithAuthRetry($command, $cwd, '', $path, $verbose); }
php
{ "resource": "" }
q241358
Svn.getCommand
validation
protected function getCommand($cmd, $url, $path = null) { $cmd = sprintf( '%s %s%s %s', $cmd, '--non-interactive ', $this->getCredentialString(), ProcessExecutor::escape($url) ); if ($path) { $cmd .= ' ' . ProcessExecutor::escape($path); } return $cmd; }
php
{ "resource": "" }
q241359
Svn.getCredentialString
validation
protected function getCredentialString() { if (!$this->hasAuth()) { return ''; } return sprintf( ' %s--username %s --password %s ', $this->getAuthCache(), ProcessExecutor::escape($this->getUsername()), ProcessExecutor::escape($this->getPassword()) ); }
php
{ "resource": "" }
q241360
Svn.getPassword
validation
protected function getPassword() { if ($this->credentials === null) { throw new \LogicException("No svn auth detected."); } return isset($this->credentials['password']) ? $this->credentials['password'] : ''; }
php
{ "resource": "" }
q241361
Svn.hasAuth
validation
protected function hasAuth() { if (null !== $this->hasAuth) { return $this->hasAuth; } if (false === $this->createAuthFromConfig()) { $this->createAuthFromUrl(); } return $this->hasAuth; }
php
{ "resource": "" }
q241362
Svn.createAuthFromConfig
validation
private function createAuthFromConfig() { if (!$this->config->has('http-basic')) { return $this->hasAuth = false; } $authConfig = $this->config->get('http-basic'); $host = parse_url($this->url, PHP_URL_HOST); if (isset($authConfig[$host])) { $this->credentials['username'] = $authConfig[$host]['username']; $this->credentials['password'] = $authConfig[$host]['password']; return $this->hasAuth = true; } return $this->hasAuth = false; }
php
{ "resource": "" }
q241363
Svn.createAuthFromUrl
validation
private function createAuthFromUrl() { $uri = parse_url($this->url); if (empty($uri['user'])) { return $this->hasAuth = false; } $this->credentials['username'] = $uri['user']; if (!empty($uri['pass'])) { $this->credentials['password'] = $uri['pass']; } return $this->hasAuth = true; }
php
{ "resource": "" }
q241364
Svn.binaryVersion
validation
public function binaryVersion() { if (!self::$version) { if (0 === $this->process->execute('svn --version', $output)) { if (preg_match('{(\d+(?:\.\d+)+)}', $output, $match)) { self::$version = $match[1]; } } } return self::$version; }
php
{ "resource": "" }
q241365
ZipDownloader.getErrorMessage
validation
protected function getErrorMessage($retval, $file) { switch ($retval) { case ZipArchive::ER_EXISTS: return sprintf("File '%s' already exists.", $file); case ZipArchive::ER_INCONS: return sprintf("Zip archive '%s' is inconsistent.", $file); case ZipArchive::ER_INVAL: return sprintf("Invalid argument (%s)", $file); case ZipArchive::ER_MEMORY: return sprintf("Malloc failure (%s)", $file); case ZipArchive::ER_NOENT: return sprintf("No such zip file: '%s'", $file); case ZipArchive::ER_NOZIP: return sprintf("'%s' is not a zip archive.", $file); case ZipArchive::ER_OPEN: return sprintf("Can't open zip file: %s", $file); case ZipArchive::ER_READ: return sprintf("Zip read error (%s)", $file); case ZipArchive::ER_SEEK: return sprintf("Zip seek error (%s)", $file); default: return sprintf("'%s' is not a valid zip archive, got error code: %s", $file, $retval); } }
php
{ "resource": "" }
q241366
Pool.whatProvides
validation
public function whatProvides($name, ConstraintInterface $constraint = null, $mustMatchName = false, $bypassFilters = false) { if ($bypassFilters) { return $this->computeWhatProvides($name, $constraint, $mustMatchName, true); } $key = ((int) $mustMatchName).$constraint; if (isset($this->providerCache[$name][$key])) { return $this->providerCache[$name][$key]; } return $this->providerCache[$name][$key] = $this->computeWhatProvides($name, $constraint, $mustMatchName, $bypassFilters); }
php
{ "resource": "" }
q241367
RuleSetGenerator.createRemoveRule
validation
protected function createRemoveRule(PackageInterface $package, $reason, $job) { return new GenericRule(array(-$package->id), $reason, $job['packageName'], $job); }
php
{ "resource": "" }
q241368
LibraryInstaller.ensureBinariesPresence
validation
public function ensureBinariesPresence(PackageInterface $package) { $this->binaryInstaller->installBinaries($package, $this->getInstallPath($package), false); }
php
{ "resource": "" }
q241369
LibraryInstaller.getPackageBasePath
validation
protected function getPackageBasePath(PackageInterface $package) { $installPath = $this->getInstallPath($package); $targetDir = $package->getTargetDir(); if ($targetDir) { return preg_replace('{/*'.str_replace('/', '/+', preg_quote($targetDir)).'/?$}', '', $installPath); } return $installPath; }
php
{ "resource": "" }
q241370
BaseChannelReader.requestContent
validation
protected function requestContent($origin, $path) { $url = rtrim($origin, '/') . '/' . ltrim($path, '/'); $content = $this->rfs->getContents($origin, $url, false); if (!$content) { throw new \UnexpectedValueException('The PEAR channel at ' . $url . ' did not respond.'); } return str_replace('http://pear.php.net/rest/', 'https://pear.php.net/rest/', $content); }
php
{ "resource": "" }
q241371
BaseChannelReader.requestXml
validation
protected function requestXml($origin, $path) { // http://components.ez.no/p/packages.xml is malformed. to read it we must ignore parsing errors. $xml = simplexml_load_string($this->requestContent($origin, $path), "SimpleXMLElement", LIBXML_NOERROR); if (false === $xml) { throw new \UnexpectedValueException(sprintf('The PEAR channel at ' . $origin . ' is broken. (Invalid XML at file `%s`)', $path)); } return $xml; }
php
{ "resource": "" }
q241372
FossilDriver.updateLocalRepo
validation
protected function updateLocalRepo() { $fs = new Filesystem(); $fs->ensureDirectoryExists($this->checkoutDir); if (!is_writable(dirname($this->checkoutDir))) { throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.$this->checkoutDir.'" directory is not writable by the current user.'); } // update the repo if it is a valid fossil repository if (is_file($this->repoFile) && is_dir($this->checkoutDir) && 0 === $this->process->execute('fossil info', $output, $this->checkoutDir)) { if (0 !== $this->process->execute('fossil pull', $output, $this->checkoutDir)) { $this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated ('.$this->process->getErrorOutput().')</error>'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->checkoutDir); $fs->remove($this->repoFile); $fs->ensureDirectoryExists($this->checkoutDir); if (0 !== $this->process->execute(sprintf('fossil clone %s %s', ProcessExecutor::escape($this->url), ProcessExecutor::escape($this->repoFile)), $output)) { $output = $this->process->getErrorOutput(); throw new \RuntimeException('Failed to clone '.$this->url.' to repository ' . $this->repoFile . "\n\n" .$output); } if (0 !== $this->process->execute(sprintf('fossil open %s --nested', ProcessExecutor::escape($this->repoFile)), $output, $this->checkoutDir)) { $output = $this->process->getErrorOutput(); throw new \RuntimeException('Failed to open repository '.$this->repoFile.' in ' . $this->checkoutDir . "\n\n" .$output); } } }
php
{ "resource": "" }
q241373
InstallationManager.disablePlugins
validation
public function disablePlugins() { foreach ($this->installers as $i => $installer) { if (!$installer instanceof PluginInstaller) { continue; } unset($this->installers[$i]); } }
php
{ "resource": "" }
q241374
InstallationManager.getInstaller
validation
public function getInstaller($type) { $type = strtolower($type); if (isset($this->cache[$type])) { return $this->cache[$type]; } foreach ($this->installers as $installer) { if ($installer->supports($type)) { return $this->cache[$type] = $installer; } } throw new \InvalidArgumentException('Unknown installer type: '.$type); }
php
{ "resource": "" }
q241375
InstallationManager.isPackageInstalled
validation
public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { if ($package instanceof AliasPackage) { return $repo->hasPackage($package) && $this->isPackageInstalled($repo, $package->getAliasOf()); } return $this->getInstaller($package->getType())->isInstalled($repo, $package); }
php
{ "resource": "" }
q241376
InstallationManager.ensureBinariesPresence
validation
public function ensureBinariesPresence(PackageInterface $package) { try { $installer = $this->getInstaller($package->getType()); } catch (\InvalidArgumentException $e) { // no installer found for the current package type (@see `getInstaller()`) return; } // if the given installer support installing binaries if ($installer instanceof BinaryPresenceInterface) { $installer->ensureBinariesPresence($package); } }
php
{ "resource": "" }
q241377
InstallationManager.execute
validation
public function execute(RepositoryInterface $repo, OperationInterface $operation) { $method = $operation->getJobType(); $this->$method($repo, $operation); }
php
{ "resource": "" }
q241378
InstallationManager.install
validation
public function install(RepositoryInterface $repo, InstallOperation $operation) { $package = $operation->getPackage(); $installer = $this->getInstaller($package->getType()); $installer->install($repo, $package); $this->markForNotification($package); }
php
{ "resource": "" }
q241379
InstallationManager.update
validation
public function update(RepositoryInterface $repo, UpdateOperation $operation) { $initial = $operation->getInitialPackage(); $target = $operation->getTargetPackage(); $initialType = $initial->getType(); $targetType = $target->getType(); if ($initialType === $targetType) { $installer = $this->getInstaller($initialType); $installer->update($repo, $initial, $target); $this->markForNotification($target); } else { $this->getInstaller($initialType)->uninstall($repo, $initial); $this->getInstaller($targetType)->install($repo, $target); } }
php
{ "resource": "" }
q241380
InstallationManager.uninstall
validation
public function uninstall(RepositoryInterface $repo, UninstallOperation $operation) { $package = $operation->getPackage(); $installer = $this->getInstaller($package->getType()); $installer->uninstall($repo, $package); }
php
{ "resource": "" }
q241381
InstallationManager.markAliasInstalled
validation
public function markAliasInstalled(RepositoryInterface $repo, MarkAliasInstalledOperation $operation) { $package = $operation->getPackage(); if (!$repo->hasPackage($package)) { $repo->addPackage(clone $package); } }
php
{ "resource": "" }
q241382
InstallationManager.markAliasUninstalled
validation
public function markAliasUninstalled(RepositoryInterface $repo, MarkAliasUninstalledOperation $operation) { $package = $operation->getPackage(); $repo->removePackage($package); }
php
{ "resource": "" }
q241383
InstallationManager.getInstallPath
validation
public function getInstallPath(PackageInterface $package) { $installer = $this->getInstaller($package->getType()); return $installer->getInstallPath($package); }
php
{ "resource": "" }
q241384
StreamContextFactory.fixHttpHeaderField
validation
private static function fixHttpHeaderField($header) { if (!is_array($header)) { $header = explode("\r\n", $header); } uasort($header, function ($el) { return stripos($el, 'content-type') === 0 ? 1 : -1; }); return $header; }
php
{ "resource": "" }
q241385
RuleWatchGraph.insert
validation
public function insert(RuleWatchNode $node) { if ($node->getRule()->isAssertion()) { return; } foreach (array($node->watch1, $node->watch2) as $literal) { if (!isset($this->watchChains[$literal])) { $this->watchChains[$literal] = new RuleWatchChain; } $this->watchChains[$literal]->unshift($node); } }
php
{ "resource": "" }
q241386
RuleWatchGraph.propagateLiteral
validation
public function propagateLiteral($decidedLiteral, $level, $decisions) { // we invert the decided literal here, example: // A was decided => (-A|B) now requires B to be true, so we look for // rules which are fulfilled by -A, rather than A. $literal = -$decidedLiteral; if (!isset($this->watchChains[$literal])) { return null; } $chain = $this->watchChains[$literal]; $chain->rewind(); while ($chain->valid()) { $node = $chain->current(); $otherWatch = $node->getOtherWatch($literal); if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) { $ruleLiterals = $node->getRule()->getLiterals(); $alternativeLiterals = array_filter($ruleLiterals, function ($ruleLiteral) use ($literal, $otherWatch, $decisions) { return $literal !== $ruleLiteral && $otherWatch !== $ruleLiteral && !$decisions->conflict($ruleLiteral); }); if ($alternativeLiterals) { reset($alternativeLiterals); $this->moveWatch($literal, current($alternativeLiterals), $node); continue; } if ($decisions->conflict($otherWatch)) { return $node->getRule(); } $decisions->decide($otherWatch, $level, $node->getRule()); } $chain->next(); } return null; }
php
{ "resource": "" }
q241387
RuleWatchGraph.moveWatch
validation
protected function moveWatch($fromLiteral, $toLiteral, $node) { if (!isset($this->watchChains[$toLiteral])) { $this->watchChains[$toLiteral] = new RuleWatchChain; } $node->moveWatch($fromLiteral, $toLiteral); $this->watchChains[$fromLiteral]->remove(); $this->watchChains[$toLiteral]->unshift($node); }
php
{ "resource": "" }
q241388
FileDownloader.processUrl
validation
protected function processUrl(PackageInterface $package, $url) { if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) { throw new \RuntimeException('You must enable the openssl extension to download files via https'); } if ($package->getDistReference()) { $url = UrlUtil::updateDistReference($this->config, $url, $package->getDistReference()); } return $url; }
php
{ "resource": "" }
q241389
Validator.createValidator
validation
public static function createValidator($type, $model, $attributes, $params = []) { $params['attributes'] = $attributes; if ($type instanceof \Closure || ($model->hasMethod($type) && !isset(static::$builtInValidators[$type]))) { // method-based validator $params['class'] = __NAMESPACE__ . '\InlineValidator'; $params['method'] = $type; } else { if (isset(static::$builtInValidators[$type])) { $type = static::$builtInValidators[$type]; } if (is_array($type)) { $params = array_merge($type, $params); } else { $params['class'] = $type; } } return Yii::createObject($params); }
php
{ "resource": "" }
q241390
Validator.isActive
validation
public function isActive($scenario) { return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true)); }
php
{ "resource": "" }
q241391
Validator.addError
validation
public function addError($model, $attribute, $message, $params = []) { $params['attribute'] = $model->getAttributeLabel($attribute); if (!isset($params['value'])) { $value = $model->$attribute; if (is_array($value)) { $params['value'] = 'array()'; } elseif (is_object($value) && !method_exists($value, '__toString')) { $params['value'] = '(object)'; } else { $params['value'] = $value; } } $model->addError($attribute, $this->formatMessage($message, $params)); }
php
{ "resource": "" }
q241392
Query.createCommand
validation
public function createCommand($db = null) { if ($db === null) { $db = Yii::$app->getDb(); } list($sql, $params) = $db->getQueryBuilder()->build($this); $command = $db->createCommand($sql, $params); $this->setCommandCache($command); return $command; }
php
{ "resource": "" }
q241393
Query.batch
validation
public function batch($batchSize = 100, $db = null) { return Yii::createObject([ 'class' => BatchQueryResult::className(), 'query' => $this, 'batchSize' => $batchSize, 'db' => $db, 'each' => false, ]); }
php
{ "resource": "" }
q241394
Query.each
validation
public function each($batchSize = 100, $db = null) { return Yii::createObject([ 'class' => BatchQueryResult::className(), 'query' => $this, 'batchSize' => $batchSize, 'db' => $db, 'each' => true, ]); }
php
{ "resource": "" }
q241395
Query.populate
validation
public function populate($rows) { if ($this->indexBy === null) { return $rows; } $result = []; foreach ($rows as $row) { $result[ArrayHelper::getValue($row, $this->indexBy)] = $row; } return $result; }
php
{ "resource": "" }
q241396
Query.scalar
validation
public function scalar($db = null) { if ($this->emulateExecution) { return null; } return $this->createCommand($db)->queryScalar(); }
php
{ "resource": "" }
q241397
Query.addSelect
validation
public function addSelect($columns) { if ($columns instanceof ExpressionInterface) { $columns = [$columns]; } elseif (!is_array($columns)) { $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); } $columns = $this->getUniqueColumns($columns); if ($this->select === null) { $this->select = $columns; } else { $this->select = array_merge($this->select, $columns); } return $this; }
php
{ "resource": "" }
q241398
Query.where
validation
public function where($condition, $params = []) { $this->where = $condition; $this->addParams($params); return $this; }
php
{ "resource": "" }
q241399
Query.andFilterCompare
validation
public function andFilterCompare($name, $value, $defaultOperator = '=') { if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) { $operator = $matches[1]; $value = substr($value, strlen($operator)); } else { $operator = $defaultOperator; } return $this->andFilterWhere([$operator, $name, $value]); }
php
{ "resource": "" }