_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q241200
AuthManagerTrait.getPath
train
public function getPath($userId, $permissionName, $params = [], $allowCaching = true) { if ($allowCaching && empty($params) && isset($this->paths[$userId][$permissionName])) { return $this->paths[$userId][$permissionName]; } $this->checkAccess($userId, $permissionName, $params); if ($allowCaching && empty($params)) { $this->paths[$userId][$permissionName] = $this->currentPath; } return $this->currentPath; }
php
{ "resource": "" }
q241201
Settings.loadFromLocation
train
private function loadFromLocation($location) { Logger::get()->debug('Loading settings...'); // Add the trailing slash to the folder if it is missing. if (substr($location, -1) != DIRECTORY_SEPARATOR) { $location .= DIRECTORY_SEPARATOR; } $settingsLocation = $location . 'settings.json'; if (!is_readable($settingsLocation)) { Logger::get()->error( 'Settings file %s cannot be read.', $settingsLocation ); throw new Settings\Exception("Settings file $settingsLocation is unavailable."); } // Load the settings. $settings = json_decode(file_get_contents($settingsLocation), true); if (empty($settings)) { throw new Settings\Exception('Settings file cannot be parsed.'); } // Load settings customised for the current environment. $environmentSettings = null; $environment = self::getEnvironment(); if ($environment) { $environmentSettingsLocation = sprintf( '%ssettings-%s.json', $location, strtolower($environment) ); if (is_readable($environmentSettingsLocation)) { $environmentSettings = json_decode(file_get_contents($environmentSettingsLocation), true); if (!empty($environmentSettings)) { $settings = self::mergeSettings($settings, $environmentSettings); } } } $this->settings = self::objectify($settings); }
php
{ "resource": "" }
q241202
Settings.objectify
train
private static function objectify( array $array ) { foreach ($array as &$item) { if (is_array($item)) { $item = self::objectify($item); } } return (object)$array; }
php
{ "resource": "" }
q241203
Settings.getEnvironment
train
public static function getEnvironment() { if (empty(self::$environment)) { self::$environment = getenv(self::ENV) ?: @$_SERVER[self::ENV] ?: @$_ENV[self::ENV]; // If the environment cannot be inferred, assume production. if (empty(self::$environment)) { self::$environment = self::ENV_PRODUCTION; } } return self::$environment; }
php
{ "resource": "" }
q241204
Settings.mergeSettings
train
public static function mergeSettings( $generalSettings, $environmentSettings ) { $mergedSettings = $generalSettings; foreach ($environmentSettings as $key => &$value) { if ( is_array($value) && isset($mergedSettings[$key]) && is_array($mergedSettings [$key]) ) { $mergedSettings[$key] = self::mergeSettings($mergedSettings[$key], $value); } else { $mergedSettings[$key] = $value; } } return $mergedSettings; }
php
{ "resource": "" }
q241205
EqualityUtils.isEqual
train
public static function isEqual( EqualityInterface $first = null, EqualityInterface $second = null ) { $result = false; if (null === $first) { $result = (null === $second) ? true : false; } else { $result = $first->equals($second); } return $result; }
php
{ "resource": "" }
q241206
EqualityUtils.isNotEqual
train
public static function isNotEqual( EqualityInterface $first = null, EqualityInterface $second = null ) { return false === self::isEqual($first, $second); }
php
{ "resource": "" }
q241207
FormController.loadAction
train
public function loadAction(Request $request) { $repository = $this->get('phlexible_media_template.template_manager'); $templateKey = $request->get('template_key'); $template = $repository->find($templateKey); $parameters = $template->getParameters(); if (isset($parameters['method'])) { $parameters['xmethod'] = $parameters['method']; unset($parameters['method']); } return new JsonResponse(['success' => true, 'data' => $parameters]); }
php
{ "resource": "" }
q241208
FormController.saveAction
train
public function saveAction(Request $request) { $repository = $this->get('phlexible_media_template.template_manager'); $templateKey = $request->get('template_key'); $params = $request->request->all(); unset($params['template_key'], $params['module'], $params['controller'], $params['action']); $template = $repository->find($templateKey); $params = $this->fixParams($params); foreach ($params as $key => $value) { $template->setParameter($key, $value); } $repository->updateTemplate($template); return new ResultResponse(true, 'Media template "'.$template->getKey().'" saved.'); }
php
{ "resource": "" }
q241209
MongoIdStrategy.hydrate
train
public function hydrate($value) { if ($value instanceof MongoId) { return (string)$value; } if ($this->nullable && $value === null) { return null; } throw new Exception\InvalidArgumentException(sprintf( 'Invalid value: must be an instance of MongoId, "%s" given.', is_object($value) ? get_class($value) : gettype($value) )); }
php
{ "resource": "" }
q241210
MongoIdStrategy.extract
train
public function extract($value) { if (is_string($value)) { return new MongoId($value); } if ($this->nullable && $value === null) { return null; } throw new Exception\InvalidArgumentException(sprintf( 'Invalid value: must be a string containing a valid mongo ID, "%s" given.', is_object($value) ? get_class($value) : gettype($value) )); }
php
{ "resource": "" }
q241211
Layout.element
train
public function element($elementName) { if (Configuration::read('mvc.autoload_shared_var') === true && empty($this->variableList) === false) { foreach ($this->variableList as $varName => $varValue) { ${$varName} = $varValue; } } $layoutDirectory = $this->getDirectory() . '/' . $this->getName(); $elementPath = $layoutDirectory . '/' . $elementName . '.' . $this->getExtension(); if (!file_exists($elementPath)) { trigger_error('Element file "' . $elementPath . '" doesn\'t exist.', E_USER_ERROR); return false; } ob_start(); require($elementPath); echo PHP_EOL; $bodyContent = ob_get_clean(); return $bodyContent; }
php
{ "resource": "" }
q241212
Layout.setVar
train
public function setVar($varName, $varValue, $force = false) { if (isset($this->variableList[$varName]) && $force === false) { trigger_error('Variable "' . $varName . '" is already defined in Layout.', E_USER_WARNING); return false; } $this->variableList[$varName] = $varValue; return true; }
php
{ "resource": "" }
q241213
Arr.except
train
static public function except(array $input, $keys) { $keys = is_array($keys) ? $keys : array_slice(func_get_args(),1); foreach ($keys as $key) { unset($input[$key]); } return $input; }
php
{ "resource": "" }
q241214
Arr.extend
train
static public function extend(array $to, array $from) { foreach ($from as $key => $value) { if (is_array($value)) { $to[$key] = self::extend((array) (isset($to[$key]) ? $to[$key] : []),$value); }else{ $to[$key] = $value; } } return $to; }
php
{ "resource": "" }
q241215
Arr.xmlToArray
train
static public function xmlToArray($xml) { //禁止引用外部xml实体 libxml_disable_entity_loader(true); $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $values; }
php
{ "resource": "" }
q241216
Arr.replaceArrayKey
train
static public function replaceArrayKey($arr = [],$field = '') { $newArr = []; if($arr){ foreach ($arr as $value) { $newArr[$value[$field]] = $value; } } return $newArr; }
php
{ "resource": "" }
q241217
Arr.replaceArrayKeyWithArray
train
static public function replaceArrayKeyWithArray($arr = [],$field = '') { $newArr = []; if($arr){ foreach ($arr as $value) { $newArr[$value[$field]][] = $value; } } return $newArr; }
php
{ "resource": "" }
q241218
JsonSerialize.jsonSerialize
train
public function jsonSerialize() { $copy = []; foreach ((array)$this as $key => $value) { if (!is_string($value)) { $element = $value->getElement(); if (is_object($element) and method_exists($element, 'name') and $name = $element->name() ) { $copy[$name] = $value instanceof JsonSerializable ? $value->jsonSerialize() : $value; } $copy[$key] = $value instanceof JsonSerializable ? $value->jsonSerialize() : $value; } else { $copy[$key] = $value; } } return $copy; }
php
{ "resource": "" }
q241219
RequestConstructor.register
train
public function register() { $this->singleton( 'validation', function () { return new Validation(); } ); $app = &$this->app; // register the request $this->singleton( 'http.request', function () use (&$app) { $request = new Request($app['validation']); $request->header('X-FRAMEWORK-NAME', $app->getName()); $request->header('X-FRAMEWORK-VERSION', $app->getVersion()); return $request; }, true ); // register the response $this->bind( 'http.response', function () use (&$app) { return $app->make('http.request')->getResponse(); }, true ); }
php
{ "resource": "" }
q241220
SetTask.setName
train
public function setName($name, $build) { $this->_name = (string) $name; if (isset($this->_name) && isset($this->_value)) { $build->getProperties()->set($this->_name, $this->_value); } }
php
{ "resource": "" }
q241221
SetTask.setValue
train
public function setValue($value, $build) { $this->_value = (string) $value; if (isset($this->_name) && isset($this->_value)) { $build->setProperty($this->_name, $this->_value); } }
php
{ "resource": "" }
q241222
SetTask.validate
train
public function validate(&$msg = null) { if (!isset($this->_name) && !isset($this->_value) && !isset($this->_file)) { return false; } elseif (isset($this->_file) && (isset($this->_name) || isset($this->_value))) { return false; } elseif ((isset($this->_name) && !isset($this->_value)) || (!isset($this->_name) && isset($this->_value))) { return false; } else { return true; } }
php
{ "resource": "" }
q241223
UploadableBehavior.beforeMarshal
train
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) { // configuration set? $this->check(); // load validator and add our custom upload validator $validator = $this->_table->getValidator(); $validator->setProvider('upload', UploadValidation::class); // go through each field foreach($this->_config['fields'] as $field => $path) { // add validators $validator->add($field, [ 'isUnderPhpSizeLimit' => ['rule' => 'isUnderPhpSizeLimit', 'provider' => 'upload', 'message' => __d('Unimatrix/cake', 'This file is too large')], 'isUnderFormSizeLimit' => ['rule' => 'isUnderFormSizeLimit', 'provider' => 'upload', 'message' => __d('Unimatrix/cake', 'This file is too large')], 'isCompletedUpload' => ['rule' => 'isCompletedUpload', 'provider' => 'upload', 'message' => __d('Unimatrix/cake', 'This file was only partially uploaded')], 'isTemporaryDirectory' => ['rule' => 'isTemporaryDirectory', 'provider' => 'upload', 'message' => __d('Unimatrix/cake', 'Missing a temporary folder')], 'isSuccessfulWrite' => ['rule' => 'isSuccessfulWrite', 'provider' => 'upload', 'message' => __d('Unimatrix/cake', 'Failed to write file to disk')], 'isNotStoppedByExtension' => ['rule' => 'isNotStoppedByExtension', 'provider' => 'upload', 'message' => __d('Unimatrix/cake', 'Upload was stopped by extension')], ]); // empty allowed? && no file uploaded? unset field if($validator->isEmptyAllowed($field, false) && isset($data[$field]['error']) && $data[$field]['error'] === UPLOAD_ERR_NO_FILE) unset($data[$field]); } }
php
{ "resource": "" }
q241224
PlanController.newAction
train
public function newAction(Request $request) { $entity = new Plan(); $form = $this->createForm('EcommerceBundle\Form\PlanType', $entity); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $checkoutManager = $this->get('checkout_manager'); $checkoutManager->createPaypalPlan($entity); $checkoutManager->activePaypalPlan($entity); //if come from popup if ($request->isXMLHttpRequest()) { return new JsonResponse(array( 'id' => $entity->getId(), 'name' => $entity->getName() )); } $this->get('session')->getFlashBag()->add('success', 'plan.created'); return $this->redirectToRoute('ecommerce_plan_show', array('id' => $entity->getId())); } return array( 'entity' => $entity, 'form' => $form->createView(), ); }
php
{ "resource": "" }
q241225
PlanController.showAction
train
public function showAction(Plan $plan) { $deleteForm = $this->createDeleteForm($plan); //get plan $paypalPlan = $this->get('checkout_manager')->getPaypalPlan($plan); return array( 'entity' => $plan, 'delete_form' => $deleteForm->createView(), 'paypalPlan' => $paypalPlan ); }
php
{ "resource": "" }
q241226
PlanController.createDeleteForm
train
private function createDeleteForm(Plan $plan) { return $this->createFormBuilder() ->setAction($this->generateUrl('ecommerce_plan_delete', array('id' => $plan->getId()))) ->setMethod('DELETE') ->getForm() ; }
php
{ "resource": "" }
q241227
ComposerScriptRunner.getEnvFile
train
public function getEnvFile() { $basePath = $this->getBasePath(); $envFile = $this->get('envFile'); $startsWith = substr($envFile, 0, 1); if (!$startsWith !== '/' && $startsWith !== '~' && $startsWith !== '\\') { $envFile = $basePath . DIRECTORY_SEPARATOR . $envFile; } return $envFile; }
php
{ "resource": "" }
q241228
ComposerScriptRunner.verifyExtras
train
protected function verifyExtras(array $extras) { if (!isset($extras['php-env-builder'])) { throw new \InvalidArgumentException( 'The parameter handler needs to be configured through the ' . 'extra.php-env-builder setting.' ); } if (!is_array($extras['php-env-builder'])) { throw new \InvalidArgumentException( 'The extra.php-env-builder setting must be an array or a configuration object.' ); } if (!isset($extras['php-env-builder']['questions']) || !is_array($extras['php-env-builder']['questions'])) { throw new \InvalidArgumentException( 'The extra.php-env-builder.questions setting must be an array of questions.' ); } }
php
{ "resource": "" }
q241229
ComposerScriptRunner.build
train
public static function build(Event $event, Builder $builder = null) { $runner = new ComposerScriptRunner($event, $builder); $runner->run(); }
php
{ "resource": "" }
q241230
ComposerScriptRunner.askQuestions
train
protected function askQuestions(array $questons) { foreach ($questons as $question) { $this->verifyQuestion($question); $name = $question['name']; $prompt = $question['prompt']; $default = isset($question['default']) ? $question['default'] : ''; $required = isset($question['required']) ? (bool) $question['required'] : false; $this->builder->ask($name, $prompt, $default, $required); } }
php
{ "resource": "" }
q241231
ComposerScriptRunner.shouldCancelOnClobber
train
protected function shouldCancelOnClobber() { $fullPath = $this->getEnvFile(); if (!$this->get('clobber') && file_exists($fullPath)) { $this->event->getIO()->write(sprintf('Env file `%s` already exists, skipping...', $fullPath)); return true; } return false; }
php
{ "resource": "" }
q241232
TCPConnection.disconnect
train
public function disconnect(): void { if ($this->connected() === true) { fclose($this->connection); $this->connection = false; } }
php
{ "resource": "" }
q241233
TCPConnection.setBlocking
train
public function setBlocking(int $mode): bool { if ($this->connected() === false) { throw new \Exception('Not connected'); } return stream_set_blocking($this->connection, $mode); }
php
{ "resource": "" }
q241234
TCPConnection.read
train
public function read(): string { if ($this->connected() === false) { throw new \Exception('Not connected'); } $response = ''; $continue = true; while ($continue == true) { $data = null; try { $data = $this->readLine(); } catch (\Exception $e) { $continue = false; } if (!is_null($data)) { $response .= $data; } } return $response; }
php
{ "resource": "" }
q241235
TCPConnection.readLine
train
public function readLine(): string { if ($this->connected() === false) { throw new \Exception('Not connected'); } $response = fgets($this->connection); if ($response === false) { throw new \Exception('Nothing to read'); } return $response; }
php
{ "resource": "" }
q241236
TCPConnection.readBytes
train
public function readBytes(int $bytes): string { if ($this->connected() === false) { throw new \Exception('Not connected'); } $response = fread($this->connection, $bytes); if ($response === false) { throw new \Exception('Nothing to read'); } return $response; }
php
{ "resource": "" }
q241237
TCPConnection.writeLine
train
public function writeLine(string $data): void { try { $this->write($data."\r\n"); } catch (\Exception $e) { throw $e; } }
php
{ "resource": "" }
q241238
Auth.role
train
public function role($src, $value = '') { if (isset($this->_config->config['firewall']['' . $src . ''])) { if ($value == '') { $role = explode('.', $this->_config->config['firewall']['' . $src . '']['roles']['name']); return $this->_getSession($role); } else { $role = explode('.', $this->_config->config['firewall']['' . $src . '']['roles']['name']); $this->_setSession($role, $value); } } else { throw new MissingConfigException('the module ' . $src . ' doesn\'t exist'); } return false; }
php
{ "resource": "" }
q241239
Auth.logged
train
public function logged($src, $value = '') { if (isset($this->_config->config['firewall']['' . $src . ''])) { if ($value == '') { $logged = explode('.', $this->_config->config['firewall']['' . $src . '']['logged']['name']); $data = $this->_getSession($logged); if ($data != '') { return $data; } else { return false; } } else { $logged = explode('.', $this->_config->config['firewall']['' . $src . '']['logged']['name']); $this->_setSession($logged, $value); } } else { throw new MissingConfigException('the module ' . $src . ' doesn\'t exist'); } return false; }
php
{ "resource": "" }
q241240
DevicesRatioComposer.getDevicesFromSessions
train
protected function getDevicesFromSessions(Carbon $start, Carbon $end) { return $this->getVisitorsFilteredByDateRange($start, $end) ->filter(function (Visitor $session) { return $session->hasDevice(); }) ->transform(function (Visitor $session) { return $session->device; }) ->groupBy('kind') ->transform(function (Collection $items, $key) { return [ 'kind' => trans("tracker::devices.kinds.$key"), 'count' => $items->count(), ]; }); }
php
{ "resource": "" }
q241241
GitLabDriver.supports
validation
public static function supports(IOInterface $io, Config $config, $url, $deep = false) { if (!preg_match(self::URL_REGEX, $url, $match)) { return false; } $scheme = !empty($match['scheme']) ? $match['scheme'] : null; $guessedDomain = !empty($match['domain']) ? $match['domain'] : $match['domain2']; $urlParts = explode('/', $match['parts']); if (false === self::determineOrigin((array) $config->get('gitlab-domains'), $guessedDomain, $urlParts)) { return false; } if ('https' === $scheme && !extension_loaded('openssl')) { $io->writeError('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE); return false; } return true; }
php
{ "resource": "" }
q241242
PackageDependencyParser.buildDependencyInfo
validation
public function buildDependencyInfo($depArray) { if (!is_array($depArray)) { return new DependencyInfo(array(), array()); } if (!$this->isHash($depArray)) { return new DependencyInfo($this->buildDependency10Info($depArray), array()); } return $this->buildDependency20Info($depArray); }
php
{ "resource": "" }
q241243
PackageDependencyParser.buildDependency10Info
validation
private function buildDependency10Info($depArray) { static $dep10toOperatorMap = array('has' => '==', 'eq' => '==', 'ge' => '>=', 'gt' => '>', 'le' => '<=', 'lt' => '<', 'not' => '!='); $result = array(); foreach ($depArray as $depItem) { if (empty($depItem['rel']) || !array_key_exists($depItem['rel'], $dep10toOperatorMap)) { // 'unknown rel type:' . $depItem['rel']; continue; } $depType = !empty($depItem['optional']) && 'yes' == $depItem['optional'] ? 'optional' : 'required'; $depType = 'not' == $depItem['rel'] ? 'conflicts' : $depType; $depVersion = !empty($depItem['version']) ? $this->parseVersion($depItem['version']) : '*'; // has & not are special operators that does not requires version $depVersionConstraint = ('has' == $depItem['rel'] || 'not' == $depItem['rel']) && '*' == $depVersion ? '*' : $dep10toOperatorMap[$depItem['rel']] . $depVersion; switch ($depItem['type']) { case 'php': $depChannelName = 'php'; $depPackageName = ''; break; case 'pkg': $depChannelName = !empty($depItem['channel']) ? $depItem['channel'] : 'pear.php.net'; $depPackageName = $depItem['name']; break; case 'ext': $depChannelName = 'ext'; $depPackageName = $depItem['name']; break; case 'os': case 'sapi': $depChannelName = ''; $depPackageName = ''; break; default: $depChannelName = ''; $depPackageName = ''; break; } if ('' != $depChannelName) { $result[] = new DependencyConstraint( $depType, $depVersionConstraint, $depChannelName, $depPackageName ); } } return $result; }
php
{ "resource": "" }
q241244
PackageDependencyParser.buildDependency20Info
validation
private function buildDependency20Info($depArray) { $result = array(); $optionals = array(); $defaultOptionals = array(); foreach ($depArray as $depType => $depTypeGroup) { if (!is_array($depTypeGroup)) { continue; } if ('required' == $depType || 'optional' == $depType) { foreach ($depTypeGroup as $depItemType => $depItem) { switch ($depItemType) { case 'php': $result[] = new DependencyConstraint( $depType, $this->parse20VersionConstraint($depItem), 'php', '' ); break; case 'package': $deps = $this->buildDepPackageConstraints($depItem, $depType); $result = array_merge($result, $deps); break; case 'extension': $deps = $this->buildDepExtensionConstraints($depItem, $depType); $result = array_merge($result, $deps); break; case 'subpackage': $deps = $this->buildDepPackageConstraints($depItem, 'replaces'); $defaultOptionals += $deps; break; case 'os': case 'pearinstaller': break; default: break; } } } elseif ('group' == $depType) { if ($this->isHash($depTypeGroup)) { $depTypeGroup = array($depTypeGroup); } foreach ($depTypeGroup as $depItem) { $groupName = $depItem['attribs']['name']; if (!isset($optionals[$groupName])) { $optionals[$groupName] = array(); } if (isset($depItem['subpackage'])) { $optionals[$groupName] += $this->buildDepPackageConstraints($depItem['subpackage'], 'replaces'); } else { $result += $this->buildDepPackageConstraints($depItem['package'], 'optional'); } } } } if (count($defaultOptionals) > 0) { $optionals['*'] = $defaultOptionals; } return new DependencyInfo($result, $optionals); }
php
{ "resource": "" }
q241245
PackageDependencyParser.buildDepExtensionConstraints
validation
private function buildDepExtensionConstraints($depItem, $depType) { if ($this->isHash($depItem)) { $depItem = array($depItem); } $result = array(); foreach ($depItem as $subDepItem) { $depChannelName = 'ext'; $depPackageName = $subDepItem['name']; $depVersionConstraint = $this->parse20VersionConstraint($subDepItem); $result[] = new DependencyConstraint( $depType, $depVersionConstraint, $depChannelName, $depPackageName ); } return $result; }
php
{ "resource": "" }
q241246
PackageDependencyParser.buildDepPackageConstraints
validation
private function buildDepPackageConstraints($depItem, $depType) { if ($this->isHash($depItem)) { $depItem = array($depItem); } $result = array(); foreach ($depItem as $subDepItem) { if (!array_key_exists('channel', $subDepItem)) { $subDepItem['channel'] = $subDepItem['uri']; } $depChannelName = $subDepItem['channel']; $depPackageName = $subDepItem['name']; $depVersionConstraint = $this->parse20VersionConstraint($subDepItem); if (isset($subDepItem['conflicts'])) { $depType = 'conflicts'; } $result[] = new DependencyConstraint( $depType, $depVersionConstraint, $depChannelName, $depPackageName ); } return $result; }
php
{ "resource": "" }
q241247
PackageDependencyParser.parse20VersionConstraint
validation
private function parse20VersionConstraint(array $data) { static $dep20toOperatorMap = array('has' => '==', 'min' => '>=', 'max' => '<=', 'exclude' => '!='); $versions = array(); $values = array_intersect_key($data, $dep20toOperatorMap); if (0 == count($values)) { return '*'; } if (isset($values['min']) && isset($values['exclude']) && $data['min'] == $data['exclude']) { $versions[] = '>' . $this->parseVersion($values['min']); } elseif (isset($values['max']) && isset($values['exclude']) && $data['max'] == $data['exclude']) { $versions[] = '<' . $this->parseVersion($values['max']); } else { foreach ($values as $op => $version) { if ('exclude' == $op && is_array($version)) { foreach ($version as $versionPart) { $versions[] = $dep20toOperatorMap[$op] . $this->parseVersion($versionPart); } } else { $versions[] = $dep20toOperatorMap[$op] . $this->parseVersion($version); } } } return implode(',', $versions); }
php
{ "resource": "" }
q241248
PackageDependencyParser.parseVersion
validation
private function parseVersion($version) { if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?}i', $version, $matches)) { $version = $matches[1] .(!empty($matches[2]) ? $matches[2] : '.0') .(!empty($matches[3]) ? $matches[3] : '.0') .(!empty($matches[4]) ? $matches[4] : '.0'); return $version; } return null; }
php
{ "resource": "" }
q241249
Request.fix
validation
public function fix($packageName, ConstraintInterface $constraint = null) { $this->addJob($packageName, 'install', $constraint, true); }
php
{ "resource": "" }
q241250
GitLab.authorizeOAuth
validation
public function authorizeOAuth($originUrl) { if (!in_array($originUrl, $this->config->get('gitlab-domains'), true)) { return false; } // if available use token from git config if (0 === $this->process->execute('git config gitlab.accesstoken', $output)) { $this->io->setAuthentication($originUrl, trim($output), 'oauth2'); return true; } // if available use token from composer config $authTokens = $this->config->get('gitlab-token'); if (isset($authTokens[$originUrl])) { $this->io->setAuthentication($originUrl, $authTokens[$originUrl], 'private-token'); return true; } return false; }
php
{ "resource": "" }
q241251
Installer.getCurrentPackages
validation
private function getCurrentPackages($installedRepo) { if ($this->locker->isLocked()) { try { return $this->locker->getLockedRepository(true)->getPackages(); } catch (\RuntimeException $e) { // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file return $this->locker->getLockedRepository()->getPackages(); } } return $installedRepo->getPackages(); }
php
{ "resource": "" }
q241252
Installer.mockLocalRepositories
validation
private function mockLocalRepositories(RepositoryManager $rm) { $packages = array(); foreach ($rm->getLocalRepository()->getPackages() as $package) { $packages[(string) $package] = clone $package; } foreach ($packages as $key => $package) { if ($package instanceof AliasPackage) { $alias = (string) $package->getAliasOf(); $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion()); } } $rm->setLocalRepository( new InstalledArrayRepository($packages) ); }
php
{ "resource": "" }
q241253
Installer.setOptimizeAutoloader
validation
public function setOptimizeAutoloader($optimizeAutoloader = false) { $this->optimizeAutoloader = (bool) $optimizeAutoloader; if (!$this->optimizeAutoloader) { // Force classMapAuthoritative off when not optimizing the // autoloader $this->setClassMapAuthoritative(false); } return $this; }
php
{ "resource": "" }
q241254
Installer.setClassMapAuthoritative
validation
public function setClassMapAuthoritative($classMapAuthoritative = false) { $this->classMapAuthoritative = (bool) $classMapAuthoritative; if ($this->classMapAuthoritative) { // Force optimizeAutoloader when classmap is authoritative $this->setOptimizeAutoloader(true); } return $this; }
php
{ "resource": "" }
q241255
Cache.copyTo
validation
public function copyTo($file, $target) { if ($this->enabled) { $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file); if (file_exists($this->root . $file)) { try { touch($this->root . $file, filemtime($this->root . $file), time()); } catch (\ErrorException $e) { // fallback in case the above failed due to incorrect ownership // see https://github.com/composer/composer/issues/4070 Silencer::call('touch', $this->root . $file); } $this->io->writeError('Reading '.$this->root . $file.' from cache', true, IOInterface::DEBUG); return copy($this->root . $file, $target); } } return false; }
php
{ "resource": "" }
q241256
Package.replaceVersion
validation
public function replaceVersion($version, $prettyVersion) { $this->version = $version; $this->prettyVersion = $prettyVersion; $this->stability = VersionParser::parseStability($version); $this->dev = $this->stability === 'dev'; }
php
{ "resource": "" }
q241257
Locker.getContentHash
validation
public static function getContentHash($composerFileContents) { $content = json_decode($composerFileContents, true); $relevantKeys = array( 'name', 'version', 'require', 'require-dev', 'conflict', 'replace', 'provide', 'minimum-stability', 'prefer-stable', 'repositories', 'extra', ); $relevantContent = array(); foreach (array_intersect($relevantKeys, array_keys($content)) as $key) { $relevantContent[$key] = $content[$key]; } if (isset($content['config']['platform'])) { $relevantContent['config']['platform'] = $content['config']['platform']; } ksort($relevantContent); return md5(json_encode($relevantContent)); }
php
{ "resource": "" }
q241258
Locker.getLockedRepository
validation
public function getLockedRepository($withDevReqs = false) { $lockData = $this->getLockData(); $packages = new ArrayRepository(); $lockedPackages = $lockData['packages']; if ($withDevReqs) { if (isset($lockData['packages-dev'])) { $lockedPackages = array_merge($lockedPackages, $lockData['packages-dev']); } else { throw new \RuntimeException('The lock file does not contain require-dev information, run install with the --no-dev option or run update to install those packages.'); } } if (empty($lockedPackages)) { return $packages; } if (isset($lockedPackages[0]['name'])) { foreach ($lockedPackages as $info) { $packages->addPackage($this->loader->load($info)); } return $packages; } throw new \RuntimeException('Your composer.lock was created before 2012-09-15, and is not supported anymore. Run "composer update" to generate a new one.'); }
php
{ "resource": "" }
q241259
Locker.getPackageTime
validation
private function getPackageTime(PackageInterface $package) { if (!function_exists('proc_open')) { return null; } $path = realpath($this->installationManager->getInstallPath($package)); $sourceType = $package->getSourceType(); $datetime = null; if ($path && in_array($sourceType, array('git', 'hg'))) { $sourceRef = $package->getSourceReference() ?: $package->getDistReference(); switch ($sourceType) { case 'git': GitUtil::cleanEnv(); if (0 === $this->process->execute('git log -n1 --pretty=%ct '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*\d+\s*$}', $output)) { $datetime = new \DateTime('@'.trim($output), new \DateTimeZone('UTC')); } break; case 'hg': if (0 === $this->process->execute('hg log --template "{date|hgdate}" -r '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*(\d+)\s*}', $output, $match)) { $datetime = new \DateTime('@'.$match[1], new \DateTimeZone('UTC')); } break; } } return $datetime ? $datetime->format(DATE_RFC3339) : null; }
php
{ "resource": "" }
q241260
BitbucketDriver.getRepoData
validation
protected function getRepoData() { $resource = sprintf( 'https://api.bitbucket.org/2.0/repositories/%s/%s?%s', $this->owner, $this->repository, http_build_query( array('fields' => '-project,-owner'), null, '&' ) ); $repoData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource, true), $resource); if ($this->fallbackDriver) { return false; } $this->parseCloneUrls($repoData['links']['clone']); $this->hasIssues = !empty($repoData['has_issues']); $this->branchesUrl = $repoData['links']['branches']['href']; $this->tagsUrl = $repoData['links']['tags']['href']; $this->homeUrl = $repoData['links']['html']['href']; $this->website = $repoData['website']; $this->vcsType = $repoData['scm']; return true; }
php
{ "resource": "" }
q241261
Solver.propagate
validation
protected function propagate($level) { while ($this->decisions->validOffset($this->propagateIndex)) { $decision = $this->decisions->atOffset($this->propagateIndex); $conflict = $this->watchGraph->propagateLiteral( $decision[Decisions::DECISION_LITERAL], $level, $this->decisions ); $this->propagateIndex++; if ($conflict) { return $conflict; } } return null; }
php
{ "resource": "" }
q241262
Solver.revert
validation
private function revert($level) { while (!$this->decisions->isEmpty()) { $literal = $this->decisions->lastLiteral(); if ($this->decisions->undecided($literal)) { break; } $decisionLevel = $this->decisions->decisionLevel($literal); if ($decisionLevel <= $level) { break; } $this->decisions->revertLast(); $this->propagateIndex = count($this->decisions); } while (!empty($this->branches) && $this->branches[count($this->branches) - 1][self::BRANCH_LEVEL] >= $level) { array_pop($this->branches); } }
php
{ "resource": "" }
q241263
ArrayRepository.addPackage
validation
public function addPackage(PackageInterface $package) { if (null === $this->packages) { $this->initialize(); } $package->setRepository($this); $this->packages[] = $package; if ($package instanceof AliasPackage) { $aliasedPackage = $package->getAliasOf(); if (null === $aliasedPackage->getRepository()) { $this->addPackage($aliasedPackage); } } }
php
{ "resource": "" }
q241264
ArrayRepository.removePackage
validation
public function removePackage(PackageInterface $package) { $packageId = $package->getUniqueName(); foreach ($this->getPackages() as $key => $repoPackage) { if ($packageId === $repoPackage->getUniqueName()) { array_splice($this->packages, $key, 1); return; } } }
php
{ "resource": "" }
q241265
RemoteFilesystem.copy
validation
public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array()) { return $this->get($originUrl, $fileUrl, $options, $fileName, $progress); }
php
{ "resource": "" }
q241266
RemoteFilesystem.getContents
validation
public function getContents($originUrl, $fileUrl, $progress = true, $options = array()) { return $this->get($originUrl, $fileUrl, $options, null, $progress); }
php
{ "resource": "" }
q241267
RemoteFilesystem.getRemoteContents
validation
protected function getRemoteContents($originUrl, $fileUrl, $context, array &$responseHeaders = null) { try { $e = null; $result = file_get_contents($fileUrl, false, $context); } catch (\Throwable $e) { } catch (\Exception $e) { } $responseHeaders = isset($http_response_header) ? $http_response_header : array(); if (null !== $e) { throw $e; } return $result; }
php
{ "resource": "" }
q241268
FilesystemRepository.write
validation
public function write() { $data = array(); $dumper = new ArrayDumper(); foreach ($this->getCanonicalPackages() as $package) { $data[] = $dumper->dump($package); } usort($data, function ($a, $b) { return strcmp($a['name'], $b['name']); }); $this->file->write($data); }
php
{ "resource": "" }
q241269
ErrorHandler.register
validation
public static function register(IOInterface $io = null) { set_error_handler(array(__CLASS__, 'handle')); error_reporting(E_ALL | E_STRICT); self::$io = $io; }
php
{ "resource": "" }
q241270
LicensesCommand.filterRequiredPackages
validation
private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()) { $requires = array_keys($package->getRequires()); $packageListNames = array_keys($bucket); $packages = array_filter( $repo->getPackages(), function ($package) use ($requires, $packageListNames) { return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames); } ); $bucket = $this->appendPackages($packages, $bucket); foreach ($packages as $package) { $bucket = $this->filterRequiredPackages($repo, $package, $bucket); } return $bucket; }
php
{ "resource": "" }
q241271
LicensesCommand.appendPackages
validation
public function appendPackages(array $packages, array $bucket) { foreach ($packages as $package) { $bucket[$package->getName()] = $package; } return $bucket; }
php
{ "resource": "" }
q241272
HgExcludeFilter.parseHgIgnoreLine
validation
public function parseHgIgnoreLine($line) { if (preg_match('#^syntax\s*:\s*(glob|regexp)$#', $line, $matches)) { if ($matches[1] === 'glob') { $this->patternMode = self::HG_IGNORE_GLOB; } else { $this->patternMode = self::HG_IGNORE_REGEX; } return null; } if ($this->patternMode == self::HG_IGNORE_GLOB) { return $this->patternFromGlob($line); } return $this->patternFromRegex($line); }
php
{ "resource": "" }
q241273
Problem.addRule
validation
public function addRule(Rule $rule) { $this->addReason(spl_object_hash($rule), array( 'rule' => $rule, 'job' => $rule->getJob(), )); }
php
{ "resource": "" }
q241274
Problem.addReason
validation
protected function addReason($id, $reason) { if (!isset($this->reasonSeen[$id])) { $this->reasonSeen[$id] = true; $this->reasons[$this->section][] = $reason; } }
php
{ "resource": "" }
q241275
Problem.jobToText
validation
protected function jobToText($job) { $packageName = $job['packageName']; $constraint = $job['constraint']; switch ($job['cmd']) { case 'install': $packages = $this->pool->whatProvides($packageName, $constraint); if (!$packages) { return 'No package found to satisfy install request for '.$packageName.$this->constraintToText($constraint); } return 'Installation request for '.$packageName.$this->constraintToText($constraint).' -> satisfiable by '.$this->getPackageList($packages).'.'; case 'update': return 'Update request for '.$packageName.$this->constraintToText($constraint).'.'; case 'remove': return 'Removal request for '.$packageName.$this->constraintToText($constraint).''; } if (isset($constraint)) { $packages = $this->pool->whatProvides($packageName, $constraint); } else { $packages = array(); } return 'Job(cmd='.$job['cmd'].', target='.$packageName.', packages=['.$this->getPackageList($packages).'])'; }
php
{ "resource": "" }
q241276
ShowCommand.printVersions
validation
protected function printVersions(CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo) { uasort($versions, 'version_compare'); $versions = array_keys(array_reverse($versions)); // highlight installed version if ($installedRepo->hasPackage($package)) { $installedVersion = $package->getPrettyVersion(); $key = array_search($installedVersion, $versions); if (false !== $key) { $versions[$key] = '<info>* ' . $installedVersion . '</info>'; } } $versions = implode(', ', $versions); $this->getIO()->write('<info>versions</info> : ' . $versions); }
php
{ "resource": "" }
q241277
ShowCommand.printLinks
validation
protected function printLinks(CompletePackageInterface $package, $linkType, $title = null) { $title = $title ?: $linkType; $io = $this->getIO(); if ($links = $package->{'get'.ucfirst($linkType)}()) { $io->write("\n<info>" . $title . "</info>"); foreach ($links as $link) { $io->write($link->getTarget() . ' <comment>' . $link->getPrettyConstraint() . '</comment>'); } } }
php
{ "resource": "" }
q241278
ShowCommand.printLicenses
validation
protected function printLicenses(CompletePackageInterface $package) { $spdxLicenses = new SpdxLicenses(); $licenses = $package->getLicense(); $io = $this->getIO(); foreach ($licenses as $licenseId) { $license = $spdxLicenses->getLicenseByIdentifier($licenseId); // keys: 0 fullname, 1 osi, 2 url if (!$license) { $out = $licenseId; } else { // is license OSI approved? if ($license[1] === true) { $out = sprintf('%s (%s) (OSI approved) %s', $license[0], $licenseId, $license[2]); } else { $out = sprintf('%s (%s) %s', $license[0], $licenseId, $license[2]); } } $io->write('<info>license</info> : ' . $out); } }
php
{ "resource": "" }
q241279
ShowCommand.initStyles
validation
protected function initStyles(OutputInterface $output) { $this->colors = array( 'green', 'yellow', 'cyan', 'magenta', 'blue', ); foreach ($this->colors as $color) { $style = new OutputFormatterStyle($color); $output->getFormatter()->setStyle($color, $style); } }
php
{ "resource": "" }
q241280
ShowCommand.generatePackageTree
validation
protected function generatePackageTree( PackageInterface $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos ) { $requires = $package->getRequires(); ksort($requires); $children = array(); foreach ($requires as $requireName => $require) { $packagesInTree = array($package->getName(), $requireName); $treeChildDesc = array( 'name' => $requireName, 'version' => $require->getPrettyConstraint(), ); $deepChildren = $this->addTree($requireName, $require, $installedRepo, $distantRepos, $packagesInTree); if ($deepChildren) { $treeChildDesc['requires'] = $deepChildren; } $children[] = $treeChildDesc; } $tree = array( 'name' => $package->getPrettyName(), 'version' => $package->getPrettyVersion(), 'description' => $package->getDescription(), ); if ($children) { $tree['requires'] = $children; } return $tree; }
php
{ "resource": "" }
q241281
GitHubDriver.fetchRootIdentifier
validation
protected function fetchRootIdentifier() { if ($this->repoData) { return; } $repoDataUrl = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository; $this->repoData = JsonFile::parseJson($this->getContents($repoDataUrl, true), $repoDataUrl); if (null === $this->repoData && null !== $this->gitDriver) { return; } $this->owner = $this->repoData['owner']['login']; $this->repository = $this->repoData['name']; $this->isPrivate = !empty($this->repoData['private']); if (isset($this->repoData['default_branch'])) { $this->rootIdentifier = $this->repoData['default_branch']; } elseif (isset($this->repoData['master_branch'])) { $this->rootIdentifier = $this->repoData['master_branch']; } else { $this->rootIdentifier = 'master'; } $this->hasIssues = !empty($this->repoData['has_issues']); }
php
{ "resource": "" }
q241282
TlsHelper.checkCertificateHost
validation
public static function checkCertificateHost($certificate, $hostname, &$cn = null) { $names = self::getCertificateNames($certificate); if (empty($names)) { return false; } $combinedNames = array_merge($names['san'], array($names['cn'])); $hostname = strtolower($hostname); foreach ($combinedNames as $certName) { $matcher = self::certNameMatcher($certName); if ($matcher && $matcher($hostname)) { $cn = $names['cn']; return true; } } return false; }
php
{ "resource": "" }
q241283
TlsHelper.getCertificateNames
validation
public static function getCertificateNames($certificate) { if (is_array($certificate)) { $info = $certificate; } elseif (CaBundle::isOpensslParseSafe()) { $info = openssl_x509_parse($certificate, false); } if (!isset($info['subject']['commonName'])) { return null; } $commonName = strtolower($info['subject']['commonName']); $subjectAltNames = array(); if (isset($info['extensions']['subjectAltName'])) { $subjectAltNames = preg_split('{\s*,\s*}', $info['extensions']['subjectAltName']); $subjectAltNames = array_filter(array_map(function ($name) { if (0 === strpos($name, 'DNS:')) { return strtolower(ltrim(substr($name, 4))); } return null; }, $subjectAltNames)); $subjectAltNames = array_values($subjectAltNames); } return array( 'cn' => $commonName, 'san' => $subjectAltNames, ); }
php
{ "resource": "" }
q241284
ChannelRest11Reader.parsePackage
validation
private function parsePackage($packageInfo) { $packageInfo->registerXPathNamespace('ns', self::CATEGORY_PACKAGES_INFO_NS); $channelName = (string) $packageInfo->p->c; $packageName = (string) $packageInfo->p->n; $license = (string) $packageInfo->p->l; $shortDescription = (string) $packageInfo->p->s; $description = (string) $packageInfo->p->d; $dependencies = array(); foreach ($packageInfo->xpath('ns:deps') as $node) { $dependencyVersion = (string) $node->v; $dependencyArray = unserialize((string) $node->d); $dependencyInfo = $this->dependencyReader->buildDependencyInfo($dependencyArray); $dependencies[$dependencyVersion] = $dependencyInfo; } $releases = array(); $releasesInfo = $packageInfo->xpath('ns:a/ns:r'); if ($releasesInfo) { foreach ($releasesInfo as $node) { $releaseVersion = (string) $node->v; $releaseStability = (string) $node->s; $releases[$releaseVersion] = new ReleaseInfo( $releaseStability, isset($dependencies[$releaseVersion]) ? $dependencies[$releaseVersion] : new DependencyInfo(array(), array()) ); } } return new PackageInfo( $channelName, $packageName, $license, $shortDescription, $description, $releases ); }
php
{ "resource": "" }
q241285
EventDispatcher.dispatchScript
validation
public function dispatchScript($eventName, $devMode = false, $additionalArgs = array(), $flags = array()) { return $this->doDispatch(new Script\Event($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags)); }
php
{ "resource": "" }
q241286
EventDispatcher.dispatchPackageEvent
validation
public function dispatchPackageEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations, OperationInterface $operation) { return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations, $operation)); }
php
{ "resource": "" }
q241287
EventDispatcher.dispatchInstallerEvent
validation
public function dispatchInstallerEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations = array()) { return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations)); }
php
{ "resource": "" }
q241288
EventDispatcher.addSubscriber
validation
public function addSubscriber(EventSubscriberInterface $subscriber) { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { $this->addListener($eventName, array($subscriber, $params)); } elseif (is_string($params[0])) { $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0); } else { foreach ($params as $listener) { $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0); } } } }
php
{ "resource": "" }
q241289
EventDispatcher.getListeners
validation
protected function getListeners(Event $event) { $scriptListeners = $this->getScriptListeners($event); if (!isset($this->listeners[$event->getName()][0])) { $this->listeners[$event->getName()][0] = array(); } krsort($this->listeners[$event->getName()]); $listeners = $this->listeners; $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners); return call_user_func_array('array_merge', $listeners[$event->getName()]); }
php
{ "resource": "" }
q241290
EventDispatcher.getScriptListeners
validation
protected function getScriptListeners(Event $event) { $package = $this->composer->getPackage(); $scripts = $package->getScripts(); if (empty($scripts[$event->getName()])) { return array(); } if ($this->loader) { $this->loader->unregister(); } $generator = $this->composer->getAutoloadGenerator(); if ($event instanceof ScriptEvent) { $generator->setDevMode($event->isDevMode()); } $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages(); $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages); $map = $generator->parseAutoloads($packageMap, $package); $this->loader = $generator->createLoader($map); $this->loader->register(); return $scripts[$event->getName()]; }
php
{ "resource": "" }
q241291
EventDispatcher.pushEvent
validation
protected function pushEvent(Event $event) { $eventName = $event->getName(); if (in_array($eventName, $this->eventStack)) { throw new \RuntimeException(sprintf("Circular call to script handler '%s' detected", $eventName)); } return array_push($this->eventStack, $eventName); }
php
{ "resource": "" }
q241292
CompositeRepository.addRepository
validation
public function addRepository(RepositoryInterface $repository) { if ($repository instanceof self) { foreach ($repository->getRepositories() as $repo) { $this->addRepository($repo); } } else { $this->repositories[] = $repository; } }
php
{ "resource": "" }
q241293
DownloadManager.setOutputProgress
validation
public function setOutputProgress($outputProgress) { foreach ($this->downloaders as $downloader) { $downloader->setOutputProgress($outputProgress); } return $this; }
php
{ "resource": "" }
q241294
DownloadManager.setDownloader
validation
public function setDownloader($type, DownloaderInterface $downloader) { $type = strtolower($type); $this->downloaders[$type] = $downloader; return $this; }
php
{ "resource": "" }
q241295
DownloadManager.getDownloader
validation
public function getDownloader($type) { $type = strtolower($type); if (!isset($this->downloaders[$type])) { throw new \InvalidArgumentException(sprintf('Unknown downloader type: %s. Available types: %s.', $type, implode(', ', array_keys($this->downloaders)))); } return $this->downloaders[$type]; }
php
{ "resource": "" }
q241296
DownloadManager.download
validation
public function download(PackageInterface $package, $targetDir, $preferSource = null) { $preferSource = null !== $preferSource ? $preferSource : $this->preferSource; $sourceType = $package->getSourceType(); $distType = $package->getDistType(); $sources = array(); if ($sourceType) { $sources[] = 'source'; } if ($distType) { $sources[] = 'dist'; } if (empty($sources)) { throw new \InvalidArgumentException('Package '.$package.' must have a source or dist specified'); } if (!$preferSource && ($this->preferDist || 'dist' === $this->resolvePackageInstallPreference($package))) { $sources = array_reverse($sources); } $this->filesystem->ensureDirectoryExists($targetDir); foreach ($sources as $i => $source) { if (isset($e)) { $this->io->writeError(' <warning>Now trying to download from ' . $source . '</warning>'); } $package->setInstallationSource($source); try { $downloader = $this->getDownloaderForInstalledPackage($package); if ($downloader) { $downloader->download($package, $targetDir); } break; } catch (\RuntimeException $e) { if ($i === count($sources) - 1) { throw $e; } $this->io->writeError( ' <warning>Failed to download '. $package->getPrettyName(). ' from ' . $source . ': '. $e->getMessage().'</warning>' ); } } }
php
{ "resource": "" }
q241297
DownloadManager.update
validation
public function update(PackageInterface $initial, PackageInterface $target, $targetDir) { $downloader = $this->getDownloaderForInstalledPackage($initial); if (!$downloader) { return; } $installationSource = $initial->getInstallationSource(); if ('dist' === $installationSource) { $initialType = $initial->getDistType(); $targetType = $target->getDistType(); } else { $initialType = $initial->getSourceType(); $targetType = $target->getSourceType(); } // upgrading from a dist stable package to a dev package, force source reinstall if ($target->isDev() && 'dist' === $installationSource) { $downloader->remove($initial, $targetDir); $this->download($target, $targetDir); return; } if ($initialType === $targetType) { $target->setInstallationSource($installationSource); try { $downloader->update($initial, $target, $targetDir); return; } catch (\RuntimeException $e) { if (!$this->io->isInteractive()) { throw $e; } $this->io->writeError('<error> Update failed ('.$e->getMessage().')</error>'); if (!$this->io->askConfirmation(' Would you like to try reinstalling the package instead [<comment>yes</comment>]? ', true)) { throw $e; } } } $downloader->remove($initial, $targetDir); $this->download($target, $targetDir, 'source' === $installationSource); }
php
{ "resource": "" }
q241298
DownloadManager.remove
validation
public function remove(PackageInterface $package, $targetDir) { $downloader = $this->getDownloaderForInstalledPackage($package); if ($downloader) { $downloader->remove($package, $targetDir); } }
php
{ "resource": "" }
q241299
DownloadManager.resolvePackageInstallPreference
validation
protected function resolvePackageInstallPreference(PackageInterface $package) { foreach ($this->packagePreferences as $pattern => $preference) { $pattern = '{^'.str_replace('\\*', '.*', preg_quote($pattern)).'$}i'; if (preg_match($pattern, $package->getName())) { if ('dist' === $preference || (!$package->isDev() && 'auto' === $preference)) { return 'dist'; } return 'source'; } } return $package->isDev() ? 'source' : 'dist'; }
php
{ "resource": "" }