Your project must rely on Symfony interface instead of classes when possible 6
- Read doc
- Productivity
- Critical
More information: https://insight.symfony.com/what-we-analyse/symfony.dependency_injection.use_interface_type_hint
- * trans_sid_hosts, $_SERVER['HTTP_HOST']
- * trans_sid_tags, "a=href,area=href,frame=src,form="
- *
- * @param AbstractProxy|\SessionHandlerInterface|null $handler
- */
- public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null)
- {
- if (!\extension_loaded('session')) {
- throw new \LogicException('PHP extension "session" is required.');
- }
- /**
- * @var array|SessionBagInterface[]
- */
- protected $bags = [];
- public function __construct(string $name = 'MOCKSESSID', MetadataBag $metaBag = null)
- {
- $this->name = $name;
- $this->setMetadataBag($metaBag);
- }
- private $savePath;
- /**
- * @param string $savePath Path of directory to save session files
- */
- public function __construct(string $savePath = null, string $name = 'MOCKSESSID', MetadataBag $metaBag = null)
- {
- if (null === $savePath) {
- $savePath = sys_get_temp_dir();
- }
- class PhpBridgeSessionStorage extends NativeSessionStorage
- {
- /**
- * @param AbstractProxy|\SessionHandlerInterface|null $handler
- */
- public function __construct($handler = null, MetadataBag $metaBag = null)
- {
- if (!\extension_loaded('session')) {
- throw new \LogicException('PHP extension "session" is required.');
- }
- */
- class AddAnnotatedClassesToCachePass implements CompilerPassInterface
- {
- private $kernel;
- public function __construct(Kernel $kernel)
- {
- $this->kernel = $kernel;
- }
- /**
- 'VG' => 'GB', // British Virgin Islands
- ];
- private $propertyAccessor;
- public function __construct(PropertyAccessor $propertyAccessor = null)
- {
- $this->propertyAccessor = $propertyAccessor;
- }
- /**
Your project should not use global variables or functions 16
- Read doc
- Reliability
- Minor
More information: https://insight.symfony.com/what-we-analyse/php.use_global_variable_or_function
- if (!function_exists('dump')) {
- /**
- * @author Nicolas Grekas <[email protected]>
- */
- function dump($var, ...$moreVars)
- {
- VarDumper::dump($var);
- foreach ($moreVars as $v) {
- VarDumper::dump($v);
- return $var;
- }
- }
- if (!function_exists('dd')) {
- function dd(...$vars)
- {
- foreach ($vars as $v) {
- VarDumper::dump($v);
- }
- }
- });
- array_shift($_SERVER['argv']);
- $dirs = $_SERVER['argv'];
- function getRelevantContent(array $composerJson)
- {
- $relevantKeys = array(
- 'name',
- 'require',
- 'require-dev',
- }
- return $relevantContent;
- }
- function getContentHash(array $composerJson)
- {
- $relevantContent = getRelevantContent($composerJson);
- ksort($relevantContent);
- return md5(json_encode($relevantContent));
- chdir('..');
- file_put_contents(".$PHPUNIT_VERSION_DIR.md5", $configurationHash);
- chdir($oldPwd);
- }
- global $argv, $argc;
- $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : array();
- $argc = isset($_SERVER['argc']) ? $_SERVER['argc'] : 0;
- if ($PHPUNIT_VERSION < 8.0) {
- $argv = array_filter($argv, function ($v) use (&$argc) { if ('--do-not-cache-result' !== $v) return true; --$argc; return false; });
- chdir('..');
- file_put_contents(".$PHPUNIT_VERSION_DIR.md5", $configurationHash);
- chdir($oldPwd);
- }
- global $argv, $argc;
- $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : array();
- $argc = isset($_SERVER['argc']) ? $_SERVER['argc'] : 0;
- if ($PHPUNIT_VERSION < 8.0) {
- $argv = array_filter($argv, function ($v) use (&$argc) { if ('--do-not-cache-result' !== $v) return true; --$argc; return false; });
- printTranslationStatus($originalFilePath, $translationStatus, $config['verbose_output']);
- }
- exit($totalMissingTranslations > 0 ? 1 : 0);
- function findTranslationFiles($originalFilePath, $localeToAnalyze)
- {
- $translations = [];
- $translationsDir = dirname($originalFilePath);
- $originalFileName = basename($originalFilePath);
- }
- return $translations;
- }
- function calculateTranslationStatus($originalFilePath, $translationFilePaths)
- {
- $translationStatus = [];
- $allTranslationKeys = extractTranslationKeys($originalFilePath);
- foreach ($translationFilePaths as $locale => $translationPath) {
- }
- return $translationStatus;
- }
- function printTranslationStatus($originalFilePath, $translationStatus, $verboseOutput)
- {
- printTitle($originalFilePath);
- printTable($translationStatus, $verboseOutput);
- echo PHP_EOL.PHP_EOL;
- }
- printTitle($originalFilePath);
- printTable($translationStatus, $verboseOutput);
- echo PHP_EOL.PHP_EOL;
- }
- function extractLocaleFromFilePath($filePath)
- {
- $parts = explode('.', $filePath);
- return $parts[count($parts) - 2];
- }
- $parts = explode('.', $filePath);
- return $parts[count($parts) - 2];
- }
- function extractTranslationKeys($filePath)
- {
- $translationKeys = [];
- $contents = new \SimpleXMLElement(file_get_contents($filePath));
- foreach ($contents->file->body->{'trans-unit'} as $translationKey) {
- }
- return $translationKeys;
- }
- function printTitle($title)
- {
- echo $title.PHP_EOL;
- echo str_repeat('=', strlen($title)).PHP_EOL.PHP_EOL;
- }
- {
- echo $title.PHP_EOL;
- echo str_repeat('=', strlen($title)).PHP_EOL.PHP_EOL;
- }
- function printTable($translations, $verboseOutput)
- {
- if (0 === count($translations)) {
- echo 'No translations found';
- return;
- echo str_repeat('-', 80).PHP_EOL;
- }
- }
- }
- function textColorGreen()
- {
- echo "\033[32m";
- }
- function textColorRed()
- function textColorGreen()
- {
- echo "\033[32m";
- }
- function textColorRed()
- {
- echo "\033[31m";
- }
- function textColorNormal()
- function textColorRed()
- {
- echo "\033[31m";
- }
- function textColorNormal()
- {
- echo "\033[0m";
- }
Your project should not change PHP configuration dynamically 21
- Read doc
- Productivity
- Major
More information: https://insight.symfony.com/what-we-analyse/php.dynamically_change_configuration
- {
- if (!static::isSupported()) {
- throw new CacheException('APCu is not enabled');
- }
- if ('cli' === \PHP_SAPI) {
- ini_set('apc.use_request_time', 0);
- }
- parent::__construct($namespace, $defaultLifetime);
- if (null !== $version) {
- CacheItem::validateKey($version);
- /**
- * {@inheritdoc}
- */
- protected function doFetch(array $ids)
- {
- $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
- try {
- $values = [];
- foreach (apcu_fetch($ids, $ok) ?: [] as $k => $v) {
- if (null !== $v || $ok) {
- $values[$k] = $v;
- return $values;
- } catch (\Error $e) {
- throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
- } finally {
- ini_set('unserialize_callback_func', $unserializeCallbackHandler);
- }
- }
- /**
- * {@inheritdoc}
- /**
- * {@inheritdoc}
- */
- protected function doFetch(array $ids)
- {
- $unserializeCallbackHandler = ini_set('unserialize_callback_func', parent::class.'::handleUnserializeCallback');
- try {
- return $this->provider->fetchMultiple($ids);
- } catch (\Error $e) {
- $trace = $e->getTrace();
- }
- }
- throw $e;
- } finally {
- ini_set('unserialize_callback_func', $unserializeCallbackHandler);
- }
- }
- /**
- * {@inheritdoc}
- }
- static $igbinaryNull;
- if ($value === ($igbinaryNull ?? $igbinaryNull = \extension_loaded('igbinary') && \PHP_VERSION_ID !== 70400 ? igbinary_serialize(null) : false)) {
- return null;
- }
- $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
- try {
- if (':' === ($value[1] ?? ':')) {
- if (false !== $value = unserialize($value)) {
- return $value;
- }
- throw new \DomainException(error_get_last() ? error_get_last()['message'] : 'Failed to unserialize values.');
- } catch (\Error $e) {
- throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
- } finally {
- ini_set('unserialize_callback_func', $unserializeCallbackHandler);
- }
- }
- /**
- * @internal
- {
- $e = null;
- $meta = false;
- $content = file_get_contents($file);
- $signalingException = new \UnexpectedValueException();
- $prevUnserializeHandler = ini_set('unserialize_callback_func', self::class.'::handleUnserializeCallback');
- $prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$prevErrorHandler, $signalingException) {
- if (__FILE__ === $file) {
- throw $signalingException;
- }
- if ($e !== $signalingException) {
- throw $e;
- }
- } finally {
- restore_error_handler();
- ini_set('unserialize_callback_func', $prevUnserializeHandler);
- }
- return $meta;
- }
- } else {
- error_reporting(E_ALL);
- }
- if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
- ini_set('display_errors', 0);
- } elseif ($displayErrors && (!filter_var(ini_get('log_errors'), FILTER_VALIDATE_BOOLEAN) || ini_get('error_log'))) {
- // CLI - display errors only if they're not already logged to STDERR
- ini_set('display_errors', 1);
- }
- if ($displayErrors) {
- if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
- ini_set('display_errors', 0);
- } elseif ($displayErrors && (!filter_var(ini_get('log_errors'), FILTER_VALIDATE_BOOLEAN) || ini_get('error_log'))) {
- // CLI - display errors only if they're not already logged to STDERR
- ini_set('display_errors', 1);
- }
- if ($displayErrors) {
- ErrorHandler::register(new ErrorHandler(new BufferingLogger()));
- } else {
- ErrorHandler::register()->throwAt(0, true);
- if ($baseDir && !is_dir($baseDir) && [email protected]($baseDir, 0777, true) && !is_dir($baseDir)) {
- throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $baseDir));
- }
- ini_set('session.save_path', $savePath);
- ini_set('session.save_handler', 'files');
- }
- }
- if ($baseDir && !is_dir($baseDir) && [email protected]($baseDir, 0777, true) && !is_dir($baseDir)) {
- throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $baseDir));
- }
- ini_set('session.save_path', $savePath);
- ini_set('session.save_handler', 'files');
- }
- }
- if (headers_sent()) {
- return false;
- }
- if (null !== $lifetime) {
- ini_set('session.cookie_lifetime', $lifetime);
- }
- if ($destroy) {
- $this->metadataBag->stampNew();
- }
- // PHP < 7.3 does not support same_site cookies. We will emulate it in
- // the start() method instead.
- $this->emulateSameSite = $value;
- continue;
- }
- ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value);
- }
- }
- }
- /**
- private function safelyUnserialize(string $contents)
- {
- $e = null;
- $signalingException = new MessageDecodingFailedException(sprintf('Could not decode message using PHP serialization: %s.', $contents));
- $prevUnserializeHandler = ini_set('unserialize_callback_func', self::class.'::handleUnserializeCallback');
- $prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$prevErrorHandler, $signalingException) {
- if (__FILE__ === $file) {
- throw $signalingException;
- }
- try {
- $meta = unserialize($contents);
- } finally {
- restore_error_handler();
- ini_set('unserialize_callback_func', $prevUnserializeHandler);
- }
- return $meta;
- }
- }
- private function safelyUnserialize(string $serializedToken)
- {
- $e = $token = null;
- $prevUnserializeHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
- $prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$prevErrorHandler) {
- if (__FILE__ === $file) {
- throw new \ErrorException($msg, 0x37313bc, $type, $file, $line);
- }
- try {
- $token = unserialize($serializedToken);
- } catch (\Throwable $e) {
- }
- restore_error_handler();
- ini_set('unserialize_callback_func', $prevUnserializeHandler);
- if ($e) {
- if (!$e instanceof \ErrorException || 0x37313bc !== $e->getCode()) {
- throw $e;
- }
- if ($this->logger) {
- }
- }
- public static function unserialize($objects, $serializables)
- {
- $unserializeCallback = ini_set('unserialize_callback_func', __CLASS__.'::getClassReflector');
- try {
- foreach ($serializables as $k => $v) {
- $objects[$k] = unserialize($v);
- }
- try {
- foreach ($serializables as $k => $v) {
- $objects[$k] = unserialize($v);
- }
- } finally {
- ini_set('unserialize_callback_func', $unserializeCallback);
- }
- return $objects;
- }
A symbol used by your project is not imported properly 10
- Read doc
- Reliability
- Major
More information: https://insight.symfony.com/what-we-analyse/php.missing_use_statement
- {
- $charset = ini_get('default_charset') ?: 'UTF-8';
- $statusCode = 500;
- $headers = [];
- if (class_exists(HtmlErrorRenderer::class)) {
- $exception = FlattenException::createFromThrowable($exception);
- $statusCode = $exception->getStatusCode();
- $headers = $exception->getHeaders();
- $response = (new HtmlErrorRenderer(0 !== $this->scopedErrors))->render($exception);
- } else {
- $charset = ini_get('default_charset') ?: 'UTF-8';
- $statusCode = 500;
- $headers = [];
- if (class_exists(HtmlErrorRenderer::class)) {
- $exception = FlattenException::createFromThrowable($exception);
- $statusCode = $exception->getStatusCode();
- $headers = $exception->getHeaders();
- $response = (new HtmlErrorRenderer(0 !== $this->scopedErrors))->render($exception);
- } else {
- $message = htmlspecialchars($exception->getMessage(), ENT_COMPAT | ENT_SUBSTITUTE, $charset);
- if (class_exists(HtmlErrorRenderer::class)) {
- $exception = FlattenException::createFromThrowable($exception);
- $statusCode = $exception->getStatusCode();
- $headers = $exception->getHeaders();
- $response = (new HtmlErrorRenderer(0 !== $this->scopedErrors))->render($exception);
- } else {
- $message = htmlspecialchars($exception->getMessage(), ENT_COMPAT | ENT_SUBSTITUTE, $charset);
- $response = sprintf('<!DOCTYPE html><html><head><meta charset="%s" /><meta name="robots" content="noindex,nofollow" /></head><body>%s</body></html>', $charset, $message);
- }
- *
- * {@inheritdoc}
- */
- protected function matches($message): bool
- {
- if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) {
- throw new \LogicException('Unable to test a message attachment on a RawMessage or Message instance.');
- }
- return $this->expectedValue === \count($message->getAttachments());
- }
- *
- * @param RawMessage $message
- */
- protected function matches($message): bool
- {
- if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) {
- throw new \LogicException('Unable to test a message HTML body on a RawMessage or Message instance.');
- }
- return false !== mb_strpos($message->getHtmlBody(), $this->expectedText);
- }
- *
- * @param RawMessage $message
- */
- protected function matches($message): bool
- {
- if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) {
- throw new \LogicException('Unable to test a message HTML body on a RawMessage or Message instance.');
- }
- return false !== mb_strpos($message->getHtmlBody(), $this->expectedText);
- }
- *
- * @param RawMessage $message
- */
- protected function matches($message): bool
- {
- if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) {
- throw new \LogicException('Unable to test a message text body on a RawMessage or Message instance.');
- }
- return false !== mb_strpos($message->getTextBody(), $this->expectedText);
- }
- *
- * @param RawMessage $message
- */
- protected function matches($message): bool
- {
- if (RawMessage::class === \get_class($message) || Message::class === \get_class($message)) {
- throw new \LogicException('Unable to test a message text body on a RawMessage or Message instance.');
- }
- return false !== mb_strpos($message->getTextBody(), $this->expectedText);
- }
- {
- return $this->decisionLog;
- }
- }
- class_alias(TraceableAccessDecisionManager::class, DebugAccessDecisionManager::class);
- case 'txt':
- return $this->displayTxt($io, $files);
- case 'json':
- return $this->displayJson($io, $files);
- default:
- throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
- }
- }
- private function displayTxt(SymfonyStyle $io, array $filesInfo)
- {
Your project uses discouraged functions to kill scripts 11
- Read doc
- Reliability
- Major
More information: https://insight.symfony.com/what-we-analyse/php.use_exit_function
- // Ignore this re-throw
- }
- if ($exit && self::$exitCode) {
- $exitCode = self::$exitCode;
- register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
- }
- }
- /**
- * Sends the error associated with the given Exception as a plain PHP response.
- <?php
- if (3 > $_SERVER['argc']) {
- echo "Usage: branch dir1 dir2 ... dirN\n";
- exit(1);
- }
- chdir(dirname(__DIR__));
- $json = ltrim(file_get_contents('composer.json'));
- if ($json !== $package = preg_replace('/\n "repositories": \[\n.*?\n \],/s', '', $json)) {
- $preferredInstall = json_decode(file_get_contents(__DIR__.'/composer-config.json'), true)['config']['preferred-install'];
- foreach ($dirs as $k => $dir) {
- if (!system("git diff --name-only $mergeBase -- $dir", $exitStatus)) {
- if ($exitStatus) {
- exit($exitStatus);
- }
- unset($dirs[$k]);
- continue;
- }
- echo "$dir\n";
- echo "$dir\n";
- $json = ltrim(file_get_contents($dir.'/composer.json'));
- if (null === $package = json_decode($json)) {
- passthru("composer validate $dir/composer.json");
- exit(1);
- }
- $package->repositories = array(array(
- 'type' => 'composer',
- 'url' => 'file://'.str_replace(DIRECTORY_SEPARATOR, '/', dirname(__DIR__)).'/',
- passthru("cd $dir && git init && git add . && git commit -q -m - && git archive -o package.tar HEAD && rm .git/ -Rf");
- }
- if (!isset($package->extra->{'branch-alias'}->{'dev-master'})) {
- echo "Missing \"dev-master\" branch-alias in composer.json extra.\n";
- exit(1);
- }
- $package->version = str_replace('-dev', '.x-dev', $package->extra->{'branch-alias'}->{'dev-master'});
- $package->dist['type'] = 'tar';
- $package->dist['url'] = 'file://'.str_replace(DIRECTORY_SEPARATOR, '/', dirname(__DIR__))."/$dir/package.tar";
- if ($dirs) {
- $json = ltrim(file_get_contents('composer.json'));
- if (null === $package = json_decode($json)) {
- passthru("composer validate $dir/composer.json");
- exit(1);
- }
- $package->repositories = array(array(
- 'type' => 'composer',
- 'url' => 'file://'.str_replace(DIRECTORY_SEPARATOR, '/', dirname(__DIR__)).'/',
- <?php
- if (false === getenv('SYMFONY_PATCH_TYPE_DECLARATIONS')) {
- echo "Please define the SYMFONY_PATCH_TYPE_DECLARATIONS env var when running this script.\n";
- exit(1);
- }
- require __DIR__.'/../.phpunit/phpunit-8.3-0/vendor/autoload.php';
- $loader = require __DIR__.'/../vendor/autoload.php';
- }
- if ($this->getConfiguration()->shouldDisplayStackTrace($msg)) {
- echo "\n".ucfirst($group).' '.$deprecation->toString();
- exit(1);
- }
- if ('legacy' !== $group) {
- $ref = &$this->deprecations[$group][$msg]['count'];
- ++$ref;
- $ref = &$this->deprecations[$group][$msg][$class.'::'.$method];
- }
- $this->displayDeprecations($groups, $configuration);
- if ($isFailing || !$configuration->tolerates($this->deprecations)) {
- exit(1);
- }
- });
- }
- private function getConfiguration()
- if ($this->autoExit) {
- if ($exitCode > 255) {
- $exitCode = 255;
- }
- exit($exitCode);
- }
- return $exitCode;
- }
- {
- foreach ($vars as $v) {
- VarDumper::dump($v);
- }
- die(1);
- }
- }
Your project uses the sleep function, which could introduce timeouts 3
- Read doc
- Reliability
- Major
More information: https://insight.symfony.com/what-we-analyse/php.use_php_sleep_function
- $this->stop();
- if (0 < $sleep = $this->restartThresholdSleep) {
- $this->getLogger()->debug(sprintf('Email transport "%s" sleeps for %d seconds after stopping', __CLASS__, $sleep));
- sleep($sleep);
- }
- $this->start();
- $this->restartCounter = 0;
- }
- {
- $client = $this->getHttpClient(__FUNCTION__);
- $response = $client->request('GET', 'http://localhost:8057/timeout-header', [
- 'timeout' => 0.9,
- ]);
- sleep(1);
- $this->assertSame(200, $response->getStatusCode());
- }
- public function testTimeoutOnAccess()
- {
- }
- };
- self::$server->process = $process;
- sleep('\\' === \DIRECTORY_SEPARATOR ? 10 : 1);
- }
- }
Your project files should use safer permissions
- Read doc
- Security
- Major
More information: https://insight.symfony.com/what-we-analyse/php.too_permissive_file_permissions
chmod a-x 'src/Symfony/Component/HttpClient/DependencyInjection/HttpClientPass.php'
Your project should not contain duplicated code 13
- Read doc
- Productivity
- Minor
More information: https://insight.symfony.com/what-we-analyse/php.duplicated_code
- }
- /**
- * Returns an excerpt of a code file around the given line number.
- */
- public function fileExcerpt(string $file, int $line, int $srcContext = 3): ?string
- {
- if (is_file($file) && is_readable($file)) {
- // highlight_file could throw warnings
- // see https://bugs.php.net/25725
- $code = @highlight_file($file, true);
- ->info('The maximum number of connections to a single host.')
- ->end()
- ->arrayNode('default_options')
- ->fixXmlConfig('header')
- ->children()
- ->arrayNode('headers')
- ->info('Associative array: header => value(s).')
- ->useAttributeAsKey('name')
- ->normalizeKeys(false)
- ->variablePrototype()->end()
- ->end()
- * @author Grégoire Pineau <[email protected]>
- * @author Charles Sarrazin <[email protected]>
- */
- class FormLoginLdapFactory extends FormLoginFactory
- {
- protected function createAuthProvider(ContainerBuilder $container, string $id, array $config, string $userProviderId)
- {
- $provider = 'security.authentication.provider.ldap_bind.'.$id;
- $definition = $container
- ->setDefinition($provider, new ChildDefinition('security.authentication.provider.ldap_bind'))
- ->replaceArgument(0, new Reference($userProviderId))
- namespace Symfony\Component\BrowserKit\Test\Constraint;
- use PHPUnit\Framework\Constraint\Constraint;
- use Symfony\Component\BrowserKit\AbstractBrowser;
- final class BrowserHasCookie extends Constraint
- {
- private $name;
- private $path;
- private $domain;
- $this->doDelete($expiredIds);
- }
- foreach ($byLifetime as $lifetime => $values) {
- try {
- $e = $this->doSave($values, $lifetime);
- } catch (\Exception $e) {
- }
- if (true === $e || [] === $e) {
- continue;
- }
- if (\is_array($e) || 1 === \count($values)) {
- $this->dsn = $connOrDsn;
- } else {
- throw new InvalidArgumentException(sprintf('"%s" requires PDO or Doctrine\DBAL\Connection instance or DSN string as first argument, "%s" given.', __CLASS__, \is_object($connOrDsn) ? \get_class($connOrDsn) : \gettype($connOrDsn)));
- }
- $this->table = isset($options['db_table']) ? $options['db_table'] : $this->table;
- $this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol;
- $this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol;
- $this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol;
- $this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol;
- $this->username = isset($options['db_username']) ? $options['db_username'] : $this->username;
- private function formatPath(string $path, int $line): string
- {
- $file = preg_match('#[^/\\\\]*+$#', $path, $file) ? $file[0] : $path;
- return sprintf('in %s %s', $path, 0 < $line ? ' line '.$line : '');
- }
- /**
- * Formats an array as a string.
- */
- ->add('date', __NAMESPACE__.'\DateType', $dateOptions)
- ->add('time', __NAMESPACE__.'\TimeType', $timeOptions)
- ;
- }
- if ('datetime_immutable' === $options['input']) {
- $builder->addModelTransformer(new DateTimeImmutableToDateTimeTransformer());
- } elseif ('string' === $options['input']) {
- $builder->addModelTransformer(new ReversedTransformer(
- new DateTimeToStringTransformer($options['model_timezone'], $options['model_timezone'], $options['input_format'])
- ));
- /**
- * Provides an intuitive error message when controller fails because it is not registered as a service.
- *
- * @author Simeon Kolev <[email protected]>
- */
- final class NotTaggedControllerValueResolver implements ArgumentValueResolverInterface
- {
- private $container;
- public function __construct(ContainerInterface $container)
- {
- $headers = [];
- foreach ($body->getPreparedHeaders()->all() as $header) {
- $headers[] = $header->toString();
- }
- $endpoint = sprintf('%s/v3/%s/messages', $this->getEndpoint(), urlencode($this->domain));
- $response = $this->client->request('POST', 'https://'.$endpoint, [
- 'auth_basic' => 'api:'.$this->key,
- 'headers' => $headers,
- 'body' => $body->bodyToIterable(),
- ]);
- * file that was distributed with this source code.
- */
- namespace Symfony\Component\Mailer\Transport;
- use Symfony\Component\Mailer\Exception\InvalidArgumentException;
- /**
- * @author Konstantin Myakshin <[email protected]>
- */
- final class Dsn
- if (!isset($parsedDsn['scheme'])) {
- throw new InvalidArgumentException(sprintf('The "%s" mailer DSN must contain a scheme.', $dsn));
- }
- if (!isset($parsedDsn['host'])) {
- throw new InvalidArgumentException(sprintf('The "%s" mailer DSN must contain a host (use "default" by default).', $dsn));
- }
- $user = isset($parsedDsn['user']) ? urldecode($parsedDsn['user']) : null;
- $password = isset($parsedDsn['pass']) ? urldecode($parsedDsn['pass']) : null;
- $port = $parsedDsn['port'] ?? null;
- /**
- * @author Nicolas Grekas <[email protected]>
- */
- class AmqpTransport implements TransportInterface, SetupableTransportInterface, MessageCountAwareInterface
- {
- private $serializer;
- private $connection;
- private $receiver;
- private $sender;
- public function __construct(Connection $connection, SerializerInterface $serializer = null)
Potential errors are silenced in your project 68
- Read doc
- Reliability
- Major
More information: https://insight.symfony.com/what-we-analyse/php.silenced_error
- // discard chmod failure (some filesystem may not support it)
- }
- }
- if (\function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN)) {
- @opcache_invalidate($this->file, true);
- }
- }
- /**
- * Gets the meta file path.
- $instantiableWithoutConstructor = true;
- } catch (\ReflectionException $e) {
- $proto = $reflector->implementsInterface('Serializable') && !method_exists($class, '__unserialize') ? 'C:' : 'O:';
- if ('C:' === $proto && !$reflector->getMethod('unserialize')->isInternal()) {
- $proto = null;
- } elseif (false === $proto = @unserialize($proto.\strlen($class).':"'.$class.'":0:{}')) {
- throw new NotInstantiableTypeException($class);
- }
- }
- if (null !== $proto && !$proto instanceof \Throwable && !$proto instanceof \Serializable && !method_exists($class, '__sleep') && (\PHP_VERSION_ID < 70400 || !method_exists($class, '__serialize'))) {
- try {
- $package->dist['type'] = 'tar';
- $package->dist['url'] = 'file://'.str_replace(DIRECTORY_SEPARATOR, '/', dirname(__DIR__))."/$dir/package.tar";
- $packages[$package->name][$package->version] = $package;
- $versions = @file_get_contents('https://repo.packagist.org/p/'.$package->name.'.json') ?: sprintf('{"packages":{"%s":{"dev-master":%s}}}', $package->name, file_get_contents($dir.'/composer.json'));
- $versions = json_decode($versions)->packages->{$package->name};
- if (isset($versions->{'dev-master'}) && $package->version === str_replace('-dev', '.x-dev', $versions->{'dev-master'}->extra->{'branch-alias'}->{'dev-master'})) {
- unset($versions->{'dev-master'});
- }
- }
- $composerJsons = array();
- foreach ($dirs as $dir) {
- if (!file_exists($dir.'/composer.lock') || !$composerLock = @json_decode(file_get_contents($dir.'/composer.lock'), true)) {
- @unlink($dir.'/composer.lock');
- continue;
- }
- if (!file_exists($dir.'/composer.json') || !$composerJson = @json_decode(file_get_contents($dir.'/composer.json'), true)) {
- echo "$dir/composer.json not found or invalid.\n";
- foreach ($dirs as $dir) {
- if (!file_exists($dir.'/composer.lock') || !$composerLock = @json_decode(file_get_contents($dir.'/composer.lock'), true)) {
- @unlink($dir.'/composer.lock');
- continue;
- }
- if (!file_exists($dir.'/composer.json') || !$composerJson = @json_decode(file_get_contents($dir.'/composer.json'), true)) {
- echo "$dir/composer.json not found or invalid.\n";
- @unlink($dir.'/composer.lock');
- continue;
- }
- if (!isset($composerLock['content-hash']) || getContentHash($composerJson) !== $composerLock['content-hash']) {
- : 'composer';
- $SYMFONY_PHPUNIT_REMOVE = $getEnvVar('SYMFONY_PHPUNIT_REMOVE', 'phpspec/prophecy'.($PHPUNIT_VERSION < 6.0 ? ' symfony/yaml': ''));
- $configurationHash = md5(implode(PHP_EOL, array(md5_file(__FILE__), $SYMFONY_PHPUNIT_REMOVE, (int) $PHPUNIT_REMOVE_RETURN_TYPEHINT)));
- $PHPUNIT_VERSION_DIR=sprintf('phpunit-%s-%d', $PHPUNIT_VERSION, $PHPUNIT_REMOVE_RETURN_TYPEHINT);
- if (!file_exists("$PHPUNIT_DIR/$PHPUNIT_VERSION_DIR/phpunit") || $configurationHash !== @file_get_contents("$PHPUNIT_DIR/.$PHPUNIT_VERSION_DIR.md5")) {
- // Build a standalone phpunit without symfony/yaml nor prophecy by default
- @mkdir($PHPUNIT_DIR, 0777, true);
- chdir($PHPUNIT_DIR);
- if (file_exists("$PHPUNIT_VERSION_DIR")) {
- try {
- if ($this->isFinder && !isset($this->loaded[$class])) {
- $this->loaded[$class] = true;
- if (!$file = $this->classLoader[0]->findFile($class) ?: '') {
- // no-op
- } elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) {
- include $file;
- return;
- } elseif (false === include $file) {
- return;
- $className = isset($class[15]) && "\0" === $class[15] && 0 === strpos($class, "[email protected]\x00") ? get_parent_class($class).'@anonymous' : $class;
- // Don't trigger deprecations for classes in the same vendor
- if ($class !== $className) {
- $vendor = preg_match('/^namespace ([^;\\\\\s]++)[;\\\\]/m', @file_get_contents($refl->getFileName()), $vendor) ? $vendor[1].'\\' : '';
- $vendorLen = \strlen($vendor);
- } elseif (2 > $vendorLen = 1 + (strpos($class, '\\') ?: strpos($class, '_'))) {
- $vendorLen = 0;
- $vendor = '';
- } else {
- return $h ? $h($type, $msg, $file, $line, $context) : false;
- }
- // If the message is serialized we need to extract the message. This occurs when the error is triggered by
- // by the isolated test path in \Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerTrait::endTest().
- $parsedMsg = @unserialize($msg);
- if (\is_array($parsedMsg)) {
- $msg = $parsedMsg['deprecation'];
- }
- if (error_reporting()) {
- $msg = 'Unsilenced deprecation: '.$msg;
- $connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
- $redis = new $class();
- $initializer = function ($redis) use ($connect, $params, $dsn, $auth, $hosts) {
- try {
- @$redis->{$connect}($hosts[0]['host'] ?? $hosts[0]['path'], $hosts[0]['port'] ?? null, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval']);
- } catch (\RedisException $e) {
- throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e->getMessage(), $dsn));
- }
- set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
- if ('globals' === $type) {
- if (\is_object($meta)) {
- return ' = object('.\get_class($meta).')';
- }
- $description = substr(@json_encode($meta), 0, 50);
- return sprintf(' = %s', $decorated ? OutputFormatter::escape($description) : $description);
- }
- if ('functions' === $type) {
- if (!$fs->exists($warmupDir.'/'.$containerDir)) {
- $fs->rename($realCacheDir.'/'.$containerDir, $warmupDir.'/'.$containerDir);
- touch($warmupDir.'/'.$containerDir.'.legacy');
- }
- if ('/' === \DIRECTORY_SEPARATOR && $mounts = @file('/proc/mounts')) {
- foreach ($mounts as $mount) {
- $mount = \array_slice(explode(' ', $mount), 1, -3);
- if (!\in_array(array_pop($mount), ['vboxsf', 'nfs'])) {
- continue;
- }
- class WebProfilerBundle extends Bundle
- {
- public function boot()
- {
- if ('prod' === $this->container->getParameter('kernel.environment')) {
- @trigger_error('Using WebProfilerBundle in production is not supported and puts your project at risk, disable it.', E_USER_WARNING);
- }
- }
- }
- $file = $this->files[$key] = $this->getFile($key, true);
- // Since OPcache only compiles files older than the script execution start, set the file's mtime in the past
- $ok = $this->write($file, "<?php //{$encodedKey}\n\n{$value}\n", self::$startTime - 10) && $ok;
- if ($allowCompile) {
- @opcache_invalidate($file, true);
- @opcache_compile_file($file);
- }
- }
- if (!$ok && !is_writable($this->directory)) {
- // Since OPcache only compiles files older than the script execution start, set the file's mtime in the past
- $ok = $this->write($file, "<?php //{$encodedKey}\n\n{$value}\n", self::$startTime - 10) && $ok;
- if ($allowCompile) {
- @opcache_invalidate($file, true);
- @opcache_compile_file($file);
- }
- }
- if (!$ok && !is_writable($this->directory)) {
- throw new CacheException(sprintf('Cache directory is not writable (%s)', $this->directory));
- }
- protected function doUnlink($file)
- {
- if (self::isSupported()) {
- @opcache_invalidate($file, true);
- }
- return @unlink($file);
- }
- foreach ($context as $k => $v) {
- if (is_scalar($v)) {
- $replace['{'.$k.'}'] = $v;
- }
- }
- @trigger_error(strtr($message, $replace), E_USER_WARNING);
- }
- }
- }
- for ($j = 0; $j < 38; ++$j) {
- if (!file_exists($dir = $directory.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
- continue;
- }
- foreach (@scandir($dir, SCANDIR_SORT_NONE) ?: [] as $file) {
- if ('.' !== $file && '..' !== $file) {
- yield $dir.\DIRECTORY_SEPARATOR.$file;
- }
- }
- }
- $paths = array_unique($paths);
- $filepaths = $notfound = [];
- foreach ($paths as $path) {
- if (@file_exists($file = $path.\DIRECTORY_SEPARATOR.$name)) {
- if (true === $first) {
- return $file;
- }
- $filepaths[] = $file;
- } else {
- } catch (\Exception $e) {
- $valid = false;
- }
- } elseif (!\is_array($schemaOrCallable) && is_file((string) $schemaOrCallable)) {
- $schemaSource = file_get_contents((string) $schemaOrCallable);
- $valid = @$dom->schemaValidateSource($schemaSource);
- } else {
- libxml_use_internal_errors($internalErrors);
- throw new XmlParsingException('The schemaOrCallable argument has to be a valid path to XSD file or callable.');
- }
- * @throws XmlParsingException When XML parsing returns any errors
- * @throws \RuntimeException When DOM extension is missing
- */
- public static function loadFile(string $file, $schemaOrCallable = null)
- {
- $content = @file_get_contents($file);
- if ('' === trim($content)) {
- throw new \InvalidArgumentException(sprintf('File %s does not contain valid XML, it is empty.', $file));
- }
- try {
- $this->initialize($input, $output);
- if (null !== $this->processTitle) {
- if (\function_exists('cli_set_process_title')) {
- if ([email protected]_set_process_title($this->processTitle)) {
- if ('Darwin' === PHP_OS) {
- $output->writeln('<comment>Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.</comment>', OutputInterface::VERBOSITY_VERY_VERBOSE);
- } else {
- cli_set_process_title($this->processTitle);
- }
- return true;
- }
- if (\DIRECTORY_SEPARATOR === '\\') {
- return (\function_exists('sapi_windows_vt100_support')
- && @sapi_windows_vt100_support($this->stream))
- || false !== getenv('ANSICON')
- || 'ON' === getenv('ConEmuANSI')
- || 'xterm' === getenv('TERM');
- }
- </xsd:schema>
- EOF
- ;
- $disableEntities = libxml_disable_entity_loader(false);
- $valid = @$dom->schemaValidateSource($source);
- libxml_disable_entity_loader($disableEntities);
- foreach ($tmpfiles as $tmpfile) {
- @unlink($tmpfile);
- }
- $dom = new \DOMDocument('1.0', $charset);
- $dom->validateOnParse = true;
- if ('' !== trim($content)) {
- @$dom->loadXML($content, $options);
- }
- libxml_use_internal_errors($internalErrors);
- libxml_disable_entity_loader($disableEntities);
- $dom = new \DOMDocument('1.0', $charset);
- $dom->validateOnParse = true;
- if ('' !== trim($htmlContent)) {
- @$dom->loadHTML($htmlContent);
- }
- libxml_use_internal_errors($internalErrors);
- libxml_disable_entity_loader($disableEntities);
- {
- list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
- // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
- if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
- $tmpFile = @tempnam($hierarchy, $prefix);
- // If tempnam failed or no scheme return the filename otherwise prepend the scheme
- if (false !== $tmpFile) {
- if (null !== $scheme && 'gs' !== $scheme) {
- return $scheme.'://'.$tmpFile;
- {
- if (null !== $this->rewindable) {
- return $this->rewindable;
- }
- if (false !== $stream = @opendir($this->getPath())) {
- $infos = stream_get_meta_data($stream);
- closedir($stream);
- if ($infos['seekable']) {
- return $this->rewindable = true;
- *
- * @return string
- */
- public static function trim(string $string)
- {
- if (null !== $result = @preg_replace('/^[\pZ\p{Cc}]+|[\pZ\p{Cc}]+$/u', '', $string)) {
- return $result;
- }
- return trim($string);
- }
- if (\extension_loaded('curl')) {
- if ('\\' !== \DIRECTORY_SEPARATOR || ini_get('curl.cainfo') || ini_get('openssl.cafile') || ini_get('openssl.capath')) {
- return new CurlHttpClient($defaultOptions, $maxHostConnections, $maxPendingPushes);
- }
- @trigger_error('Configure the "curl.cainfo", "openssl.cafile" or "openssl.capath" php.ini setting to enable the CurlHttpClient', E_USER_WARNING);
- }
- return new NativeHttpClient($defaultOptions, $maxHostConnections);
- }
- }
- return $body;
- }
- if (!\is_string($body) && !\is_array(@stream_get_meta_data($body))) {
- throw new InvalidArgumentException(sprintf('Option "body" must be string, stream resource, iterable or callable, %s given.', \is_resource($body) ? get_resource_type($body) : \gettype($body)));
- }
- return $body;
- }
- $active = 0;
- while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($multi->handle, $active));
- while ($info = curl_multi_info_read($multi->handle)) {
- $multi->handlesActivity[(int) $info['handle']][] = null;
- $multi->handlesActivity[(int) $info['handle']][] = \in_array($info['result'], [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true) || (\CURLE_WRITE_ERROR === $info['result'] && 'destruct' === @curl_getinfo($info['handle'], CURLINFO_PRIVATE)) ? null : new TransportException(sprintf('%s for "%s".', curl_strerror($info['result']), curl_getinfo($info['handle'], CURLINFO_EFFECTIVE_URL)));
- }
- } finally {
- self::$performing = false;
- }
- }
- /**
- * Parses header lines as curl yields them to us.
- */
- private static function parseHeaderLine($ch, string $data, array &$info, array &$headers, ?array $options, CurlClientState $multi, int $id, ?string &$location, ?callable $resolveRedirect, ?LoggerInterface $logger, &$content = null): int
- {
- if (!\in_array($waitFor = @curl_getinfo($ch, CURLINFO_PRIVATE), ['headers', 'destruct'], true)) {
- return \strlen($data); // Ignore HTTP trailers
- }
- if ("\r\n" !== $data) {
- // Regular header line: add it to the list
- }
- } elseif ('' !== $data = stream_get_contents($buffer, -1, 0)) {
- rewind($buffer);
- ftruncate($buffer, 0);
- if (null !== $inflate && false === $data = @inflate_add($inflate, $data)) {
- $e = new TransportException('Error while processing content unencoding.');
- }
- if ('' !== $data && null === $e) {
- $multi->handlesActivity[$i][] = $data;
- $cacheKey = $requestIp.'-'.$ip;
- if (isset(self::$checkedIps[$cacheKey])) {
- return self::$checkedIps[$cacheKey];
- }
- if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) {
- throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
- }
- if (false !== strpos($ip, '/')) {
- list($address, $netmask) = explode('/', $ip, 2);
- if (false !== strpos($ip, '/')) {
- list($address, $netmask) = explode('/', $ip, 2);
- if ('0' === $netmask) {
- return (bool) unpack('n*', @inet_pton($address));
- }
- if ($netmask < 1 || $netmask > 128) {
- return self::$checkedIps[$cacheKey] = false;
- }
- } else {
- $address = $ip;
- $netmask = 128;
- }
- $bytesAddr = unpack('n*', @inet_pton($address));
- $bytesTest = unpack('n*', @inet_pton($requestIp));
- if (!$bytesAddr || !$bytesTest) {
- return self::$checkedIps[$cacheKey] = false;
- }
- $address = $ip;
- $netmask = 128;
- }
- $bytesAddr = unpack('n*', @inet_pton($address));
- $bytesTest = unpack('n*', @inet_pton($requestIp));
- if (!$bytesAddr || !$bytesTest) {
- return self::$checkedIps[$cacheKey] = false;
- }
- */
- abstract class CacheWarmer implements CacheWarmerInterface
- {
- protected function writeCacheFile(string $file, $content)
- {
- $tmpFile = @tempnam(\dirname($file), basename($file));
- if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
- @chmod($file, 0666 & ~umask());
- return;
- }
- {
- $path = $this->getPath($key);
- if (isset($this->locks[$key])) {
- $fp = $this->locks[$key];
- @ftruncate($fp, 0);
- @fseek($fp, 0);
- $len = @fwrite($fp, $data);
- if (\strlen($data) !== $len) {
- @ftruncate($fp, 0);
- $path = $this->getPath($key);
- if (isset($this->locks[$key])) {
- $fp = $this->locks[$key];
- @ftruncate($fp, 0);
- @fseek($fp, 0);
- $len = @fwrite($fp, $data);
- if (\strlen($data) !== $len) {
- @ftruncate($fp, 0);
- return false;
- $fp = $this->locks[$key];
- @ftruncate($fp, 0);
- @fseek($fp, 0);
- $len = @fwrite($fp, $data);
- if (\strlen($data) !== $len) {
- @ftruncate($fp, 0);
- return false;
- }
- } else {
- if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
- if (false === $this->connection) {
- throw new LdapException(sprintf('Could not connect to Ldap server: %s.', ldap_error($this->connection)));
- }
- if ('tls' === $this->config['encryption'] && false === @ldap_start_tls($this->connection)) {
- throw new LdapException(sprintf('Could not initiate TLS connection: %s.', ldap_error($this->connection)));
- }
- }
- private function disconnect()
- */
- public function addAttributeValues(Entry $entry, string $attribute, array $values)
- {
- $con = $this->getConnectionResource();
- if ([email protected]_mod_add($con, $entry->getDn(), [$attribute => $values])) {
- throw new LdapException(sprintf('Could not add values to entry "%s", attribute %s: %s.', $entry->getDn(), $attribute, ldap_error($con)));
- }
- }
- /**
- */
- public function removeAttributeValues(Entry $entry, string $attribute, array $values)
- {
- $con = $this->getConnectionResource();
- if ([email protected]_mod_del($con, $entry->getDn(), [$attribute => $values])) {
- throw new LdapException(sprintf('Could not remove values from entry "%s", attribute %s: %s.', $entry->getDn(), $attribute, ldap_error($con)));
- }
- }
- /**
- */
- public function rename(Entry $entry, string $newRdn, bool $removeOldRdn = true)
- {
- $con = $this->getConnectionResource();
- if ([email protected]_rename($con, $entry->getDn(), $newRdn, null, $removeOldRdn)) {
- throw new LdapException(sprintf('Could not rename entry "%s" to "%s": %s.', $entry->getDn(), $newRdn, ldap_error($con)));
- }
- }
- /**
- public function move(Entry $entry, string $newParent)
- {
- $con = $this->getConnectionResource();
- $rdn = $this->parseRdnFromEntry($entry);
- // deleteOldRdn does not matter here, since the Rdn will not be changing in the move.
- if ([email protected]_rename($con, $entry->getDn(), $rdn, $newParent, true)) {
- throw new LdapException(sprintf('Could not move entry "%s" to "%s": %s.', $entry->getDn(), $newParent, ldap_error($con)));
- }
- }
- /**
- $operationsMapped = [];
- foreach ($operations as $modification) {
- $operationsMapped[] = $modification->toArray();
- }
- if ([email protected]_modify_batch($this->getConnectionResource(), $dn, $operationsMapped)) {
- throw new UpdateOperationException(sprintf('Error executing UpdateOperation on "%s": "%s".', $dn, ldap_error($this->getConnectionResource())));
- }
- }
- private function parseRdnFromEntry(Entry $entry): string
- }
- $sizeLimit = $itemsLeft;
- if ($pageSize > 0 && $sizeLimit >= $pageSize) {
- $sizeLimit = 0;
- }
- $search = @$func(
- $con,
- $this->dn,
- $this->query,
- $this->options['filter'],
- $this->options['attrsOnly'],
- return;
- }
- $keyId = crc32($key);
- $resource = sem_get($keyId);
- $acquired = @sem_acquire($resource, !$blocking);
- while ($blocking && !$acquired) {
- $resource = sem_get($keyId);
- $acquired = @sem_acquire($resource);
- }
- $resource = sem_get($keyId);
- $acquired = @sem_acquire($resource, !$blocking);
- while ($blocking && !$acquired) {
- $resource = sem_get($keyId);
- $acquired = @sem_acquire($resource);
- }
- if (!$acquired) {
- throw new LockConflictedException();
- }
- $bufferFile = tmpfile();
- $outputFile = tmpfile();
- $this->iteratorToFile($message->toIterable(), $bufferFile);
- if ([email protected]_pkcs7_encrypt(stream_get_meta_data($bufferFile)['uri'], stream_get_meta_data($outputFile)['uri'], $this->certs, [], 0, $this->cipher)) {
- throw new RuntimeException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
- }
- $mimePart = $this->convertMessageToSMimePart($outputFile, 'application', 'pkcs7-mime');
- $mimePart->getHeaders()
- $bufferFile = tmpfile();
- $outputFile = tmpfile();
- $this->iteratorToFile($message->getBody()->toIterable(), $bufferFile);
- if ([email protected]_pkcs7_sign(stream_get_meta_data($bufferFile)['uri'], stream_get_meta_data($outputFile)['uri'], $this->signCertificate, $this->signPrivateKey, [], $this->signOptions, $this->extraCerts)) {
- throw new RuntimeException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
- }
- return new Message($message->getHeaders(), $this->convertMessageToSMimePart($outputFile, 'multipart', 'signed'));
- }
- if (ini_get('open_basedir')) {
- $searchPath = array_merge(explode(PATH_SEPARATOR, ini_get('open_basedir')), $extraDirs);
- $dirs = [];
- foreach ($searchPath as $path) {
- // Silencing against https://bugs.php.net/69240
- if (@is_dir($path)) {
- $dirs[] = $path;
- } else {
- if (basename($path) == $name && @is_executable($path)) {
- return $path;
- }
- $r = $e = [];
- $w = [$this->pipes[0]];
- // let's have a look if something changed in streams
- if (false === @stream_select($r, $w, $e, 0, 0)) {
- return null;
- }
- foreach ($w as $stdin) {
- if (isset($this->inputBuffer[0])) {
- $w = $this->write();
- $read = $r = $e = [];
- if ($blocking) {
- if ($w) {
- @stream_select($r, $w, $e, 0, Process::TIMEOUT_PRECISION * 1E6);
- } elseif ($this->fileHandles) {
- usleep(Process::TIMEOUT_PRECISION * 1E6);
- }
- }
- foreach ($this->fileHandles as $type => $fileHandle) {
- public static function isTtySupported(): bool
- {
- static $isTtySupported;
- if (null === $isTtySupported) {
- $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes);
- }
- return $isTtySupported;
- }
- if ('\\' === \DIRECTORY_SEPARATOR) {
- return $result = false;
- }
- return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes);
- }
- /**
- * Creates the descriptors needed by the proc_open.
- */
- return false;
- }
- } else {
- if (!$this->isSigchildEnabled()) {
- $ok = @proc_terminate($this->process, $signal);
- } elseif (\function_exists('posix_kill')) {
- $ok = @posix_kill($pid, $signal);
- } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) {
- $ok = false === fgets($pipes[2]);
- }
- }
- } else {
- if (!$this->isSigchildEnabled()) {
- $ok = @proc_terminate($this->process, $signal);
- } elseif (\function_exists('posix_kill')) {
- $ok = @posix_kill($pid, $signal);
- } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) {
- $ok = false === fgets($pipes[2]);
- }
- if (!$ok) {
- if ($throwException) {
- {
- $xliffVersion = static::getVersionNumber($dom);
- $internalErrors = libxml_use_internal_errors(true);
- $disableEntities = libxml_disable_entity_loader(false);
- $isValid = @$dom->schemaValidateSource(self::getSchema($xliffVersion));
- if (!$isValid) {
- libxml_disable_entity_loader($disableEntities);
- return self::getXmlErrors($internalErrors);
- }
- if (null !== $constraint->normalizer) {
- $stringValue = ($constraint->normalizer)($stringValue);
- }
- if (!$invalidCharset = [email protected]_check_encoding($stringValue, $constraint->charset)) {
- $length = mb_strlen($stringValue, $constraint->charset);
- }
- if ($invalidCharset) {
- $this->context->buildViolation($constraint->charsetMessage)
- }
- private static function getPhpTimezones(int $zone, string $countryCode = null): array
- {
- if (null !== $countryCode) {
- return @\DateTimeZone::listIdentifiers($zone, $countryCode) ?: [];
- }
- return \DateTimeZone::listIdentifiers($zone);
- }
- return $root;
- }
- }
- $parent = $dir;
- while ([email protected]_exists($parent.'/composer.json')) {
- if ([email protected]_exists($parent)) {
- // open_basedir restriction in effect
- break;
- }
- if ($parent === \dirname($parent)) {
- }
- }
- $parent = $dir;
- while ([email protected]_exists($parent.'/composer.json')) {
- if ([email protected]_exists($parent)) {
- // open_basedir restriction in effect
- break;
- }
- if ($parent === \dirname($parent)) {
- return self::$composerRoots[$dir] = false;
- return $a;
- }
- public static function castStreamContext($stream, array $a, Stub $stub, bool $isNested)
- {
- return @stream_context_get_params($stream) ?: $a;
- }
- public static function castGd($gd, array $a, Stub $stub, $isNested)
- {
- $a['size'] = imagesx($gd).'x'.imagesy($gd);
- return true;
- }
- if (\DIRECTORY_SEPARATOR === '\\') {
- return (\function_exists('sapi_windows_vt100_support')
- && @sapi_windows_vt100_support($stream))
- || false !== getenv('ANSICON')
- || 'ON' === getenv('ConEmuANSI')
- || 'xterm' === getenv('TERM');
- }
- if (null === $this->socket) {
- $this->start();
- }
- foreach ($this->getMessages() as $clientId => $message) {
- $payload = @unserialize(base64_decode($message), ['allowed_classes' => [Data::class, Stub::class]]);
- // Impossible to decode the message, give up.
- if (false === $payload) {
- if ($this->logger) {
- $this->logger->warning('Unable to decode a message from {clientId} client.', ['clientId' => $clientId]);
Your project object parameters should be type hinted 18
- Read doc
- Productivity
- Minor
More information: https://insight.symfony.com/what-we-analyse/php.object_parameter_not_type_hinted
- /**
- * @param string[] $groups
- * @param Configuration $configuration
- */
- private function displayDeprecations($groups, $configuration)
- {
- $cmp = function ($a, $b) {
- return $b['count'] - $a['count'];
- };
- {
- self::$globallyEnabled = false;
- $this->state = -1;
- }
- public function startTestSuite($suite)
- {
- $suiteName = $suite->getName();
- $this->testsWithWarnings = array();
- foreach ($suite->tests() as $test) {
- /**
- * @param TestCase $test
- *
- * @return bool
- */
- private function willBeIsolated($test)
- {
- if ($test->isInIsolation()) {
- return false;
- }
- $title = 'Available registered bundles with their extension alias if available';
- $headers = ['Bundle name', 'Extension alias'];
- $rows = [];
- $bundles = $this->getApplication()->getKernel()->getBundles();
- usort($bundles, function ($bundleA, $bundleB) {
- return strcmp($bundleA->getName(), $bundleB->getName());
- });
- foreach ($bundles as $bundle) {
- $extension = $bundle->getContainerExtension();
- $title = 'Available registered bundles with their extension alias if available';
- $headers = ['Bundle name', 'Extension alias'];
- $rows = [];
- $bundles = $this->getApplication()->getKernel()->getBundles();
- usort($bundles, function ($bundleA, $bundleB) {
- return strcmp($bundleA->getName(), $bundleB->getName());
- });
- foreach ($bundles as $bundle) {
- $extension = $bundle->getContainerExtension();
- if (is_a($class, \Redis::class, true)) {
- $connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
- $redis = new $class();
- $initializer = function ($redis) use ($connect, $params, $dsn, $auth, $hosts) {
- try {
- @$redis->{$connect}($hosts[0]['host'] ?? $hosts[0]['path'], $hosts[0]['port'] ?? null, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval']);
- } catch (\RedisException $e) {
- throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e->getMessage(), $dsn));
- }
- foreach ($generator() as $command => $args) {
- $results[] = $redis->{$command}(...$args);
- $ids[] = 'eval' === $command ? ($redis instanceof \Predis\ClientInterface ? $args[2] : $args[1][0]) : $args[0];
- }
- } elseif ($redis instanceof \Predis\ClientInterface) {
- $results = $redis->pipeline(static function ($redis) use ($generator, &$ids) {
- foreach ($generator() as $command => $args) {
- $redis->{$command}(...$args);
- $ids[] = 'eval' === $command ? $args[2] : $args[0];
- }
- });
- *
- * @param string|\Closure|self $error
- *
- * @return $this
- */
- public function addError($error)
- {
- if ($error instanceof self) {
- $this->errors = array_merge($this->errors, $error->errors);
- } else {
- $this->errors[] = $error;
- /**
- * {@inheritdoc}
- */
- public function guessType(string $class, string $property)
- {
- return $this->guess(function ($guesser) use ($class, $property) {
- return $guesser->guessType($class, $property);
- });
- }
- /**
- /**
- * {@inheritdoc}
- */
- public function guessRequired(string $class, string $property)
- {
- return $this->guess(function ($guesser) use ($class, $property) {
- return $guesser->guessRequired($class, $property);
- });
- }
- /**
- /**
- * {@inheritdoc}
- */
- public function guessMaxLength(string $class, string $property)
- {
- return $this->guess(function ($guesser) use ($class, $property) {
- return $guesser->guessMaxLength($class, $property);
- });
- }
- /**
- /**
- * {@inheritdoc}
- */
- public function guessPattern(string $class, string $property)
- {
- return $this->guess(function ($guesser) use ($class, $property) {
- return $guesser->guessPattern($class, $property);
- });
- }
- /**
- }
- $event->setResponse($response);
- if ($this->debug && $eventDispatcher instanceof EventDispatcherInterface) {
- $cspRemovalListener = function ($event) use (&$cspRemovalListener, $eventDispatcher) {
- $event->getResponse()->headers->remove('Content-Security-Policy');
- $eventDispatcher->removeListener(KernelEvents::RESPONSE, $cspRemovalListener);
- };
- $eventDispatcher->addListener(KernelEvents::RESPONSE, $cspRemovalListener, -128);
- }
- }
- static $setSession;
- if (null === $setSession) {
- $setSession = \Closure::bind(static function ($subRequest, $request) { $subRequest->session = $request->session; }, null, Request::class);
- }
- $setSession($subRequest, $request);
- if ($request->get('_format')) {
- $subRequest->attributes->set('_format', $request->get('_format'));
- $newRequest = Request::create($this->generateUri($request, $path), 'get', [], $request->cookies->all(), [], $request->server->all());
- static $setSession;
- if (null === $setSession) {
- $setSession = \Closure::bind(static function ($newRequest, $request) { $newRequest->session = $request->session; }, null, Request::class);
- }
- $setSession($newRequest, $request);
- if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
- $newRequest->attributes->set(Security::AUTHENTICATION_ERROR, $request->attributes->get(Security::AUTHENTICATION_ERROR));
- }
- return $a;
- }
- public static function castLength($dom, array $a, Stub $stub, bool $isNested)
- {
- $a += [
- 'length' => $dom->length,
- ];
- }
- /**
- * @param \Redis|\RedisArray|\RedisCluster $redis
- */
- private static function getRedisOptions($redis, array $options = []): EnumStub
- {
- $serializer = $redis->getOption(\Redis::OPT_SERIALIZER);
- if (\is_array($serializer)) {
- foreach ($serializer as &$v) {
- if (isset(self::$serializer[$v])) {
- }
- return $a;
- }
- public static function castHttpClientResponse($response, array $a, Stub $stub, bool $isNested)
- {
- $stub->cut += \count($a);
- $a = [];
- foreach ($response->getInfo() as $k => $v) {
Your project should use strict comparison for booleans and null
- Read doc
- Productivity
- Minor
More information: https://insight.symfony.com/what-we-analyse/php.strict_boolean_comparison_should_be_used
- if ($static ? $hasStaticCall : $hasCall) {
- continue;
- }
- $realName = substr($name, 0, strpos($name, '('));
- if (!$refl->hasMethod($realName) || !($methodRefl = $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) {
- $deprecations[] = sprintf('Class "%s" should implement method "%s::%s"%s', $className, ($static ? 'static ' : '').$interface, $name, null == $description ? '.' : ': '.$description);
- }
- }
- }
- }
- }
Your project templates should not be too long
- Read doc
- Productivity
- Minor
More information: https://insight.symfony.com/what-we-analyse/twig.template_too_long
- src/Symfony/…/Profiler/profiler.css.twig is 1121 lines long
- src/Symfony/…/Profiler/base_js.html.twig is 681 lines long
- src/Symfony/…/Profiler/toolbar.css.twig is 500 lines long
- src/Symfony/…/Collector/form.html.twig is 379 lines long
- src/…/Form/form_div_layout.html.twig is 378 lines long
- src/Symfony/…/Collector/security.html.twig is 336 lines long
- src/…/Form/foundation_5_layout.html.twig is 303 lines long
- src/…/Form/bootstrap_4_layout.html.twig is 296 lines long
- src/Symfony/…/Collector/request.html.twig is 268 lines long
- src/Symfony/…/Collector/config.html.twig is 201 lines long
Your project should not contain unused code 250
- Read doc
- Productivity
- Minor
More information: https://insight.symfony.com/what-we-analyse/php.unused_local_variable_or_private_member
- ];
- }
- private function safelyUnserialize(string $contents)
- {
- $e = null;
- $signalingException = new MessageDecodingFailedException(sprintf('Could not decode message using PHP serialization: %s.', $contents));
- $prevUnserializeHandler = ini_set('unserialize_callback_func', self::class.'::handleUnserializeCallback');
- $prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$prevErrorHandler, $signalingException) {
- if (__FILE__ === $file) {
- throw $signalingException;
- if (!$type || (!$log && !$throw)) {
- return !$silenced && $type && $log;
- }
- $scope = $this->scopedErrors & $type;
- if (4 < $numArgs = \func_num_args()) {
- $context = $scope ? (func_get_arg(4) ?: []) : [];
- } else {
- $context = [];
- }
- use Symfony\Component\Mime\RawMessage;
- final class EmailAttachmentCount extends Constraint
- {
- private $expectedValue;
- private $transport;
- public function __construct(int $expectedValue, string $transport = null)
- {
- $this->expectedValue = $expectedValue;
- $this->transport = $transport;
- *
- * @experimental in 1.1
- */
- abstract class HttpClientTestCase extends TestCase
- {
- private static $server;
- public static function setUpBeforeClass(): void
- {
- TestHttpServer::start();
- }
- protected const NS_SEPARATOR = ':';
- use AbstractAdapterTrait;
- use ContractsTrait;
- private static $apcuSupported;
- private static $phpFilesSupported;
- protected function __construct(string $namespace = '', int $defaultLifetime = 0)
- {
- $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).static::NS_SEPARATOR;
- use AbstractAdapterTrait;
- use ContractsTrait;
- private static $apcuSupported;
- private static $phpFilesSupported;
- protected function __construct(string $namespace = '', int $defaultLifetime = 0)
- {
- $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).static::NS_SEPARATOR;
- if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
- $this->properties = $properties;
- $this->value = $value;
- $this->wakeups = $wakeups;
- }
- public static function hydrate($objects, $values, $properties, $value, $wakeups)
- {
- foreach ($properties as $class => $vars) {
- (self::$hydrators[$class] ?? self::getHydrator($class))($vars, $objects);
- }
- foreach ($wakeups as $k => $v) {
- }
- $suite->setTests($skipped);
- }
- }
- public function addSkippedTest($test, \Exception $e, $time)