From 97de887222bd2892c61776caceda558ee9a8f7bd Mon Sep 17 00:00:00 2001 From: Diego Saint Esteben Date: Fri, 12 Jun 2015 16:45:17 -0300 Subject: [PATCH 1/6] Remove duplicated paths --- src/Symfony/Component/Config/FileLocator.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Config/FileLocator.php b/src/Symfony/Component/Config/FileLocator.php index c224833f26..c6600c7783 100644 --- a/src/Symfony/Component/Config/FileLocator.php +++ b/src/Symfony/Component/Config/FileLocator.php @@ -53,6 +53,7 @@ class FileLocator implements FileLocatorInterface array_unshift($paths, $currentPath); } + $paths = array_unique($paths); $filepaths = array(); foreach ($paths as $path) { @@ -68,7 +69,7 @@ class FileLocator implements FileLocatorInterface throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s).', $name, implode(', ', $paths))); } - return array_values(array_unique($filepaths)); + return $filepaths; } /** From 4a4fea742bbde8b99233ee990e159a1a529cbf65 Mon Sep 17 00:00:00 2001 From: Vladimir Reznichenko Date: Sat, 6 Jun 2015 08:25:15 +0200 Subject: [PATCH 2/6] [2.3] Static Code Analysis for Components --- src/Symfony/Component/Console/Application.php | 2 +- src/Symfony/Component/Console/Formatter/OutputFormatter.php | 4 ++-- src/Symfony/Component/Console/Shell.php | 2 +- .../Component/DependencyInjection/Dumper/GraphvizDumper.php | 2 +- src/Symfony/Component/Filesystem/Tests/FilesystemTest.php | 2 +- src/Symfony/Component/Finder/Tests/FinderTest.php | 2 +- .../Finder/Tests/Iterator/CustomFilterIteratorTest.php | 2 +- .../Component/Finder/Tests/Iterator/MockSplFileInfo.php | 4 ++-- .../Session/Storage/MockArraySessionStorage.php | 2 +- src/Symfony/Component/HttpKernel/HttpCache/Esi.php | 2 +- src/Symfony/Component/Process/ProcessUtils.php | 2 +- .../Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php | 4 ++-- src/Symfony/Component/Yaml/Inline.php | 2 +- src/Symfony/Component/Yaml/Parser.php | 6 +++--- 14 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php index badcce6473..0d66598204 100644 --- a/src/Symfony/Component/Console/Application.php +++ b/src/Symfony/Component/Console/Application.php @@ -1161,7 +1161,7 @@ class Application $lines[] = str_pad($line, $width); $line = $char; } - if (strlen($line)) { + if ('' !== $line) { $lines[] = count($lines) ? str_pad($line, $width) : $line; } diff --git a/src/Symfony/Component/Console/Formatter/OutputFormatter.php b/src/Symfony/Component/Console/Formatter/OutputFormatter.php index a053ac6ba0..331b204fec 100644 --- a/src/Symfony/Component/Console/Formatter/OutputFormatter.php +++ b/src/Symfony/Component/Console/Formatter/OutputFormatter.php @@ -33,7 +33,7 @@ class OutputFormatter implements OutputFormatterInterface */ public static function escape($text) { - return preg_replace('/([^\\\\]?)#isx", $message, $matches, PREG_OFFSET_CAPTURE); + preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, PREG_OFFSET_CAPTURE); foreach ($matches[0] as $i => $match) { $pos = $match[1]; $text = $match[0]; diff --git a/src/Symfony/Component/Console/Shell.php b/src/Symfony/Component/Console/Shell.php index b3cbf16fa8..d0bcb7ee8a 100644 --- a/src/Symfony/Component/Console/Shell.php +++ b/src/Symfony/Component/Console/Shell.php @@ -207,7 +207,7 @@ EOF; } else { $this->output->write($this->getPrompt()); $line = fgets(STDIN, 1024); - $line = (!$line && strlen($line) == 0) ? false : rtrim($line); + $line = (false === $line || '' === $line) ? false : rtrim($line); } return $line; diff --git a/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php index fdd71b36ee..ed4f0b1fb3 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php @@ -271,7 +271,7 @@ class GraphvizDumper extends Dumper */ private function dotize($id) { - return strtolower(preg_replace('/[^\w]/i', '_', $id)); + return strtolower(preg_replace('/\W/i', '_', $id)); } /** diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php index ad1a0928ab..62dfd9ad91 100644 --- a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php +++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php @@ -675,7 +675,7 @@ class FilesystemTest extends \PHPUnit_Framework_TestCase */ public function testRenameThrowsExceptionOnError() { - $file = $this->workspace.DIRECTORY_SEPARATOR.uniqid(); + $file = $this->workspace.DIRECTORY_SEPARATOR.uniqid('fs_test_', true); $newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file'; $this->filesystem->rename($file, $newPath); diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php index 3ae88a9db4..92f38ab94c 100644 --- a/src/Symfony/Component/Finder/Tests/FinderTest.php +++ b/src/Symfony/Component/Finder/Tests/FinderTest.php @@ -272,7 +272,7 @@ class FinderTest extends Iterator\RealIteratorTestCase public function testFilter($adapter) { $finder = $this->buildFinder($adapter); - $this->assertSame($finder, $finder->filter(function (\SplFileInfo $f) { return preg_match('/test/', $f) > 0; })); + $this->assertSame($finder, $finder->filter(function (\SplFileInfo $f) { return false !== strpos($f, 'test'); })); $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator()); } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php index 62629b183f..b036ad13c2 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php @@ -39,7 +39,7 @@ class CustomFilterIteratorTest extends IteratorTestCase { return array( array(array(function (\SplFileInfo $fileinfo) { return false; }), array()), - array(array(function (\SplFileInfo $fileinfo) { return preg_match('/^test/', $fileinfo) > 0; }), array('test.php', 'test.py')), + array(array(function (\SplFileInfo $fileinfo) { return 0 === strpos($fileinfo, 'test'); }), array('test.php', 'test.py')), array(array('is_dir'), array()), ); } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php b/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php index f2e8f8e2fd..a895350732 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php @@ -51,7 +51,7 @@ class MockSplFileInfo extends \SplFileInfo public function isFile() { if (null === $this->type) { - return preg_match('/file/', $this->getFilename()); + return false !== strpos($this->getFilename(), 'file'); }; return self::TYPE_FILE === $this->type; @@ -60,7 +60,7 @@ class MockSplFileInfo extends \SplFileInfo public function isDir() { if (null === $this->type) { - return preg_match('/directory/', $this->getFilename()); + return false !== strpos($this->getFilename(), 'directory'); } return self::TYPE_DIRECTORY === $this->type; diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php index 96dae6b35c..f2d8bcf5a4 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php @@ -249,7 +249,7 @@ class MockArraySessionStorage implements SessionStorageInterface */ protected function generateId() { - return sha1(uniqid(mt_rand())); + return sha1(uniqid('ss_mock_', true)); } protected function loadSession() diff --git a/src/Symfony/Component/HttpKernel/HttpCache/Esi.php b/src/Symfony/Component/HttpKernel/HttpCache/Esi.php index 58b6265656..bc55bed51a 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/Esi.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/Esi.php @@ -183,7 +183,7 @@ class Esi $chunks[$i] = sprintf('esi->handle($this, %s, %s, %s) ?>'."\n", var_export($options['src'], true), var_export(isset($options['alt']) ? $options['alt'] : '', true), - isset($options['onerror']) && 'continue' == $options['onerror'] ? 'true' : 'false' + isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false' ); ++$i; $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]); diff --git a/src/Symfony/Component/Process/ProcessUtils.php b/src/Symfony/Component/Process/ProcessUtils.php index ed3dc35032..2ec608daa0 100644 --- a/src/Symfony/Component/Process/ProcessUtils.php +++ b/src/Symfony/Component/Process/ProcessUtils.php @@ -49,7 +49,7 @@ class ProcessUtils $escapedArgument = ''; $quote = false; - foreach (preg_split('/(")/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { + foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { if ('"' === $part) { $escapedArgument .= '\\"'; } elseif (self::isSurroundedBy($part, '%')) { diff --git a/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php b/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php index 89d1f6a1ac..26673ea45a 100644 --- a/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php +++ b/src/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.php @@ -32,7 +32,7 @@ while ($read || $write) { } $out = (binary) substr($out, $written); } - if (null === $read && strlen($out) < 1) { + if (null === $read && '' === $out) { $write = array_diff($write, array(STDOUT)); } @@ -43,7 +43,7 @@ while ($read || $write) { } $err = (binary) substr($err, $written); } - if (null === $read && strlen($err) < 1) { + if (null === $read && '' === $err) { $write = array_diff($write, array(STDERR)); } diff --git a/src/Symfony/Component/Yaml/Inline.php b/src/Symfony/Component/Yaml/Inline.php index 6d21a48f41..aff4ce7ff5 100644 --- a/src/Symfony/Component/Yaml/Inline.php +++ b/src/Symfony/Component/Yaml/Inline.php @@ -45,7 +45,7 @@ class Inline $value = trim($value); - if (0 == strlen($value)) { + if ('' === $value) { return ''; } diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php index ae4f500f7d..fc46ab3caf 100644 --- a/src/Symfony/Component/Yaml/Parser.php +++ b/src/Symfony/Component/Yaml/Parser.php @@ -509,9 +509,9 @@ class Parser // deal with trailing newlines as indicated if ('' === $indicator) { - $text = preg_replace('/\n+$/s', "\n", $text); + $text = preg_replace('/\n+$/', "\n", $text); } elseif ('-' === $indicator) { - $text = preg_replace('/\n+$/s', '', $text); + $text = preg_replace('/\n+$/', '', $text); } return $text; @@ -610,7 +610,7 @@ class Parser $value = $trimmedValue; // remove end of the document marker (...) - $value = preg_replace('#\.\.\.\s*$#s', '', $value); + $value = preg_replace('#\.\.\.\s*$#', '', $value); } return $value; From e8b924c2d316f158d71975f1a86dd6b79e9241ce Mon Sep 17 00:00:00 2001 From: Javier Eguiluz Date: Wed, 10 Jun 2015 20:30:03 +0200 Subject: [PATCH 3/6] Standardize the name of the exception variables --- src/Symfony/Bundle/TwigBundle/TwigEngine.php | 2 +- .../Component/Config/Definition/ArrayNode.php | 2 +- .../Component/Config/Definition/BaseNode.php | 12 ++++-------- .../Config/Definition/PrototypedArrayNode.php | 2 +- .../Component/Console/Helper/DialogHelper.php | 10 +++++----- .../Compiler/ResolveInvalidReferencesPass.php | 4 ++-- .../DataCollector/RequestDataCollector.php | 2 +- .../ContainerAwareHttpKernelTest.php | 8 ++++---- .../Component/Security/Acl/Dbal/AclProvider.php | 4 ++-- .../Security/Acl/Dbal/MutableAclProvider.php | 12 ++++++------ .../Security/Acl/Domain/ObjectIdentity.php | 4 ++-- .../Domain/ObjectIdentityRetrievalStrategy.php | 2 +- .../Acl/Domain/PermissionGrantingStrategy.php | 16 ++++++++-------- .../Domain/SecurityIdentityRetrievalStrategy.php | 2 +- .../Security/Acl/Permission/MaskBuilder.php | 2 +- .../Component/Security/Acl/Voter/AclVoter.php | 4 ++-- .../Provider/DaoAuthenticationProvider.php | 14 +++++++------- .../Provider/UserAuthenticationProvider.php | 8 ++++---- .../Security/Core/User/ChainUserProvider.php | 12 ++++++------ .../AbstractPreAuthenticatedListener.php | 8 ++++---- .../Firewall/BasicAuthenticationListener.php | 6 +++--- .../Security/Http/Firewall/ContextListener.php | 6 +++--- .../Firewall/DigestAuthenticationListener.php | 2 +- .../Http/Firewall/RememberMeListener.php | 4 ++-- .../RememberMe/AbstractRememberMeServices.php | 12 ++++++------ .../RememberMe/TokenBasedRememberMeServices.php | 8 ++++---- .../Security/Tests/Acl/Dbal/AclProviderTest.php | 8 ++++---- .../Tests/Acl/Dbal/MutableAclProviderTest.php | 6 +++--- .../Domain/PermissionGrantingStrategyTest.php | 2 +- ...ersistentTokenBasedRememberMeServicesTest.php | 2 +- 30 files changed, 91 insertions(+), 95 deletions(-) diff --git a/src/Symfony/Bundle/TwigBundle/TwigEngine.php b/src/Symfony/Bundle/TwigBundle/TwigEngine.php index c6f8a09a35..927256a20c 100644 --- a/src/Symfony/Bundle/TwigBundle/TwigEngine.php +++ b/src/Symfony/Bundle/TwigBundle/TwigEngine.php @@ -79,7 +79,7 @@ class TwigEngine extends BaseEngine implements EngineInterface try { // try to get the real file name of the template where the error occurred $e->setTemplateFile(sprintf('%s', $this->locator->locate($this->parser->parse($e->getTemplateFile())))); - } catch (\Exception $ex) { + } catch (\Exception $e2) { } } diff --git a/src/Symfony/Component/Config/Definition/ArrayNode.php b/src/Symfony/Component/Config/Definition/ArrayNode.php index 2bb9a7e9e7..4513922576 100644 --- a/src/Symfony/Component/Config/Definition/ArrayNode.php +++ b/src/Symfony/Component/Config/Definition/ArrayNode.php @@ -256,7 +256,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface try { $value[$name] = $child->finalize($value[$name]); - } catch (UnsetKeyException $unset) { + } catch (UnsetKeyException $e) { unset($value[$name]); } } diff --git a/src/Symfony/Component/Config/Definition/BaseNode.php b/src/Symfony/Component/Config/Definition/BaseNode.php index 732e086261..ad84d012a6 100644 --- a/src/Symfony/Component/Config/Definition/BaseNode.php +++ b/src/Symfony/Component/Config/Definition/BaseNode.php @@ -302,14 +302,10 @@ abstract class BaseNode implements NodeInterface foreach ($this->finalValidationClosures as $closure) { try { $value = $closure($value); - } catch (Exception $correctEx) { - throw $correctEx; - } catch (\Exception $invalid) { - throw new InvalidConfigurationException(sprintf( - 'Invalid configuration for path "%s": %s', - $this->getPath(), - $invalid->getMessage() - ), $invalid->getCode(), $invalid); + } catch (Exception $e) { + throw $e; + } catch (\Exception $e) { + throw new InvalidConfigurationException(sprintf('Invalid configuration for path "%s": %s', $this->getPath(), $e->getMessage()), $e->getCode(), $e); } } diff --git a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php index b1fbc36167..f0930db9f6 100644 --- a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php +++ b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php @@ -211,7 +211,7 @@ class PrototypedArrayNode extends ArrayNode $this->prototype->setName($k); try { $value[$k] = $this->prototype->finalize($v); - } catch (UnsetKeyException $unset) { + } catch (UnsetKeyException $e) { unset($value[$k]); } } diff --git a/src/Symfony/Component/Console/Helper/DialogHelper.php b/src/Symfony/Component/Console/Helper/DialogHelper.php index d81ec9454f..adbf1869c0 100644 --- a/src/Symfony/Component/Console/Helper/DialogHelper.php +++ b/src/Symfony/Component/Console/Helper/DialogHelper.php @@ -452,18 +452,18 @@ class DialogHelper extends Helper */ private function validateAttempts($interviewer, OutputInterface $output, $validator, $attempts) { - $error = null; + $e = null; while (false === $attempts || $attempts--) { - if (null !== $error) { - $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error')); + if (null !== $e) { + $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($e->getMessage(), 'error')); } try { return call_user_func($validator, $interviewer()); - } catch (\Exception $error) { + } catch (\Exception $e) { } } - throw $error; + throw $e; } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveInvalidReferencesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveInvalidReferencesPass.php index 000bf08700..85dbceb9a6 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveInvalidReferencesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveInvalidReferencesPass.php @@ -47,7 +47,7 @@ class ResolveInvalidReferencesPass implements CompilerPassInterface foreach ($definition->getMethodCalls() as $call) { try { $calls[] = array($call[0], $this->processArguments($call[1], true)); - } catch (RuntimeException $ignore) { + } catch (RuntimeException $e) { // this call is simply removed } } @@ -58,7 +58,7 @@ class ResolveInvalidReferencesPass implements CompilerPassInterface try { $value = $this->processArguments(array($value), true); $properties[$name] = reset($value); - } catch (RuntimeException $ignore) { + } catch (RuntimeException $e) { // ignore property } } diff --git a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php index 49f252a81c..5cc3b7d154 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php @@ -125,7 +125,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter 'file' => $r->getFileName(), 'line' => $r->getStartLine(), ); - } catch (\ReflectionException $re) { + } catch (\ReflectionException $e) { if (is_callable($controller)) { // using __call or __callStatic $this->data['controller'] = array( diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ContainerAwareHttpKernelTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ContainerAwareHttpKernelTest.php index 28901dafdd..f015857b73 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ContainerAwareHttpKernelTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ContainerAwareHttpKernelTest.php @@ -137,10 +137,10 @@ class ContainerAwareHttpKernelTest extends \PHPUnit_Framework_TestCase try { $kernel->handle($request, $type); $this->fail('->handle() suppresses the controller exception'); - } catch (\PHPUnit_Framework_Exception $exception) { - throw $exception; - } catch (\Exception $actual) { - $this->assertSame($expected, $actual, '->handle() throws the controller exception'); + } catch (\PHPUnit_Framework_Exception $e) { + throw $e; + } catch (\Exception $e) { + $this->assertSame($expected, $e, '->handle() throws the controller exception'); } } diff --git a/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php b/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php index 7c512adc7c..1fade3b4b2 100644 --- a/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php +++ b/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php @@ -177,13 +177,13 @@ class AclProvider implements AclProviderInterface if ($currentBatchesCount > 0 && (self::MAX_BATCH_SIZE === $currentBatchesCount || ($i + 1) === $c)) { try { $loadedBatch = $this->lookupObjectIdentities($currentBatch, $sids, $oidLookup); - } catch (AclNotFoundException $aclNotFoundexception) { + } catch (AclNotFoundException $e) { if ($result->count()) { $partialResultException = new NotAllAclsFoundException('The provider could not find ACLs for all object identities.'); $partialResultException->setPartialResult($result); throw $partialResultException; } else { - throw $aclNotFoundexception; + throw $e; } } foreach ($loadedBatch as $loadedOid) { diff --git a/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php b/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php index 30772b46bf..c62bdd4176 100644 --- a/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php +++ b/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php @@ -62,10 +62,10 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf $this->connection->executeQuery($this->getInsertObjectIdentityRelationSql($pk, $pk)); $this->connection->commit(); - } catch (\Exception $failed) { + } catch (\Exception $e) { $this->connection->rollBack(); - throw $failed; + throw $e; } // re-read the ACL from the database to ensure proper caching, etc. @@ -90,10 +90,10 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf $this->deleteObjectIdentity($oidPK); $this->connection->commit(); - } catch (\Exception $failed) { + } catch (\Exception $e) { $this->connection->rollBack(); - throw $failed; + throw $e; } // evict the ACL from the in-memory identity map @@ -324,10 +324,10 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf } $this->connection->commit(); - } catch (\Exception $failed) { + } catch (\Exception $e) { $this->connection->rollBack(); - throw $failed; + throw $e; } $this->propertyChanges->offsetSet($acl, array()); diff --git a/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php b/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php index fc5b9c6de6..871bda7b10 100644 --- a/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php +++ b/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php @@ -68,8 +68,8 @@ final class ObjectIdentity implements ObjectIdentityInterface } elseif (method_exists($domainObject, 'getId')) { return new self((string) $domainObject->getId(), ClassUtils::getRealClass($domainObject)); } - } catch (\InvalidArgumentException $invalid) { - throw new InvalidDomainObjectException($invalid->getMessage(), 0, $invalid); + } catch (\InvalidArgumentException $e) { + throw new InvalidDomainObjectException($e->getMessage(), 0, $e); } throw new InvalidDomainObjectException('$domainObject must either implement the DomainObjectInterface, or have a method named "getId".'); diff --git a/src/Symfony/Component/Security/Acl/Domain/ObjectIdentityRetrievalStrategy.php b/src/Symfony/Component/Security/Acl/Domain/ObjectIdentityRetrievalStrategy.php index 21ac8121fb..80de6e0284 100644 --- a/src/Symfony/Component/Security/Acl/Domain/ObjectIdentityRetrievalStrategy.php +++ b/src/Symfony/Component/Security/Acl/Domain/ObjectIdentityRetrievalStrategy.php @@ -28,7 +28,7 @@ class ObjectIdentityRetrievalStrategy implements ObjectIdentityRetrievalStrategy { try { return ObjectIdentity::fromDomainObject($domainObject); - } catch (InvalidDomainObjectException $failed) { + } catch (InvalidDomainObjectException $e) { return; } } diff --git a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php index ef80a2036c..742c4e5fbf 100644 --- a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php +++ b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php @@ -55,21 +55,21 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); - } catch (NoAceFoundException $noObjectAce) { + } catch (NoAceFoundException $e) { $aces = $acl->getClassAces(); if (!$aces) { - throw $noObjectAce; + throw $e; } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); } - } catch (NoAceFoundException $noClassAce) { + } catch (NoAceFoundException $e) { if ($acl->isEntriesInheriting() && null !== $parentAcl = $acl->getParentAcl()) { return $parentAcl->isGranted($masks, $sids, $administrativeMode); } - throw $noClassAce; + throw $e; } } @@ -86,20 +86,20 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); - } catch (NoAceFoundException $noObjectAces) { + } catch (NoAceFoundException $e) { $aces = $acl->getClassFieldAces($field); if (!$aces) { - throw $noObjectAces; + throw $e; } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); } - } catch (NoAceFoundException $noClassAces) { + } catch (NoAceFoundException $e) { if ($acl->isEntriesInheriting() && null !== $parentAcl = $acl->getParentAcl()) { return $parentAcl->isFieldGranted($field, $masks, $sids, $administrativeMode); } - throw $noClassAces; + throw $e; } } diff --git a/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php b/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php index 708c633af8..a08f67e295 100644 --- a/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php +++ b/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php @@ -51,7 +51,7 @@ class SecurityIdentityRetrievalStrategy implements SecurityIdentityRetrievalStra if (!$token instanceof AnonymousToken) { try { $sids[] = UserSecurityIdentity::fromToken($token); - } catch (\InvalidArgumentException $invalid) { + } catch (\InvalidArgumentException $e) { // ignore, user has no user security identity } } diff --git a/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php b/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php index 45d89aa710..ca25c70f06 100644 --- a/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php +++ b/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php @@ -132,7 +132,7 @@ class MaskBuilder if ('1' === $bitmask[$i]) { try { $pattern[$i] = self::getCode(1 << ($length - $i - 1)); - } catch (\Exception $notPredefined) { + } catch (\Exception $e) { $pattern[$i] = self::ON; } } diff --git a/src/Symfony/Component/Security/Acl/Voter/AclVoter.php b/src/Symfony/Component/Security/Acl/Voter/AclVoter.php index 9657eedb8d..4a8533afd6 100644 --- a/src/Symfony/Component/Security/Acl/Voter/AclVoter.php +++ b/src/Symfony/Component/Security/Acl/Voter/AclVoter.php @@ -113,13 +113,13 @@ class AclVoter implements VoterInterface } return self::ACCESS_DENIED; - } catch (AclNotFoundException $noAcl) { + } catch (AclNotFoundException $e) { if (null !== $this->logger) { $this->logger->debug('No ACL found for the object identity. Voting to deny access.'); } return self::ACCESS_DENIED; - } catch (NoAceFoundException $noAce) { + } catch (NoAceFoundException $e) { if (null !== $this->logger) { $this->logger->debug('ACL found, no ACE applicable. Voting to deny access.'); } diff --git a/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php b/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php index b7b4917e90..90cba25d64 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php @@ -87,13 +87,13 @@ class DaoAuthenticationProvider extends UserAuthenticationProvider } return $user; - } catch (UsernameNotFoundException $notFound) { - $notFound->setUsername($username); - throw $notFound; - } catch (\Exception $repositoryProblem) { - $ex = new AuthenticationServiceException($repositoryProblem->getMessage(), 0, $repositoryProblem); - $ex->setToken($token); - throw $ex; + } catch (UsernameNotFoundException $e) { + $e->setUsername($username); + throw $e; + } catch (\Exception $e) { + $e = new AuthenticationServiceException($e->getMessage(), 0, $e); + $e->setToken($token); + throw $e; } } } diff --git a/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php b/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php index b9481359a2..b65a16bbb2 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php @@ -68,13 +68,13 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter try { $user = $this->retrieveUser($username, $token); - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { if ($this->hideUserNotFoundExceptions) { - throw new BadCredentialsException('Bad credentials', 0, $notFound); + throw new BadCredentialsException('Bad credentials', 0, $e); } - $notFound->setUsername($username); + $e->setUsername($username); - throw $notFound; + throw $e; } if (!$user instanceof UserInterface) { diff --git a/src/Symfony/Component/Security/Core/User/ChainUserProvider.php b/src/Symfony/Component/Security/Core/User/ChainUserProvider.php index 6e14a4ff26..8604ddc4a7 100644 --- a/src/Symfony/Component/Security/Core/User/ChainUserProvider.php +++ b/src/Symfony/Component/Security/Core/User/ChainUserProvider.php @@ -47,7 +47,7 @@ class ChainUserProvider implements UserProviderInterface foreach ($this->providers as $provider) { try { return $provider->loadUserByUsername($username); - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { // try next one } } @@ -67,18 +67,18 @@ class ChainUserProvider implements UserProviderInterface foreach ($this->providers as $provider) { try { return $provider->refreshUser($user); - } catch (UnsupportedUserException $unsupported) { + } catch (UnsupportedUserException $e) { // try next one - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { $supportedUserFound = true; // try next one } } if ($supportedUserFound) { - $ex = new UsernameNotFoundException(sprintf('There is no user with name "%s".', $user->getUsername())); - $ex->setUsername($user->getUsername()); - throw $ex; + $e = new UsernameNotFoundException(sprintf('There is no user with name "%s".', $user->getUsername())); + $e->setUsername($user->getUsername()); + throw $e; } else { throw new UnsupportedUserException(sprintf('The account "%s" is not supported.', get_class($user))); } diff --git a/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php b/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php index f040107ac1..997368348a 100644 --- a/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php @@ -62,8 +62,8 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface try { list($user, $credentials) = $this->getPreAuthenticatedData($request); - } catch (BadCredentialsException $exception) { - $this->clearToken($exception); + } catch (BadCredentialsException $e) { + $this->clearToken($e); return; } @@ -90,8 +90,8 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface $loginEvent = new InteractiveLoginEvent($request, $token); $this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent); } - } catch (AuthenticationException $failed) { - $this->clearToken($failed); + } catch (AuthenticationException $e) { + $this->clearToken($e); } } diff --git a/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php index bfc4abc834..eed9838c40 100644 --- a/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php @@ -73,21 +73,21 @@ class BasicAuthenticationListener implements ListenerInterface try { $token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey)); $this->securityContext->setToken($token); - } catch (AuthenticationException $failed) { + } catch (AuthenticationException $e) { $token = $this->securityContext->getToken(); if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) { $this->securityContext->setToken(null); } if (null !== $this->logger) { - $this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $failed->getMessage())); + $this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $e->getMessage())); } if ($this->ignoreFailure) { return; } - $event->setResponse($this->authenticationEntryPoint->start($request, $failed)); + $event->setResponse($this->authenticationEntryPoint->start($request, $e)); } } } diff --git a/src/Symfony/Component/Security/Http/Firewall/ContextListener.php b/src/Symfony/Component/Security/Http/Firewall/ContextListener.php index c80fff3317..43ad31d1a1 100644 --- a/src/Symfony/Component/Security/Http/Firewall/ContextListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/ContextListener.php @@ -167,11 +167,11 @@ class ContextListener implements ListenerInterface } return $token; - } catch (UnsupportedUserException $unsupported) { + } catch (UnsupportedUserException $e) { // let's try the next user provider - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { if (null !== $this->logger) { - $this->logger->warning(sprintf('Username "%s" could not be found.', $notFound->getUsername())); + $this->logger->warning(sprintf('Username "%s" could not be found.', $e->getUsername())); } return; diff --git a/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php index 358c3c7a7c..27370694d9 100644 --- a/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php @@ -93,7 +93,7 @@ class DigestAuthenticationListener implements ListenerInterface } $serverDigestMd5 = $digestAuth->calculateServerDigest($user->getPassword(), $request->getMethod()); - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { $this->fail($event, $request, new BadCredentialsException(sprintf('Username %s not found.', $digestAuth->getUsername()))); return; diff --git a/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php b/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php index beacff301c..942e53787a 100644 --- a/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php @@ -80,12 +80,12 @@ class RememberMeListener implements ListenerInterface if (null !== $this->logger) { $this->logger->debug('SecurityContext populated with remember-me token.'); } - } catch (AuthenticationException $failed) { + } catch (AuthenticationException $e) { if (null !== $this->logger) { $this->logger->warning( 'SecurityContext not populated with remember-me token as the' .' AuthenticationManager rejected the AuthenticationToken returned' - .' by the RememberMeServices: '.$failed->getMessage() + .' by the RememberMeServices: '.$e->getMessage() ); } diff --git a/src/Symfony/Component/Security/Http/RememberMe/AbstractRememberMeServices.php b/src/Symfony/Component/Security/Http/RememberMe/AbstractRememberMeServices.php index 16f7831e7c..1ba2df677a 100644 --- a/src/Symfony/Component/Security/Http/RememberMe/AbstractRememberMeServices.php +++ b/src/Symfony/Component/Security/Http/RememberMe/AbstractRememberMeServices.php @@ -123,21 +123,21 @@ abstract class AbstractRememberMeServices implements RememberMeServicesInterface } return new RememberMeToken($user, $this->providerKey, $this->key); - } catch (CookieTheftException $theft) { + } catch (CookieTheftException $e) { $this->cancelCookie($request); - throw $theft; - } catch (UsernameNotFoundException $notFound) { + throw $e; + } catch (UsernameNotFoundException $e) { if (null !== $this->logger) { $this->logger->info('User for remember-me cookie not found.'); } - } catch (UnsupportedUserException $unSupported) { + } catch (UnsupportedUserException $e) { if (null !== $this->logger) { $this->logger->warning('User class for remember-me cookie not supported.'); } - } catch (AuthenticationException $invalid) { + } catch (AuthenticationException $e) { if (null !== $this->logger) { - $this->logger->debug('Remember-Me authentication failed: '.$invalid->getMessage()); + $this->logger->debug('Remember-Me authentication failed: '.$e->getMessage()); } } diff --git a/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php b/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php index 89bcb6faf5..de662fb3d8 100644 --- a/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php +++ b/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php @@ -41,12 +41,12 @@ class TokenBasedRememberMeServices extends AbstractRememberMeServices } try { $user = $this->getUserProvider($class)->loadUserByUsername($username); - } catch (\Exception $ex) { - if (!$ex instanceof AuthenticationException) { - $ex = new AuthenticationException($ex->getMessage(), $ex->getCode(), $ex); + } catch (\Exception $e) { + if (!$e instanceof AuthenticationException) { + $e = new AuthenticationException($e->getMessage(), $e->getCode(), $e); } - throw $ex; + throw $e; } if (!$user instanceof UserInterface) { diff --git a/src/Symfony/Component/Security/Tests/Acl/Dbal/AclProviderTest.php b/src/Symfony/Component/Security/Tests/Acl/Dbal/AclProviderTest.php index ecd53db122..7ca493f70d 100644 --- a/src/Symfony/Component/Security/Tests/Acl/Dbal/AclProviderTest.php +++ b/src/Symfony/Component/Security/Tests/Acl/Dbal/AclProviderTest.php @@ -45,11 +45,11 @@ class AclProviderTest extends \PHPUnit_Framework_TestCase $this->getProvider()->findAcls($oids); $this->fail('Provider did not throw an expected exception.'); - } catch (\Exception $ex) { - $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\AclNotFoundException', $ex); - $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\NotAllAclsFoundException', $ex); + } catch (\Exception $e) { + $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\AclNotFoundException', $e); + $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\NotAllAclsFoundException', $e); - $partialResult = $ex->getPartialResult(); + $partialResult = $e->getPartialResult(); $this->assertTrue($partialResult->contains($oids[0])); $this->assertFalse($partialResult->contains($oids[1])); } diff --git a/src/Symfony/Component/Security/Tests/Acl/Dbal/MutableAclProviderTest.php b/src/Symfony/Component/Security/Tests/Acl/Dbal/MutableAclProviderTest.php index f6d66ef115..00500f8779 100644 --- a/src/Symfony/Component/Security/Tests/Acl/Dbal/MutableAclProviderTest.php +++ b/src/Symfony/Component/Security/Tests/Acl/Dbal/MutableAclProviderTest.php @@ -88,7 +88,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase try { $provider->findAcl($oid); $this->fail('ACL has not been properly deleted.'); - } catch (AclNotFoundException $notFound) { + } catch (AclNotFoundException $e) { } } @@ -104,7 +104,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase try { $provider->findAcl(new ObjectIdentity(1, 'Foo')); $this->fail('Child-ACLs have not been deleted.'); - } catch (AclNotFoundException $notFound) { + } catch (AclNotFoundException $e) { } } @@ -290,7 +290,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase try { $provider->updateAcl($acl1); $this->fail('Provider failed to detect a concurrent modification.'); - } catch (ConcurrentModificationException $ex) { + } catch (ConcurrentModificationException $e) { } } diff --git a/src/Symfony/Component/Security/Tests/Acl/Domain/PermissionGrantingStrategyTest.php b/src/Symfony/Component/Security/Tests/Acl/Domain/PermissionGrantingStrategyTest.php index 4935bffe49..fd33f8ddb1 100644 --- a/src/Symfony/Component/Security/Tests/Acl/Domain/PermissionGrantingStrategyTest.php +++ b/src/Symfony/Component/Security/Tests/Acl/Domain/PermissionGrantingStrategyTest.php @@ -154,7 +154,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase try { $strategy->isGranted($acl, array($requiredMask), array($sid)); $this->fail('The ACE is not supposed to match.'); - } catch (NoAceFoundException $noAce) { + } catch (NoAceFoundException $e) { } } else { $this->assertTrue($strategy->isGranted($acl, array($requiredMask), array($sid))); diff --git a/src/Symfony/Component/Security/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php b/src/Symfony/Component/Security/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php index 19f6984e6f..591828f080 100644 --- a/src/Symfony/Component/Security/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php @@ -115,7 +115,7 @@ class PersistentTokenBasedRememberMeServicesTest extends \PHPUnit_Framework_Test try { $service->autoLogin($request); $this->fail('Expected CookieTheftException was not thrown.'); - } catch (CookieTheftException $theft) { + } catch (CookieTheftException $e) { } $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME)); From d29bfdcc3135e63192e2e34540a16e2f7d546beb Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 16 Jun 2015 14:17:21 +0200 Subject: [PATCH 4/6] [2.3][Debug] Fix fatal-errors handling on HHVM --- src/Symfony/Component/Debug/ErrorHandler.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Debug/ErrorHandler.php b/src/Symfony/Component/Debug/ErrorHandler.php index 1565523843..43e196242a 100644 --- a/src/Symfony/Component/Debug/ErrorHandler.php +++ b/src/Symfony/Component/Debug/ErrorHandler.php @@ -133,6 +133,7 @@ class ErrorHandler unset($context['GLOBALS']); } + $level &= E_ALL | E_STRICT; $exception = new ContextErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line), 0, $level, $file, $line, $context); // Exceptions thrown from error handlers are sometimes not caught by the exception @@ -173,7 +174,7 @@ class ErrorHandler } $this->reservedMemory = ''; - $type = $error['type']; + $type = $error['type'] & (E_ALL | E_STRICT); if (0 === $this->level || !in_array($type, array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE))) { return; } From 445de5e828cec8fdd222349839fd39bc20241cba Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 16 Jun 2015 14:15:02 +0200 Subject: [PATCH 5/6] [2.6][Debug] Fix fatal-errors handling on HHVM --- src/Symfony/Component/Debug/ErrorHandler.php | 35 +++++++++++++++---- .../Debug/Exception/FatalErrorException.php | 14 ++++++-- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/Symfony/Component/Debug/ErrorHandler.php b/src/Symfony/Component/Debug/ErrorHandler.php index 91a59058dc..f315a536ea 100644 --- a/src/Symfony/Component/Debug/ErrorHandler.php +++ b/src/Symfony/Component/Debug/ErrorHandler.php @@ -350,7 +350,7 @@ class ErrorHandler * * @internal */ - public function handleError($type, $message, $file, $line, array $context) + public function handleError($type, $message, $file, $line, array $context, array $backtrace = null) { $level = error_reporting() | E_RECOVERABLE_ERROR | E_USER_ERROR; $log = $this->loggedErrors & $type; @@ -367,6 +367,15 @@ class ErrorHandler $context = $e; } + if (null !== $backtrace && $type & E_ERROR) { + // E_ERROR fatal errors are triggered on HHVM when + // hhvm.error_handling.call_user_handler_on_fatals=1 + // which is the way to get their backtrace. + $this->handleFatalError(compact('type', 'message', 'file', 'line', 'backtrace')); + + return true; + } + if ($throw) { if (($this->scopedErrors & $type) && class_exists('Symfony\Component\Debug\Exception\ContextErrorException')) { // Checking for class existence is a work around for https://bugs.php.net/42098 @@ -402,10 +411,17 @@ class ErrorHandler if ($this->scopedErrors & $type) { $e['scope_vars'] = $context; if ($trace) { - $e['stack'] = debug_backtrace(true); // Provide object + $e['stack'] = $backtrace ?: debug_backtrace(true); // Provide object } } elseif ($trace) { - $e['stack'] = debug_backtrace(PHP_VERSION_ID >= 50306 ? DEBUG_BACKTRACE_IGNORE_ARGS : false); + if (null === $backtrace) { + $e['stack'] = debug_backtrace(PHP_VERSION_ID >= 50306 ? DEBUG_BACKTRACE_IGNORE_ARGS : false); + } else { + foreach ($backtrace as &$frame) { + unset($frame['args'], $frame); + } + $e['stack'] = $backtrace; + } } } @@ -505,7 +521,11 @@ class ErrorHandler */ public static function handleFatalError(array $error = null) { - self::$reservedMemory = ''; + if (null === self::$reservedMemory) { + return; + } + + self::$reservedMemory = null; $handler = set_error_handler('var_dump', 0); $handler = is_array($handler) ? $handler[0] : null; @@ -527,14 +547,15 @@ class ErrorHandler // Handled below } - if ($error && ($error['type'] & (E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR))) { + if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) { // Let's not throw anymore but keep logging $handler->throwAt(0, true); + $trace = isset($error['backtrace']) ? $error['backtrace'] : null; if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) { - $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false); + $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace); } else { - $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true); + $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace); } } elseif (!isset($exception)) { return; diff --git a/src/Symfony/Component/Debug/Exception/FatalErrorException.php b/src/Symfony/Component/Debug/Exception/FatalErrorException.php index d142051ba9..f46e20875a 100644 --- a/src/Symfony/Component/Debug/Exception/FatalErrorException.php +++ b/src/Symfony/Component/Debug/Exception/FatalErrorException.php @@ -35,11 +35,19 @@ use Symfony\Component\HttpKernel\Exception\FatalErrorException as LegacyFatalErr */ class FatalErrorException extends LegacyFatalErrorException { - public function __construct($message, $code, $severity, $filename, $lineno, $traceOffset = null, $traceArgs = true) + public function __construct($message, $code, $severity, $filename, $lineno, $traceOffset = null, $traceArgs = true, array $trace = null) { parent::__construct($message, $code, $severity, $filename, $lineno); - if (null !== $traceOffset) { + if (null !== $trace) { + if (!$traceArgs) { + foreach ($trace as &$frame) { + unset($frame['args'], $frame['this'], $frame); + } + } + + $this->setTrace($trace); + } elseif (null !== $traceOffset) { if (function_exists('xdebug_get_function_stack')) { $trace = xdebug_get_function_stack(); if (0 < $traceOffset) { @@ -48,7 +56,7 @@ class FatalErrorException extends LegacyFatalErrorException foreach ($trace as &$frame) { if (!isset($frame['type'])) { - // XDebug pre 2.1.1 doesn't currently set the call type key http://bugs.xdebug.org/view.php?id=695 + // XDebug pre 2.1.1 doesn't currently set the call type key http://bugs.xdebug.org/view.php?id=695 if (isset($frame['class'])) { $frame['type'] = '::'; } From 9f346a5a8d35f2176a04f5b2bf302ff0f5f3cbde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Sch=C3=B6nthal?= Date: Fri, 12 Jun 2015 23:50:21 +0200 Subject: [PATCH 6/6] Add test for HHVM FatalErrors --- .../Debug/Tests/DebugClassLoaderTest.php | 6 +++ .../Debug/Tests/ErrorHandlerTest.php | 46 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php index f720b35958..8435397f66 100644 --- a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php +++ b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php @@ -64,6 +64,9 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase if (PHP_VERSION_ID >= 70000) { $this->markTestSkipped('PHP7 throws exceptions, unsilencing is not required anymore.'); } + if (defined('HHVM_VERSION')) { + $this->markTestSkipped('HHVM is not handled in this test case.'); + } ob_start(); @@ -86,6 +89,9 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase if (class_exists('Symfony\Component\Debug\Exception\ContextErrorException', false)) { $this->markTestSkipped('The ContextErrorException class is already loaded.'); } + if (defined('HHVM_VERSION')) { + $this->markTestSkipped('HHVM is not handled in this test case.'); + } ErrorHandler::register(); diff --git a/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php b/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php index 19e7a7def7..033b1c7f72 100644 --- a/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php +++ b/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php @@ -393,6 +393,52 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase } } + public function testHandleFatalErrorOnHHVM() + { + try { + $handler = ErrorHandler::register(); + + $logger = $this->getMock('Psr\Log\LoggerInterface'); + $logger + ->expects($this->once()) + ->method('log') + ->with( + $this->equalTo(LogLevel::EMERGENCY), + $this->equalTo('Fatal Error: foo'), + $this->equalTo(array( + 'type' => 1, + 'file' => 'bar', + 'line' => 123, + 'level' => -1, + 'stack' => array(456), + )) + ) + ; + + $handler->setDefaultLogger($logger, E_ERROR); + + $error = array( + 'type' => E_ERROR + 0x1000000, // This error level is used by HHVM for fatal errors + 'message' => 'foo', + 'file' => 'bar', + 'line' => 123, + 'context' => array(123), + 'backtrace' => array(456), + ); + + call_user_func_array(array($handler, 'handleError'), $error); + $handler->handleFatalError($error); + + restore_error_handler(); + restore_exception_handler(); + } catch (\Exception $e) { + restore_error_handler(); + restore_exception_handler(); + + throw $e; + } + } + /** * @group legacy */