_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q256200
CommandControllerCommand.configure
test
protected function configure() { $this->setDescription($this->commandDefinition->getShortDescription()); $this->setHelp($this->commandDefinition->getDescription()); $strict = $this->commandDefinition->shouldValidateInputStrict(); if (!$strict) { $this->ignoreValidationErrors(); } $this->setDefinition($this->commandDefinition->getInputDefinitions()); }
php
{ "resource": "" }
q256201
CommandControllerCommand.execute
test
protected function execute(InputInterface $input, OutputInterface $output) { // @deprecated in 5.0 will be removed in 6.0 $givenCommandName = $input->getArgument('command'); $debugOutput = $output; if ($output instanceof ConsoleOutput) { $debugOutput = $output->getErrorOutput(); } if ($givenCommandName === $this->getAliases()[0]) { $debugOutput->writeln('<warning>Specifying the full command name is deprecated.</warning>'); $debugOutput->writeln(sprintf('<warning>Please use "%s" as command name instead.</warning>', $this->getName())); } if ($this->isLateCommand && $output->isVerbose()) { $debugOutput->writeln('<warning>Registering commands via $GLOBALS[\'TYPO3_CONF_VARS\'][\'SC_OPTIONS\'][\'extbase\'][\'commandControllers\'] is deprecated and will be removed with 6.0. Register Symfony commands in Configuration/Commands.php instead.</warning>'); } $response = (new RequestHandler())->handle($this->commandDefinition, $input, $output); return $response->getExitCode(); }
php
{ "resource": "" }
q256202
Kernel.ensureRequiredEnvironment
test
private function ensureRequiredEnvironment() { if (!in_array(PHP_SAPI, ['cli', 'phpdbg'], true) || !isset($_SERVER['argc'], $_SERVER['argv'])) { echo 'The command line must be executed with a cli PHP binary! The current PHP sapi type is "' . PHP_SAPI . '".' . PHP_EOL; exit(1); } if (ini_get('memory_limit') !== '-1') { @ini_set('memory_limit', '-1'); } if (ini_get('max_execution_time') !== '0') { @ini_set('max_execution_time', '0'); } }
php
{ "resource": "" }
q256203
Kernel.initializeCompatibilityLayer
test
public static function initializeCompatibilityLayer(ClassLoader $classLoader) { $typo3Branch = '95'; if (method_exists(Bootstrap::class, 'setCacheHashOptions')) { $typo3Branch = '87'; } if ($typo3Branch === '95') { return; } $classLoader = self::$nonComposerCompatClassLoader ?? $classLoader; $compatibilityNamespace = 'Helhum\\Typo3Console\\TYPO3v' . $typo3Branch . '\\'; spl_autoload_register(function ($className) use ($classLoader, $compatibilityNamespace) { if (strpos($className, 'Helhum\\Typo3Console\\') !== 0) { // We don't care about classes that are not within our namespace return; } $compatibilityClassName = str_replace('Helhum\\Typo3Console\\', $compatibilityNamespace, $className); if ($file = $classLoader->findFile($compatibilityClassName)) { require $file; class_alias($compatibilityClassName, $className); } }, true, true); }
php
{ "resource": "" }
q256204
Kernel.handle
test
public function handle(InputInterface $input): int { $this->initialize(); $commandCollection = new CommandCollection( $this->runLevel, new CommandConfiguration(GeneralUtility::makeInstance(PackageManager::class)) ); $application = new Application($this->runLevel, CompatibilityScripts::isComposerMode()); $application->setCommandLoader($commandCollection); // Try to resolve short command names and aliases $givenCommandName = $input->getFirstArgument() ?: 'list'; $commandNameCandidate = $commandCollection->find($givenCommandName); if ($this->runLevel->isCommandAvailable($commandNameCandidate)) { $this->runLevel->runSequenceForCommand($commandNameCandidate); // @deprecated will be removed once command controller support is removed if ($this->runLevel->getRunLevelForCommand($commandNameCandidate) !== RunLevel::LEVEL_ESSENTIAL) { $commandCollection->addCommandControllerCommands($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'] ?? []); $commandName = $commandCollection->find($givenCommandName); if ($commandNameCandidate !== $commandName) { // Mitigate #779 and #778 at least when command controller commands conflict with non low level // previously registered commands $this->runLevel->runSequenceForCommand($commandName); } } } return $application->run($input); }
php
{ "resource": "" }
q256205
ExceptionRenderer.render
test
public function render(\Throwable $exception, OutputInterface $output, Application $application = null) { if (getenv('TYPO3_CONSOLE_SUB_PROCESS')) { $output->write(\json_encode($this->serializeException($exception)), false, OutputInterface::VERBOSITY_QUIET); return; } $output->writeln('', OutputInterface::VERBOSITY_QUIET); do { $this->outputException($exception, $output); if ($output->isVerbose()) { $this->outputCode($exception, $output); $this->outputCommand($exception, $output); $this->outputTrace($exception, $output); $output->writeln(''); } $exception = $exception->getPrevious(); if ($exception) { $output->writeln('<comment>Caused by:</comment>', OutputInterface::VERBOSITY_QUIET); } } while ($exception); $this->outputSynopsis($output, $application); }
php
{ "resource": "" }
q256206
ExceptionRenderer.outputException
test
private function outputException(\Throwable $exception, OutputInterface $output) { $exceptionClass = get_class($exception); if ($exception instanceof SubProcessException) { $exceptionClass = $exception->getPreviousExceptionClass(); } $title = sprintf('[ %s ]', $exceptionClass); $messageLength = Helper::strlen($title); $maxWidth = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX; $lines = []; foreach (preg_split('/\r?\n/', trim($exception->getMessage())) as $line) { foreach ($this->splitStringByWidth($line, $maxWidth - 4) as $splitLine) { $lines[] = $splitLine; $messageLength = max(Helper::strlen($splitLine), $messageLength); } } $messages = []; $messages[] = $emptyLine = $this->padMessage('', $messageLength); $messages[] = $this->padMessage($title, $messageLength); foreach ($lines as $line) { $messages[] = $this->padMessage(OutputFormatter::escape($line), $messageLength); } $messages[] = $emptyLine; $messages[] = ''; $output->writeln($messages, OutputInterface::VERBOSITY_QUIET); }
php
{ "resource": "" }
q256207
ExceptionRenderer.outputTrace
test
private function outputTrace(\Throwable $exception, OutputInterface $output) { $output->writeln('<comment>Exception trace:</comment>'); $backtraceSteps = $this->getTrace($exception); foreach ($backtraceSteps as $index => $step) { $traceLine = '#' . $index . ' '; if (isset($backtraceSteps[$index]['class'])) { $traceLine .= $backtraceSteps[$index]['class']; } if (isset($backtraceSteps[$index]['function'])) { $traceLine .= (isset($backtraceSteps[$index]['class']) ? $backtraceSteps[$index]['type'] : '') . $backtraceSteps[$index]['function'] . '()'; } $output->writeln(sprintf('<info>%s</info>', $traceLine)); if (isset($backtraceSteps[$index]['file'])) { $output->writeln(' ' . $this->getPossibleShortenedFileName($backtraceSteps[$index]['file']) . (isset($backtraceSteps[$index]['line']) ? ':' . $backtraceSteps[$index]['line'] : '')); } } }
php
{ "resource": "" }
q256208
ExceptionRenderer.getPossibleShortenedFileName
test
private function getPossibleShortenedFileName($fileName): string { $pathPrefixes = []; if (getenv('TYPO3_PATH_COMPOSER_ROOT')) { $pathPrefixes = [getenv('TYPO3_PATH_COMPOSER_ROOT') . '/']; } $pathPrefixes[] = PATH_site; $fileName = str_replace($pathPrefixes, '', $fileName); $pathPosition = strpos($fileName, 'typo3conf/ext/'); $pathAndFilename = ($pathPosition !== false) ? substr($fileName, $pathPosition) : $fileName; $pathPosition = strpos($pathAndFilename, 'typo3/sysext/'); return ($pathPosition !== false) ? substr($pathAndFilename, $pathPosition) : $pathAndFilename; }
php
{ "resource": "" }
q256209
HelpCommandController.errorCommand
test
public function errorCommand(\TYPO3\CMS\Extbase\Mvc\Exception\CommandException $exception) { $this->outputLine('<error>%s</error>', [$exception->getMessage()]); if ($exception instanceof \TYPO3\CMS\Extbase\Mvc\Exception\AmbiguousCommandIdentifierException) { $this->outputLine('Please specify the complete command identifier. Matched commands:'); foreach ($exception->getMatchingCommands() as $matchingCommand) { $this->outputLine(' %s', [$matchingCommand->getCommandIdentifier()]); } } $this->outputLine(); $this->outputLine('See <info>list</info> for an overview of all available commands'); $this->outputLine('or <info>help</info> <command> for a detailed description of the corresponding command.'); $this->quit(1); }
php
{ "resource": "" }
q256210
DatabaseCommandController.importCommand
test
public function importCommand($interactive = false, string $connection = 'Default') { $availableConnectionNames = $this->connectionConfiguration->getAvailableConnectionNames('mysql'); if (empty($availableConnectionNames) || !in_array($connection, $availableConnectionNames, true)) { $this->output('<error>No suitable MySQL connection found for import.</error>'); $this->quit(2); } $mysqlCommand = new MysqlCommand($this->connectionConfiguration->build($connection), [], $this->output->getSymfonyConsoleOutput()); $exitCode = $mysqlCommand->mysql( $interactive ? [] : ['--skip-column-names'], STDIN, null, $interactive ); $this->quit($exitCode); }
php
{ "resource": "" }
q256211
UpgradeHandling.executeInSubProcess
test
public function executeInSubProcess($command, array $arguments = [], array &$messages = []) { $messages = $this->ensureUpgradeIsPossible(); return @unserialize($this->commandDispatcher->executeCommand('upgrade:subprocess', [$command, serialize($arguments)])); }
php
{ "resource": "" }
q256212
ExtensionSetupResultRenderer.renderSchemaResult
test
public function renderSchemaResult(ConsoleOutput $output, SchemaUpdateResultRenderer $schemaUpdateResultRenderer = null) { if (!isset($this->results['renderSchemaResult'])) { return; } $result = reset($this->results['renderSchemaResult']); if ($result->hasPerformedUpdates()) { $schemaUpdateResultRenderer = $schemaUpdateResultRenderer ?: new SchemaUpdateResultRenderer(); $output->outputLine('<info>The following database schema updates were performed:</info>'); $schemaUpdateResultRenderer->render($result, $output, true); } else { $output->outputLine( '<info>No schema updates were performed for update types:%s</info>', [ PHP_EOL . '"' . implode('", "', SchemaUpdateType::expandSchemaUpdateTypes(['safe'])) . '"', ] ); } }
php
{ "resource": "" }
q256213
ExtensionSetupResultRenderer.renderImportedStaticDataResult
test
public function renderImportedStaticDataResult(ConsoleOutput $output) { if (!isset($this->results['renderImportedStaticDataResult'])) { return; } foreach ($this->results['renderImportedStaticDataResult'] as $pathToStaticSqlFile) { // Output content of $pathToStaticSqlFile at cli context $absolutePath = PATH_site . $pathToStaticSqlFile; if (file_exists($absolutePath)) { $output->outputFormatted('<info>Import content of file "%s" into database.</info>', [$pathToStaticSqlFile]); $output->outputFormatted(file_get_contents($absolutePath), [], 2); } } }
php
{ "resource": "" }
q256214
SchemaService.updateSchema
test
public function updateSchema(array $schemaUpdateTypes, $dryRun = false) { $updateStatements = [ SchemaUpdateType::GROUP_SAFE => $this->schemaUpdate->getSafeUpdates(), SchemaUpdateType::GROUP_DESTRUCTIVE => $this->schemaUpdate->getDestructiveUpdates(), ]; $updateResult = new SchemaUpdateResult(); foreach ($schemaUpdateTypes as $schemaUpdateType) { foreach ($schemaUpdateType->getStatementTypes() as $statementType => $statementGroup) { if (isset($updateStatements[$statementGroup][$statementType])) { $statements = $updateStatements[$statementGroup][$statementType]; if (empty($statements)) { continue; } if ($dryRun) { $updateResult->addPerformedUpdates($schemaUpdateType, $statements); } else { $result = $this->schemaUpdate->migrate( $statements, // Generate a map of statements as keys and true as values array_combine(array_keys($statements), array_fill(0, count($statements), true)) ); if (empty($result)) { $updateResult->addPerformedUpdates($schemaUpdateType, $statements); } else { $updateResult->addErrors($schemaUpdateType, $result, $statements); } } } } } $this->emitDatabaseUpdateSignal($updateResult); return $updateResult; }
php
{ "resource": "" }
q256215
RunLevel.buildSequence
test
private function buildSequence(string $runLevel): Sequence { if (is_callable([$this, $runLevel])) { return $this->{$runLevel}($runLevel); } throw new InvalidArgumentException('Invalid run level "' . $runLevel . '"', 1402075492); }
php
{ "resource": "" }
q256216
RunLevel.buildEssentialSequence
test
private function buildEssentialSequence(string $identifier): Sequence { $sequence = new Sequence($identifier); $this->addStep($sequence, 'helhum.typo3console:coreconfiguration'); $this->addStep($sequence, 'helhum.typo3console:providecleanclassimplementations'); $this->addStep($sequence, 'helhum.typo3console:disabledcaching'); $this->addStep($sequence, 'helhum.typo3console:errorhandling'); return $sequence; }
php
{ "resource": "" }
q256217
RunLevel.buildBasicRuntimeSequence
test
private function buildBasicRuntimeSequence(string $identifier = self::LEVEL_MINIMAL): Sequence { $sequence = $this->buildEssentialSequence($identifier); $this->addStep($sequence, 'helhum.typo3console:extensionconfiguration'); return $sequence; }
php
{ "resource": "" }
q256218
CacheCommandController.flushGroupsCommand
test
public function flushGroupsCommand(array $groups) { try { $this->cacheService->flushGroups($groups); $this->outputLine('Flushed all caches for group(s): "' . implode('","', $groups) . '".'); } catch (NoSuchCacheGroupException $e) { $this->outputLine($e->getMessage()); $this->quit(1); } }
php
{ "resource": "" }
q256219
CacheCommandController.flushTagsCommand
test
public function flushTagsCommand(array $tags, array $groups = null) { try { $this->cacheService->flushByTagsAndGroups($tags, $groups); if ($groups === null) { $this->outputLine('Flushed caches by tags "' . implode('","', $tags) . '".'); } else { $this->outputLine('Flushed caches by tags "' . implode('","', $tags) . '" in groups: "' . implode('","', $groups) . '".'); } } catch (NoSuchCacheGroupException $e) { $this->outputLine($e->getMessage()); $this->quit(1); } }
php
{ "resource": "" }
q256220
CacheCommandController.listGroupsCommand
test
public function listGroupsCommand() { $groups = $this->cacheService->getValidCacheGroups(); sort($groups); switch (count($groups)) { case 0: $this->outputLine('No cache groups are registered.'); break; case 1: $this->outputLine('The following cache group is registered: "' . implode('", "', $groups) . '".'); break; default: $this->outputLine('The following cache groups are registered: "' . implode('", "', $groups) . '".'); break; } }
php
{ "resource": "" }
q256221
Invokable.hydrate
test
private function hydrate(): void { if (null !== $this->values) { return; } $values = \call_user_func_array($this->callable, $this->callableArgs); if (false === \is_array($values)) { throw new InvalidArgumentException( 'Dictionary callable must return an array or an instance of ArrayAccess.' ); } $this->values = $values; }
php
{ "resource": "" }
q256222
Traceable.trace
test
private function trace(): void { $this->collector->addDictionary( $this->dictionary->getName(), $this->dictionary->getKeys(), array_values($this->dictionary->getValues()) ); }
php
{ "resource": "" }
q256223
ManagerController.retrieveFilesNumber
test
private function retrieveFilesNumber($path, $regex) { $files = new Finder(); $files->in($path)->files()->depth(0)->name($regex); return iterator_count($files); }
php
{ "resource": "" }
q256224
AbstractRestRequest.toJSON
test
public function toJSON($data, $options = 0) { // Because of PHP Version 5.3, we cannot use JSON_UNESCAPED_SLASHES option // Instead we would use the str_replace command for now. // TODO: Replace this code with return json_encode($this->toArray(), $options | 64); once we support PHP >= 5.4 if (version_compare(phpversion(), '5.4.0', '>=') === true) { return json_encode($data, $options | 64); } return str_replace('\\/', '/', json_encode($data, $options)); }
php
{ "resource": "" }
q256225
RestAuthorizeRequest.getDescription
test
public function getDescription() { $id = $this->getTransactionId(); $desc = parent::getDescription(); if (empty($id)) { return $desc; } elseif (empty($desc)) { return $id; } else { return "$id : $desc"; } }
php
{ "resource": "" }
q256226
RestGateway.getToken
test
public function getToken($createIfNeeded = true) { if ($createIfNeeded && !$this->hasToken()) { $response = $this->createToken()->send(); if ($response->isSuccessful()) { $data = $response->getData(); if (isset($data['access_token'])) { $this->setToken($data['access_token']); $this->setTokenExpires(time() + $data['expires_in']); } } } return $this->getParameter('token'); }
php
{ "resource": "" }
q256227
RestGateway.hasToken
test
public function hasToken() { $token = $this->getParameter('token'); $expires = $this->getTokenExpires(); if (!empty($expires) && !is_numeric($expires)) { $expires = strtotime($expires); } return !empty($token) && time() < $expires; }
php
{ "resource": "" }
q256228
RestListPurchaseRequest.setStartTime
test
public function setStartTime($value) { if ($value instanceof \DateTime) { $value->setTimezone(new \DateTimeZone('UTC')); $value = $value->format('Y-m-d\TH:i:s\Z'); } return $this->setParameter('startTime', $value); }
php
{ "resource": "" }
q256229
RestListPurchaseRequest.setEndTime
test
public function setEndTime($value) { if ($value instanceof \DateTime) { $value->setTimezone(new \DateTimeZone('UTC')); $value = $value->format('Y-m-d\TH:i:s\Z'); } return $this->setParameter('endTime', $value); }
php
{ "resource": "" }
q256230
IssuesBank.getAll
test
public function getAll($type) { $all = []; foreach ($this->issues as $version => $issues) { if (isset($issues[$type])) { foreach ($issues[$type] as $issue_name => $issue_value) { if (is_int($issue_name)) { /** * If issue does not have a key (for example, function does not have a replacement), it sets key to that function. * That because scanner looks for methods/functions/variables in keys, not in values. * Exception: if issue with type `function_usage` does not have a key, it just adds with numeric key. */ if ($type !== 'functions_usage') $all[$issue_value] = array($issue_value, $version); else $all[] = array($issue_value, $version); } else $all[$issue_name] = array($issue_value, $version); } } } return $all; }
php
{ "resource": "" }
q256231
Application.run
test
public function run() { try { $this->setTarget(); $this->setMaxSize(); $this->setExcludeList(); $this->setSkipChecks(); $this->setFileExtensions(); $this->scanFiles(); $this->printReport(); $this->printMemoryUsage(); if ($this->hasIssue) exit(1); } catch (Exception $e) { $this->exitWithError($e->getMessage(), 128); } }
php
{ "resource": "" }
q256232
Application.normalizeAndTruncatePath
test
public function normalizeAndTruncatePath($path, $maxLength) { $truncated = 1; $path_parts = explode('/', str_replace('\\', '/', $path)); $total_parts = count($path_parts); while (strlen($path) > $maxLength) { if (($truncated + 1) === $total_parts) break; $part_to_modify = $total_parts - 1 - $truncated; $chars_to_truncate = min(strlen($path_parts[$part_to_modify]) - 1, strlen($path) - $maxLength); if ((strlen($path) - $maxLength + 2) < strlen($path_parts[$part_to_modify])) $chars_to_truncate += 2; $path_parts[$part_to_modify] = substr($path_parts[$part_to_modify], 0, -$chars_to_truncate).'..'; $path = implode('/', $path_parts); $truncated++; } return $path; }
php
{ "resource": "" }
q256233
Application.exitWithError
test
public function exitWithError($message, $code = 128) { fwrite(STDERR, TerminalInfo::colorize($message, TerminalInfo::RED_BACKGROUND).PHP_EOL); exit($code); }
php
{ "resource": "" }
q256234
PhpCodeFixer.divideByComma
test
public static function divideByComma(array $tokens) { $delimited = []; $comma = 0; foreach ($tokens as $token) { if ($token == ',') $comma++; else $delimited[$comma][] = $token; } return $delimited; }
php
{ "resource": "" }
q256235
PhpCodeFixer.trimSpaces
test
public static function trimSpaces(array $tokens) { $trimmed = []; foreach ($tokens as $token) { if (is_array($token)) { if ($token[0] == T_WHITESPACE) continue; else $trimmed[] = self::trimSpaces($token); } else $trimmed[] = $token; } return $trimmed; }
php
{ "resource": "" }
q256236
PhpCodeFixer.callFunctionUsageChecker
test
protected static function callFunctionUsageChecker($checker, $functionName, array $callTokens) { require_once dirname(dirname(__FILE__)).'/data/'.$checker.'.php'; $checker = __NAMESPACE__ . '\\' . $checker; $result = $checker($callTokens, $functionName); return $result; }
php
{ "resource": "" }
q256237
Report.add
test
public function add($version, $type, $text, $replacement, $file, $line) { if ($this->removablePath !== null && strncasecmp($file, $this->removablePath, strlen($this->removablePath)) === 0) $file = substr($file, strlen($this->removablePath)); $this->records[$version][] = [$type, $text, $replacement, $file, $line]; }
php
{ "resource": "" }
q256238
TerminalInfo.isColorsCapable
test
static public function isColorsCapable() { if (self::$colorsCapability === null) { if (!static::isUnixPlatform()) self::$colorsCapability = false; else if (!static::isInteractive()) self::$colorsCapability = false; else { $tput_presence = static::exec('which tput'); if (strlen(trim($tput_presence[0])) === 0) self::$colorsCapability = false; else { $tput_colors = static::exec('tput colors'); self::$colorsCapability = (int)$tput_colors[0] > 0; } } } return self::$colorsCapability; }
php
{ "resource": "" }
q256239
TerminalInfo.getWindowsTerminalSize
test
static protected function getWindowsTerminalSize() { $output = self::exec('mode', $returnCode); if ($returnCode !== 0) return [25, 80]; foreach ($output as $i => $line) { if (strpos($line, ' CON') !== false) { $sizes = [$output[$i + 2], $output[$i + 3]]; break; } } if (!isset($sizes)) return [25, 80]; return array_map(function($val) { list(, $val) = explode(':', $val); return trim($val); }, $sizes); }
php
{ "resource": "" }
q256240
AutoloadSourceLocator.attemptAutoloadForIdentifier
test
private function attemptAutoloadForIdentifier(Identifier $identifier) : ?string { if ($identifier->isClass()) { return $this->locateClassByName($identifier->getName()); } if ($identifier->isFunction()) { return $this->locateFunctionByName($identifier->getName()); } return null; }
php
{ "resource": "" }
q256241
AutoloadSourceLocator.locateClassByName
test
private function locateClassByName(string $className) : ?string { if (class_exists($className, false) || interface_exists($className, false) || trait_exists($className, false)) { $filename = (new ReflectionClass($className))->getFileName(); if (! is_string($filename)) { return null; } return $filename; } self::$autoloadLocatedFile = null; self::$currentAstLocator = $this->astLocator; // passing the locator on to the implicitly instantiated `self` $previousErrorHandler = set_error_handler(static function () : void { }); stream_wrapper_unregister('file'); stream_wrapper_register('file', self::class); class_exists($className); stream_wrapper_restore('file'); set_error_handler($previousErrorHandler); return self::$autoloadLocatedFile; }
php
{ "resource": "" }
q256242
AutoloadSourceLocator.locateFunctionByName
test
private function locateFunctionByName(string $functionName) : ?string { if (! function_exists($functionName)) { return null; } $reflection = new ReflectionFunction($functionName); $reflectionFileName = $reflection->getFileName(); if (! is_string($reflectionFileName)) { return null; } return $reflectionFileName; }
php
{ "resource": "" }
q256243
AutoloadSourceLocator.stream_open
test
public function stream_open($path, $mode, $options, &$opened_path) : bool { self::$autoloadLocatedFile = $path; return false; }
php
{ "resource": "" }
q256244
AutoloadSourceLocator.url_stat
test
public function url_stat($path, $flags) { stream_wrapper_restore('file'); if ($flags & STREAM_URL_STAT_QUIET) { set_error_handler(static function () { // Use native error handler return false; }); $result = @stat($path); restore_error_handler(); } else { $result = stat($path); } stream_wrapper_unregister('file'); stream_wrapper_register('file', self::class); return $result; }
php
{ "resource": "" }
q256245
CompileNodeToValue.compileConstFetch
test
private function compileConstFetch(Node\Expr\ConstFetch $constNode, CompilerContext $context) { $firstName = reset($constNode->name->parts); switch ($firstName) { case 'null': return null; case 'false': return false; case 'true': return true; default: if (! defined($firstName)) { throw Exception\UnableToCompileNode::becauseOfNotFoundConstantReference($context, $constNode); } return constant($firstName); } }
php
{ "resource": "" }
q256246
CompileNodeToValue.compileClassConstFetch
test
private function compileClassConstFetch(Node\Expr\ClassConstFetch $node, CompilerContext $context) { /** @var Node\Identifier $node->name */ $nodeName = $node->name->name; /** @var Node\Name $node->class */ $className = $node->class->toString(); if ($nodeName === 'class') { return $className; } /** @var ReflectionClass|null $classInfo */ $classInfo = null; if ($className === 'self' || $className === 'static') { $classInfo = $this->getConstantDeclaringClass($nodeName, $context->getSelf()); } if ($classInfo === null) { /** @var ReflectionClass $classInfo */ $classInfo = $context->getReflector()->reflect($className); } $reflectionConstant = $classInfo->getReflectionConstant($nodeName); if (! $reflectionConstant instanceof ReflectionClassConstant) { throw Exception\UnableToCompileNode::becauseOfNotFoundClassConstantReference($context, $classInfo, $node); } return $this->__invoke( $reflectionConstant->getAst()->consts[$reflectionConstant->getPositionInAst()]->value, new CompilerContext($context->getReflector(), $classInfo) ); }
php
{ "resource": "" }
q256247
FindReflectionOnLine.computeReflections
test
private function computeReflections(string $filename) : array { $singleFileSourceLocator = new SingleFileSourceLocator($filename, $this->astLocator); $reflector = new ClassReflector(new AggregateSourceLocator([$singleFileSourceLocator, $this->sourceLocator])); return array_merge( $singleFileSourceLocator->locateIdentifiersByType($reflector, new IdentifierType(IdentifierType::IDENTIFIER_CLASS)), $singleFileSourceLocator->locateIdentifiersByType($reflector, new IdentifierType(IdentifierType::IDENTIFIER_FUNCTION)) ); }
php
{ "resource": "" }
q256248
FindReflectionOnLine.containsLine
test
private function containsLine($reflection, int $lineNumber) : bool { if (! method_exists($reflection, 'getStartLine')) { throw new InvalidArgumentException('Reflection does not have getStartLine method'); } if (! method_exists($reflection, 'getEndLine')) { throw new InvalidArgumentException('Reflection does not have getEndLine method'); } return $lineNumber >= $reflection->getStartLine() && $lineNumber <= $reflection->getEndLine(); }
php
{ "resource": "" }
q256249
ClassReflector.getAllClasses
test
public function getAllClasses() : array { /** @var ReflectionClass[] $allClasses */ $allClasses = $this->sourceLocator->locateIdentifiersByType( $this, new IdentifierType(IdentifierType::IDENTIFIER_CLASS) ); return $allClasses; }
php
{ "resource": "" }
q256250
ReflectionProperty.createFromName
test
public static function createFromName(string $className, string $propertyName) : self { return ReflectionClass::createFromName($className)->getProperty($propertyName); }
php
{ "resource": "" }
q256251
ReflectionProperty.createFromInstance
test
public static function createFromInstance($instance, string $propertyName) : self { return ReflectionClass::createFromInstance($instance)->getProperty($propertyName); }
php
{ "resource": "" }
q256252
ReflectionProperty.getDocBlockTypeStrings
test
public function getDocBlockTypeStrings() : array { $stringTypes = []; foreach ($this->getDocBlockTypes() as $type) { $stringTypes[] = (string) $type; } return $stringTypes; }
php
{ "resource": "" }
q256253
Locator.findReflectionsOfType
test
public function findReflectionsOfType( Reflector $reflector, LocatedSource $locatedSource, IdentifierType $identifierType ) : array { try { return $this->findReflectionsInTree->__invoke( $reflector, $this->parser->parse($locatedSource->getSource()), $identifierType, $locatedSource ); } catch (Throwable $exception) { throw Exception\ParseToAstFailure::fromLocatedSource($locatedSource, $exception); } }
php
{ "resource": "" }
q256254
Locator.findInArray
test
private function findInArray(array $reflections, Identifier $identifier) : Reflection { $identifierName = strtolower($identifier->getName()); foreach ($reflections as $reflection) { if (strtolower($reflection->getName()) === $identifierName) { return $reflection; } } throw IdentifierNotFound::fromIdentifier($identifier); }
php
{ "resource": "" }
q256255
ReflectionParameter.createFromClassNameAndMethod
test
public static function createFromClassNameAndMethod( string $className, string $methodName, string $parameterName ) : self { return ReflectionClass::createFromName($className) ->getMethod($methodName) ->getParameter($parameterName); }
php
{ "resource": "" }
q256256
ReflectionParameter.createFromClassInstanceAndMethod
test
public static function createFromClassInstanceAndMethod( $instance, string $methodName, string $parameterName ) : self { return ReflectionClass::createFromInstance($instance) ->getMethod($methodName) ->getParameter($parameterName); }
php
{ "resource": "" }
q256257
ReflectionParameter.createFromClosure
test
public static function createFromClosure(Closure $closure, string $parameterName) : ReflectionParameter { return ReflectionFunction::createFromClosure($closure) ->getParameter($parameterName); }
php
{ "resource": "" }
q256258
ReflectionParameter.allowsNull
test
public function allowsNull() : bool { if (! $this->hasType()) { return true; } if ($this->node->type instanceof NullableType) { return true; } if (! $this->isDefaultValueAvailable()) { return false; } return $this->getDefaultValue() === null; }
php
{ "resource": "" }
q256259
ReflectionParameter.getType
test
public function getType() : ?ReflectionType { $type = $this->node->type; if ($type === null) { return null; } if ($type instanceof NullableType) { $type = $type->type; } return ReflectionType::createFromTypeAndReflector((string) $type, $this->allowsNull(), $this->reflector); }
php
{ "resource": "" }
q256260
ReflectionParameter.setType
test
public function setType(string $newParameterType) : void { $this->node->type = new Node\Name($newParameterType); }
php
{ "resource": "" }
q256261
FunctionReflector.getAllFunctions
test
public function getAllFunctions() : array { /** @var ReflectionFunction[] $allFunctions */ $allFunctions = $this->sourceLocator->locateIdentifiersByType( $this, new IdentifierType(IdentifierType::IDENTIFIER_FUNCTION) ); return $allFunctions; }
php
{ "resource": "" }
q256262
ReflectionMethod.createFromName
test
public static function createFromName(string $className, string $methodName) : self { return ReflectionClass::createFromName($className)->getMethod($methodName); }
php
{ "resource": "" }
q256263
ReflectionMethod.createFromInstance
test
public static function createFromInstance($instance, string $methodName) : self { return ReflectionClass::createFromInstance($instance)->getMethod($methodName); }
php
{ "resource": "" }
q256264
ReflectionMethod.getPrototype
test
public function getPrototype() : self { $currentClass = $this->getDeclaringClass(); while ($currentClass) { foreach ($currentClass->getImmediateInterfaces() as $interface) { if ($interface->hasMethod($this->getName())) { return $interface->getMethod($this->getName()); } } $currentClass = $currentClass->getParentClass(); if ($currentClass === null || ! $currentClass->hasMethod($this->getName())) { break; } $prototype = $currentClass->getMethod($this->getName())->findPrototype(); if ($prototype !== null) { return $prototype; } } throw new Exception\MethodPrototypeNotFound(sprintf( 'Method %s::%s does not have a prototype', $this->getDeclaringClass()->getName(), $this->getName() )); }
php
{ "resource": "" }
q256265
ReflectionMethod.isConstructor
test
public function isConstructor() : bool { if (strtolower($this->getName()) === '__construct') { return true; } $declaringClass = $this->getDeclaringClass(); if ($declaringClass->inNamespace()) { return false; } return strtolower($this->getName()) === strtolower($declaringClass->getShortName()); }
php
{ "resource": "" }
q256266
ReflectionClass.export
test
public static function export(?string $className) : string { if ($className === null) { throw new InvalidArgumentException('Class name must be provided'); } return self::createFromName($className)->__toString(); }
php
{ "resource": "" }
q256267
ReflectionClass.createFromNode
test
public static function createFromNode( Reflector $reflector, ClassLikeNode $node, LocatedSource $locatedSource, ?NamespaceNode $namespace = null ) : self { $class = new self(); $class->reflector = $reflector; $class->locatedSource = $locatedSource; $class->node = $node; if ($namespace !== null) { $class->declaringNamespace = $namespace; } return $class; }
php
{ "resource": "" }
q256268
ReflectionClass.getAllMethods
test
private function getAllMethods() : array { return array_merge( [], array_map( function (ClassMethod $methodNode) : ReflectionMethod { return ReflectionMethod::createFromNode( $this->reflector, $methodNode, $this->declaringNamespace, $this, $this ); }, $this->node->getMethods() ), ...array_map( function (ReflectionClass $trait) : array { return array_map(function (ReflectionMethod $method) use ($trait) : ReflectionMethod { /** @var ClassMethod $methodAst */ $methodAst = $method->getAst(); return ReflectionMethod::createFromNode( $this->reflector, $methodAst, $this->declaringNamespace, $trait, $this ); }, $trait->getMethods()); }, $this->getTraits() ), ...array_map( static function (ReflectionClass $ancestor) : array { return $ancestor->getMethods(); }, array_values(array_merge( array_filter([$this->getParentClass()]), $this->getInterfaces() )) ) ); }
php
{ "resource": "" }
q256269
ReflectionClass.getMethods
test
public function getMethods(?int $filter = null) : array { if ($filter === null) { return array_values($this->getMethodsIndexedByName()); } return array_values( array_filter( $this->getMethodsIndexedByName(), static function (ReflectionMethod $method) use ($filter) : bool { return (bool) ($filter & $method->getModifiers()); } ) ); }
php
{ "resource": "" }
q256270
ReflectionClass.hasMethod
test
public function hasMethod(string $methodName) : bool { try { $this->getMethod($methodName); return true; } catch (OutOfBoundsException $exception) { return false; } }
php
{ "resource": "" }
q256271
ReflectionClass.getConstant
test
public function getConstant(string $name) { $reflectionConstant = $this->getReflectionConstant($name); if (! $reflectionConstant) { return null; } return $reflectionConstant->getValue(); }
php
{ "resource": "" }
q256272
ReflectionClass.getConstructor
test
public function getConstructor() : ReflectionMethod { $constructors = array_filter($this->getMethods(), static function (ReflectionMethod $method) : bool { return $method->isConstructor(); }); if (! isset($constructors[0])) { throw new OutOfBoundsException('Could not find method: __construct'); } return $constructors[0]; }
php
{ "resource": "" }
q256273
ReflectionClass.getProperties
test
public function getProperties(?int $filter = null) : array { if ($this->cachedProperties === null) { // merging together properties from parent class, traits, current class (in this precise order) $this->cachedProperties = array_merge( array_merge( [], ...array_map( static function (ReflectionClass $ancestor) use ($filter) : array { return array_filter( $ancestor->getProperties($filter), static function (ReflectionProperty $property) : bool { return ! $property->isPrivate(); } ); }, array_filter([$this->getParentClass()]) ), ...array_map( function (ReflectionClass $trait) use ($filter) { return array_map(function (ReflectionProperty $property) use ($trait) : ReflectionProperty { return ReflectionProperty::createFromNode( $this->reflector, $property->getAst(), $property->getPositionInAst(), $trait->declaringNamespace, $property->getDeclaringClass(), $this ); }, $trait->getProperties($filter)); }, $this->getTraits() ) ), $this->getImmediateProperties() ); } if ($filter === null) { return $this->cachedProperties; } return array_filter( $this->cachedProperties, static function (ReflectionProperty $property) use ($filter) : bool { return (bool) ($filter & $property->getModifiers()); } ); }
php
{ "resource": "" }
q256274
ReflectionClass.getParentClass
test
public function getParentClass() : ?ReflectionClass { if (! ($this->node instanceof ClassNode) || $this->node->extends === null) { return null; } // @TODO use actual `ClassReflector` or `FunctionReflector`? /** @var self $parent */ $parent = $this->reflector->reflect($this->node->extends->toString()); if ($parent->isInterface() || $parent->isTrait()) { throw NotAClassReflection::fromReflectionClass($parent); } return $parent; }
php
{ "resource": "" }
q256275
ReflectionClass.getParentClassNames
test
public function getParentClassNames() : array { return array_map(static function (self $parentClass) : string { return $parentClass->getName(); }, array_slice(array_reverse($this->getInheritanceClassHierarchy()), 1)); }
php
{ "resource": "" }
q256276
ReflectionClass.getTraits
test
public function getTraits() : array { return array_map( function (Node\Name $importedTrait) : ReflectionClass { return $this->reflectClassForNamedNode($importedTrait); }, array_merge( [], ...array_map( static function (TraitUse $traitUse) : array { return $traitUse->traits; }, array_filter($this->node->stmts, static function (Node $node) : bool { return $node instanceof TraitUse; }) ) ) ); }
php
{ "resource": "" }
q256277
ReflectionClass.reflectClassForNamedNode
test
private function reflectClassForNamedNode(Node\Name $node) : self { // @TODO use actual `ClassReflector` or `FunctionReflector`? if ($this->isAnonymous()) { /** @var self $class */ $class = (new BetterReflection())->classReflector()->reflect($node->toString()); } else { /** @var self $class */ $class = $this->reflector->reflect($node->toString()); } return $class; }
php
{ "resource": "" }
q256278
ReflectionClass.isInstance
test
public function isInstance($object) : bool { if (! is_object($object)) { throw NotAnObject::fromNonObject($object); } $className = $this->getName(); // note: since $object was loaded, we can safely assume that $className is available in the current // php script execution context return $object instanceof $className; }
php
{ "resource": "" }
q256279
ReflectionClass.isSubclassOf
test
public function isSubclassOf(string $className) : bool { return in_array( ltrim($className, '\\'), array_map( static function (self $reflectionClass) : string { return $reflectionClass->getName(); }, array_slice(array_reverse($this->getInheritanceClassHierarchy()), 1) ), true ); }
php
{ "resource": "" }
q256280
ReflectionClass.implementsInterface
test
public function implementsInterface(string $interfaceName) : bool { return in_array(ltrim($interfaceName, '\\'), $this->getInterfaceNames(), true); }
php
{ "resource": "" }
q256281
ReflectionClass.isInstantiable
test
public function isInstantiable() : bool { // @TODO doesn't consider internal non-instantiable classes yet. if ($this->isAbstract()) { return false; } if ($this->isInterface()) { return false; } if ($this->isTrait()) { return false; } try { return $this->getConstructor()->isPublic(); } catch (OutOfBoundsException $e) { return true; } }
php
{ "resource": "" }
q256282
ReflectionClass.isCloneable
test
public function isCloneable() : bool { if (! $this->isInstantiable()) { return false; } if (! $this->hasMethod('__clone')) { return true; } return $this->getMethod('__clone')->isPublic(); }
php
{ "resource": "" }
q256283
ReflectionClass.getInterfacesHierarchy
test
private function getInterfacesHierarchy() : array { if (! $this->isInterface()) { throw NotAnInterfaceReflection::fromReflectionClass($this); } /** @var InterfaceNode $node */ $node = $this->node; return array_merge( [$this->getName() => $this], ...array_map( function (Node\Name $interfaceName) : array { return $this ->reflectClassForNamedNode($interfaceName) ->getInterfacesHierarchy(); }, $node->extends ) ); }
php
{ "resource": "" }
q256284
ReflectionClass.setStaticPropertyValue
test
public function setStaticPropertyValue(string $propertyName, $value) : void { $property = $this->getProperty($propertyName); if (! $property || ! $property->isStatic()) { throw PropertyDoesNotExist::fromName($propertyName); } $property->setValue($value); }
php
{ "resource": "" }
q256285
ReflectionClass.setFinal
test
public function setFinal(bool $isFinal) : void { if (! $this->node instanceof ClassNode) { throw NotAClassReflection::fromReflectionClass($this); } if ($isFinal === true) { $this->node->flags |= ClassNode::MODIFIER_FINAL; return; } $this->node->flags &= ~ClassNode::MODIFIER_FINAL; }
php
{ "resource": "" }
q256286
ReflectionClass.removeMethod
test
public function removeMethod(string $methodName) : bool { $lowerName = strtolower($methodName); foreach ($this->node->stmts as $key => $stmt) { if ($stmt instanceof ClassMethod && $lowerName === $stmt->name->toLowerString()) { unset($this->node->stmts[$key], $this->cachedMethods); return true; } } return false; }
php
{ "resource": "" }
q256287
ReflectionClass.addMethod
test
public function addMethod(string $methodName) : void { $this->node->stmts[] = new ClassMethod($methodName); unset($this->cachedMethods); }
php
{ "resource": "" }
q256288
ReflectionClass.addProperty
test
public function addProperty( string $propertyName, int $visibility = CoreReflectionProperty::IS_PUBLIC, bool $static = false ) : void { $type = 0; switch ($visibility) { case CoreReflectionProperty::IS_PRIVATE: $type |= ClassNode::MODIFIER_PRIVATE; break; case CoreReflectionProperty::IS_PROTECTED: $type |= ClassNode::MODIFIER_PROTECTED; break; default: $type |= ClassNode::MODIFIER_PUBLIC; break; } if ($static) { $type |= ClassNode::MODIFIER_STATIC; } $this->node->stmts[] = new PropertyNode($type, [new Node\Stmt\PropertyProperty($propertyName)]); $this->cachedProperties = null; $this->cachedImmediateProperties = null; }
php
{ "resource": "" }
q256289
ReflectionClass.removeProperty
test
public function removeProperty(string $propertyName) : bool { $lowerName = strtolower($propertyName); foreach ($this->node->stmts as $key => $stmt) { if (! ($stmt instanceof PropertyNode)) { continue; } $propertyNames = array_map(static function (Node\Stmt\PropertyProperty $propertyProperty) : string { return $propertyProperty->name->toLowerString(); }, $stmt->props); if (in_array($lowerName, $propertyNames, true)) { $this->cachedProperties = null; $this->cachedImmediateProperties = null; unset($this->node->stmts[$key]); return true; } } return false; }
php
{ "resource": "" }
q256290
IdentifierType.isMatchingReflector
test
public function isMatchingReflector(Reflection $reflector) : bool { if ($this->name === self::IDENTIFIER_CLASS) { return $reflector instanceof ReflectionClass; } if ($this->name === self::IDENTIFIER_FUNCTION) { return $reflector instanceof ReflectionFunction; } return false; }
php
{ "resource": "" }
q256291
ReflectionObject.export
test
public static function export($instance = null) : string { if ($instance === null) { throw new InvalidArgumentException('Class instance must be provided'); } return self::createFromInstance($instance)->__toString(); }
php
{ "resource": "" }
q256292
ReflectionObject.createFromInstance
test
public static function createFromInstance($object) : ReflectionClass { if (! is_object($object)) { throw new InvalidArgumentException('Can only create from an instance of an object'); } $className = get_class($object); if (strpos($className, ReflectionClass::ANONYMOUS_CLASS_NAME_PREFIX) === 0) { $reflector = new ClassReflector(new AnonymousClassObjectSourceLocator( $object, (new BetterReflection())->phpParser() )); } else { $reflector = (new BetterReflection())->classReflector(); } return new self($reflector, $reflector->reflect($className), $object); }
php
{ "resource": "" }
q256293
ReflectionObject.getRuntimeProperties
test
private function getRuntimeProperties(?int $filter = null) : array { if (! $this->reflectionClass->isInstance($this->object)) { throw new InvalidArgumentException('Cannot reflect runtime properties of a separate class'); } // Ensure we have already cached existing properties so we can add to them $this->reflectionClass->getProperties(); // Only known current way is to use internal ReflectionObject to get // the runtime-declared properties :/ $reflectionProperties = (new CoreReflectionObject($this->object))->getProperties(); $runtimeProperties = []; foreach ($reflectionProperties as $property) { if ($this->reflectionClass->hasProperty($property->getName())) { continue; } $reflectionProperty = $this->reflectionClass->getProperty($property->getName()); $runtimeProperty = ReflectionProperty::createFromNode( $this->reflector, $this->createPropertyNodeFromReflection($property, $this->object), 0, $reflectionProperty ? $reflectionProperty->getDeclaringClass()->getDeclaringNamespaceAst() : null, $this, $this, false ); if ($filter !== null && ! ($filter & $runtimeProperty->getModifiers())) { continue; } $runtimeProperties[$runtimeProperty->getName()] = $runtimeProperty; } return $runtimeProperties; }
php
{ "resource": "" }
q256294
ReflectionObject.createPropertyNodeFromReflection
test
private function createPropertyNodeFromReflection(CoreReflectionProperty $property, $instance) : PropertyNode { $builder = new PropertyNodeBuilder($property->getName()); $builder->setDefault($property->getValue($instance)); if ($property->isPublic()) { $builder->makePublic(); } return $builder->getNode(); }
php
{ "resource": "" }
q256295
ReflectionFunctionAbstract.populateFunctionAbstract
test
protected function populateFunctionAbstract( Reflector $reflector, Node\FunctionLike $node, LocatedSource $locatedSource, ?NamespaceNode $declaringNamespace = null ) : void { $this->reflector = $reflector; $this->node = $node; $this->locatedSource = $locatedSource; $this->declaringNamespace = $declaringNamespace; $this->setNodeOptionalFlag(); }
php
{ "resource": "" }
q256296
ReflectionFunctionAbstract.setNodeOptionalFlag
test
private function setNodeOptionalFlag() : void { $overallOptionalFlag = true; $lastParamIndex = count($this->node->params) - 1; for ($i = $lastParamIndex; $i >= 0; $i--) { $hasDefault = ($this->node->params[$i]->default !== null); // When we find the first parameter that does not have a default, // flip the flag as all params for this are no longer optional // EVEN if they have a default value if (! $hasDefault) { $overallOptionalFlag = false; } $this->node->params[$i]->isOptional = $overallOptionalFlag; } }
php
{ "resource": "" }
q256297
ReflectionFunctionAbstract.getNumberOfRequiredParameters
test
public function getNumberOfRequiredParameters() : int { return count(array_filter( $this->getParameters(), static function (ReflectionParameter $p) : bool { return ! $p->isOptional(); } )); }
php
{ "resource": "" }
q256298
ReflectionFunctionAbstract.getParameters
test
public function getParameters() : array { $parameters = []; foreach ($this->node->params as $paramIndex => $paramNode) { $parameters[] = ReflectionParameter::createFromNode( $this->reflector, $paramNode, $this->declaringNamespace, $this, $paramIndex ); } return $parameters; }
php
{ "resource": "" }
q256299
ReflectionFunctionAbstract.getParameter
test
public function getParameter(string $parameterName) : ?ReflectionParameter { foreach ($this->getParameters() as $parameter) { if ($parameter->getName() === $parameterName) { return $parameter; } } return null; }
php
{ "resource": "" }